vibelet 1.2.238 → 1.2.240

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 (206) hide show
  1. package/README.md +32 -6
  2. package/dist/cloudflared/LICENSE +202 -0
  3. package/dist/cloudflared/manifest.json +96 -0
  4. package/dist/index.cjs +1 -1
  5. package/dist/inventory-scan-worker.cjs +1 -1
  6. package/dist/remoteDirect/vibelet-remote-direct-darwin-amd64 +0 -0
  7. package/dist/remoteDirect/vibelet-remote-direct-darwin-arm64 +0 -0
  8. package/dist/remoteDirect/vibelet-remote-direct-linux-amd64 +0 -0
  9. package/dist/remoteDirect/vibelet-remote-direct-linux-arm64 +0 -0
  10. package/dist/remoteDirect/vibelet-remote-direct-win32-amd64.exe +0 -0
  11. package/dist/remoteDirect/vibelet-remote-direct-win32-arm64.exe +0 -0
  12. package/dist/runtime-version.cjs +1 -1
  13. package/dist/vibelet.mjs +152 -28
  14. package/dist/web/assets/App-B0w50ugd.css +97 -0
  15. package/dist/web/assets/App-NMmWfGoY.js +2 -0
  16. package/dist/web/assets/BrowserControlPanel-0BJ0UEIg.js +1 -0
  17. package/dist/web/assets/ChatPane-DG_WUdJo.css +1 -0
  18. package/dist/web/assets/ChatPane-DeCnLcyQ.js +2 -0
  19. package/dist/web/assets/{ChipGroup-YMpjYR9P.js → ChipGroup-B4vUfB2t.js} +1 -1
  20. package/dist/web/assets/ComposerMenus-8RI97wiO.css +1 -0
  21. package/dist/web/assets/ComposerMenus-DzcPREkw.js +1 -0
  22. package/dist/web/assets/DiffDrawer-BznOAVqb.js +1 -0
  23. package/dist/web/assets/FilesControlPanel-Czt8c-TF.js +1 -0
  24. package/dist/web/assets/GlobalPendingDialog-DexSMOb1.js +1 -0
  25. package/dist/web/assets/ImageViewer-BQZAWRHv.js +1 -0
  26. package/dist/web/assets/{ImageViewer-Fya-Uufq.css → ImageViewer-DilwNKHW.css} +1 -1
  27. package/dist/web/assets/InteractionPolish-Nkww8pqM.css +1 -0
  28. package/dist/web/assets/{LanguageSettingsPanel-BXx4BvyU.js → LanguageSettingsPanel-CcKwfMci.js} +1 -1
  29. package/dist/web/assets/{MarkdownModePanel-VRQHdCgq.js → MarkdownModePanel-Djl7nwaJ.js} +1 -1
  30. package/dist/web/assets/MessageImage-BNOsxgJR.js +1 -0
  31. package/dist/web/assets/MessageImage-XcPrPLDn.css +1 -0
  32. package/dist/web/assets/NewSessionDialog-EXTRdgtg.js +1 -0
  33. package/dist/web/assets/NewSessionDialog-eX_6NPbk.css +1 -0
  34. package/dist/web/assets/{NotificationSettingsPanel-D78c9Tv6.js → NotificationSettingsPanel-Clp5I7Xt.js} +1 -1
  35. package/dist/web/assets/PanelFind-DtJNet9b.js +1 -0
  36. package/dist/web/assets/PanelFind-Du02CWMm.css +1 -0
  37. package/dist/web/assets/RemoteLifeOSBlock-B5kU_35n.js +2 -0
  38. package/dist/web/assets/RemoteWorkspaceSettings-DiV8YdWM.js +1 -0
  39. package/dist/web/assets/SessionTerminalPanel-CfChktgw.js +2 -0
  40. package/dist/web/assets/SpeechInputSettingsPanel-BT-RXrZI.js +1 -0
  41. package/dist/web/assets/{ThemeSettingsPanel-BAHOGS0L.js → ThemeSettingsPanel-BMeMeln2.js} +1 -1
  42. package/dist/web/assets/__vite-browser-external-2447137e-DZMxqW1v.js +1 -0
  43. package/dist/web/assets/{_baseMerge-CwDZKfvJ.js → _baseMerge-DBQbsGvS.js} +1 -1
  44. package/dist/web/assets/{_initCloneObject-C781OlVa.js → _initCloneObject-BR1zWEqJ.js} +1 -1
  45. package/dist/web/assets/abnfDiagram-VRR7QNED-DK2hMaza.js +1 -0
  46. package/dist/web/assets/arc-CzrEQYq_.js +1 -0
  47. package/dist/web/assets/architectureDiagram-ZJ3FMSHR-DZxghfRl.js +1 -0
  48. package/dist/web/assets/arrow-left-CaVb4nSl.js +1 -0
  49. package/dist/web/assets/arrow-right-BzeEEQgJ.js +1 -0
  50. package/dist/web/assets/blockDiagram-677ZJIJ3-BkA7tw-T.js +1 -0
  51. package/dist/web/assets/c4Diagram-LMCZKHZV-B7XTpVaD.js +1 -0
  52. package/dist/web/assets/channel-KKpxBoQi.js +1 -0
  53. package/dist/web/assets/chevron-up-d3Fwun7t.js +1 -0
  54. package/dist/web/assets/{chunk-2Q5K7J3B-CuStQQP5.js → chunk-2Q5K7J3B-Bss5s9E2.js} +1 -1
  55. package/dist/web/assets/{chunk-32BRIVSS-CqcvfQyF.js → chunk-32BRIVSS-CA1C0nXS.js} +1 -1
  56. package/dist/web/assets/{chunk-5VM5RSS4-ClfzIwi_.js → chunk-5VM5RSS4-BH6U7p_f.js} +1 -1
  57. package/dist/web/assets/{chunk-EX3LRPZG-km8mrFBg.js → chunk-EX3LRPZG-CcqWCMjI.js} +1 -1
  58. package/dist/web/assets/{chunk-JWPE2WC7-CwqQJZta.js → chunk-JWPE2WC7-B-4yNTb8.js} +1 -1
  59. package/dist/web/assets/{chunk-MOJQB5TN-D6HJ3YLS.js → chunk-MOJQB5TN-Bwvx3fwJ.js} +1 -1
  60. package/dist/web/assets/{chunk-RYQCIY6F-DzxL_I7L.js → chunk-RYQCIY6F-Bb4gbrTX.js} +1 -1
  61. package/dist/web/assets/{chunk-V7JOEXUC-Cx4-zn7N.js → chunk-V7JOEXUC-DKK57hpe.js} +1 -1
  62. package/dist/web/assets/{chunk-VR4S4FIN-uFIJLxCS.js → chunk-VR4S4FIN--Lw_tXW6.js} +1 -1
  63. package/dist/web/assets/{chunk-XXDRQBXY-Cg2Q6HPU.js → chunk-XXDRQBXY-BmnjnFO6.js} +1 -1
  64. package/dist/web/assets/classDiagram-OUVF2IWQ-CHHZpVy2.js +1 -0
  65. package/dist/web/assets/classDiagram-v2-EOCWNBFH-CHHZpVy2.js +1 -0
  66. package/dist/web/assets/collectMessageImages-C3-JxSH9.js +1 -0
  67. package/dist/web/assets/cose-bilkent-JH36ORCC-BxPt-mvK.js +1 -0
  68. package/dist/web/assets/{cynefin-VYW2F7L2-fGkbWpUF.js → cynefin-VYW2F7L2-XMhkQxq7.js} +1 -1
  69. package/dist/web/assets/cynefinDiagram-TSTJHNR4-Dxsg5z0o.js +1 -0
  70. package/dist/web/assets/dagre-VKFMJZFB-BTkUFd1o.js +1 -0
  71. package/dist/web/assets/diagram-FQU43EPY-C1CbNvfX.js +1 -0
  72. package/dist/web/assets/diagram-G47NLZAW-BlP_2bxX.js +1 -0
  73. package/dist/web/assets/diagram-NH7WQ7WH-QGwfazGi.js +1 -0
  74. package/dist/web/assets/diagram-OA4YK3LP-DMuz6rJC.js +1 -0
  75. package/dist/web/assets/diagram-WEI45ONY-B2xDOQNA.js +1 -0
  76. package/dist/web/assets/ebnfDiagram-CCIWWBDH-CerWiTMA.js +1 -0
  77. package/dist/web/assets/erDiagram-Q63AITRT-B-ssV3I1.js +1 -0
  78. package/dist/web/assets/{file-editor-FileCodeEditor-Cc7o0SoW.js → file-editor-FileCodeEditor-DHRDHCQw.js} +2 -2
  79. package/dist/web/assets/{file-editor-ObsidianCodeEditor-DKHh91wx.js → file-editor-ObsidianCodeEditor-DTwaAF2M.js} +1 -1
  80. package/dist/web/assets/file-editor-ObsidianFileEditor-HVqh_MR8.js +2 -0
  81. package/dist/web/assets/{file-editor-index-CylY6jN7.js → file-editor-index--NhAFrCD.js} +1 -1
  82. package/dist/web/assets/{file-editor-index-BrEnI_H0.js → file-editor-index-BhOxVDWT.js} +1 -1
  83. package/dist/web/assets/{file-editor-index-Bg9-IMrE.js → file-editor-index-BkRDu8Ih.js} +1 -1
  84. package/dist/web/assets/{file-editor-index-DBUZobR-.js → file-editor-index-BxQDEPaH.js} +1 -1
  85. package/dist/web/assets/{file-editor-index-BocbUhDf.js → file-editor-index-CEjRXkxt.js} +1 -1
  86. package/dist/web/assets/{file-editor-index-DSJHLC6d.js → file-editor-index-CTfoBHg1.js} +1 -1
  87. package/dist/web/assets/{file-editor-index-DdTlNUV4.js → file-editor-index-DIH2DQ5-.js} +1 -1
  88. package/dist/web/assets/{file-editor-index-EvPD_eNu.js → file-editor-index-D_riXMER.js} +1 -1
  89. package/dist/web/assets/{file-editor-index-DPwrStxR.js → file-editor-index-DhGjGca-.js} +1 -1
  90. package/dist/web/assets/{file-editor-index-ByGYwqNf.js → file-editor-index-YeA2vzMT.js} +1 -1
  91. package/dist/web/assets/{file-editor-index-C-F4L_uP.js → file-editor-index-_YJUu8LH.js} +1 -1
  92. package/dist/web/assets/{file-editor-index-WprjWcs8.js → file-editor-index-x-jPAG-9.js} +1 -1
  93. package/dist/web/assets/{flowDiagram-23GEKE2U-CTWUxjYj.js → flowDiagram-23GEKE2U-CK4bbOLH.js} +1 -1
  94. package/dist/web/assets/{folder-plus-Cud2L2F4.js → folder-plus-ROMRV3aa.js} +1 -1
  95. package/dist/web/assets/ganttDiagram-NO4QXBWP-BeljgJy_.js +1 -0
  96. package/dist/web/assets/git-actions-DHCQ17VG.js +1 -0
  97. package/dist/web/assets/gitGraphDiagram-IHSO6WYX-Cxm3yG2c.js +1 -0
  98. package/dist/web/assets/highlighted-body-TPN3WLV5-BQu24dd9.js +1 -0
  99. package/dist/web/assets/imageViewerCopy-DZnSk47F.js +1 -0
  100. package/dist/web/assets/{index-B3XA1dVd.css → index-B0hzMPwQ.css} +1 -1
  101. package/dist/web/assets/index-BNl2LlC5.js +1 -0
  102. package/dist/web/assets/index-D0cZ64pO.js +1 -0
  103. package/dist/web/assets/index-D0cm1aa-.js +1 -0
  104. package/dist/web/assets/{index-Dx_1eu1W.js → index-DUrY8OKv.js} +2 -2
  105. package/dist/web/assets/index-ucaYl4gM.js +1 -0
  106. package/dist/web/assets/infoDiagram-FWYZ7A6U-D1XxPfE7.js +1 -0
  107. package/dist/web/assets/ishikawaDiagram-FXEZZL3T-no1azdW5.js +1 -0
  108. package/dist/web/assets/journeyDiagram-5HDEW3XC-D69pbBkz.js +1 -0
  109. package/dist/web/assets/kanban-definition-HUTT4EX6-DF9jBMQX.js +1 -0
  110. package/dist/web/assets/{key-round-BgAVbd3A.js → key-round-Cz5tcv0j.js} +1 -1
  111. package/dist/web/assets/{layout-DvVF2R1Q.js → layout-CmMX872C.js} +1 -1
  112. package/dist/web/assets/{linear-DmQK5Nk3.js → linear-BvELtO_n.js} +1 -1
  113. package/dist/web/assets/logo-Caf1Fn81.webp +0 -0
  114. package/dist/web/assets/{map-yP9qyz-l.js → map-Dwt0FgOz.js} +1 -1
  115. package/dist/web/assets/mermaid-O7DHMXV3-DQT4ZA59.js +2 -0
  116. package/dist/web/assets/{mermaid.core-jR_k1I8D.js → mermaid.core-Cqy39_Ub.js} +2 -2
  117. package/dist/web/assets/mic-CfwPV1bx.js +1 -0
  118. package/dist/web/assets/mindmap-definition-LN4V7U3C-rUKSYXvP.js +1 -0
  119. package/dist/web/assets/pegDiagram-2B236MQR-C_nLcufF.js +1 -0
  120. package/dist/web/assets/pieDiagram-ENE6RG2P-lKOgx3ur.js +1 -0
  121. package/dist/web/assets/quadrantDiagram-ABIIQ3AL-CmD-Y89j.js +1 -0
  122. package/dist/web/assets/railroadDiagram-RFXS5EU6-BtUqJU9X.js +1 -0
  123. package/dist/web/assets/requirementDiagram-TGXJPOKE-BTuqBSlC.js +1 -0
  124. package/dist/web/assets/sankeyDiagram-HTMAVEWB-BIe_zpdG.js +1 -0
  125. package/dist/web/assets/sequenceDiagram-DBY2YBRQ-D4KPMbym.js +1 -0
  126. package/dist/web/assets/shield-check-BIUOkwl_.js +1 -0
  127. package/dist/web/assets/sizeCapture-X5ZJPWSS-CzD-vufl.js +1 -0
  128. package/dist/web/assets/stateDiagram-2N3HPSRC-C1i-TljJ.js +1 -0
  129. package/dist/web/assets/stateDiagram-v2-6OUMAXLB-km2c4PyD.js +1 -0
  130. package/dist/web/assets/swimlanes-5IMT3BWC-CNe1pOBr.js +2 -0
  131. package/dist/web/assets/swimlanesDiagram-G3AALYLV-Da0hYc5p.js +1 -0
  132. package/dist/web/assets/timeline-definition-FHXFAJF6-CMs8BbV7.js +1 -0
  133. package/dist/web/assets/useComposerCompletion-B0xUeljY.css +1 -0
  134. package/dist/web/assets/useComposerCompletion-Brvpj9zV.js +1 -0
  135. package/dist/web/assets/useMessageImage-CNR1wZjv.js +1 -0
  136. package/dist/web/assets/vennDiagram-L72KCM5P-aQDmSxcV.js +1 -0
  137. package/dist/web/assets/wardleyDiagram-EHGQE667-B77JdKDN.js +1 -0
  138. package/dist/web/assets/xychartDiagram-FW5EYKEG-RXhJfM4g.js +1 -0
  139. package/dist/web/assets/zap-CIk2VoXi.js +1 -0
  140. package/dist/web/icon.svg +1 -7
  141. package/dist/web/index.html +2 -2
  142. package/dist/web/logo.svg +1 -13
  143. package/dist/web/obsidian-editor-assets.json +1 -1
  144. package/package.json +16 -2
  145. package/scripts/install-cloudflared.mjs +58 -0
  146. package/dist/web/assets/App-C21-MM7L.js +0 -2
  147. package/dist/web/assets/App-CbEM8WX0.css +0 -1
  148. package/dist/web/assets/BrowserControlPanel-CkKIuEsj.js +0 -1
  149. package/dist/web/assets/FilesControlPanel-CwbB5lm2.js +0 -1
  150. package/dist/web/assets/GlobalPendingDialog-DqEBvP53.js +0 -1
  151. package/dist/web/assets/ImageViewer-CK5ZHIVv.js +0 -1
  152. package/dist/web/assets/NewSessionDialog-5JSvL7EJ.css +0 -1
  153. package/dist/web/assets/NewSessionDialog-CuL1-FFv.js +0 -1
  154. package/dist/web/assets/RemoteLifeOSBlock-BjYrjRa2.js +0 -2
  155. package/dist/web/assets/RemoteWorkspaceSettings-B9yBCaSU.js +0 -1
  156. package/dist/web/assets/SessionTerminalPanel-D_XqGjcx.js +0 -1
  157. package/dist/web/assets/abnfDiagram-VRR7QNED-C_g14JDy.js +0 -1
  158. package/dist/web/assets/arc-Dlh78dPq.js +0 -1
  159. package/dist/web/assets/architectureDiagram-ZJ3FMSHR-r6osYFBK.js +0 -1
  160. package/dist/web/assets/arrow-right-BtC2L5Xy.js +0 -1
  161. package/dist/web/assets/blockDiagram-677ZJIJ3-Dt1NkFp6.js +0 -1
  162. package/dist/web/assets/c4Diagram-LMCZKHZV-DgzJiNGp.js +0 -1
  163. package/dist/web/assets/channel-CoeVE6la.js +0 -1
  164. package/dist/web/assets/classDiagram-OUVF2IWQ-UcfsFNaj.js +0 -1
  165. package/dist/web/assets/classDiagram-v2-EOCWNBFH-UcfsFNaj.js +0 -1
  166. package/dist/web/assets/clsx-dhsJw0G5.js +0 -1
  167. package/dist/web/assets/collectMessageImages-ZyOAE6id.js +0 -1
  168. package/dist/web/assets/cose-bilkent-JH36ORCC-CcjvJAJB.js +0 -1
  169. package/dist/web/assets/cynefinDiagram-TSTJHNR4-Cvuw_uxU.js +0 -1
  170. package/dist/web/assets/dagre-VKFMJZFB-D07owLRU.js +0 -1
  171. package/dist/web/assets/diagram-FQU43EPY-C8yKetrQ.js +0 -1
  172. package/dist/web/assets/diagram-G47NLZAW-CM7slttO.js +0 -1
  173. package/dist/web/assets/diagram-NH7WQ7WH-CAqIaHvI.js +0 -1
  174. package/dist/web/assets/diagram-OA4YK3LP-s_8LmV3Y.js +0 -1
  175. package/dist/web/assets/diagram-WEI45ONY-DcL-hbJN.js +0 -1
  176. package/dist/web/assets/ebnfDiagram-CCIWWBDH-BiY1-WEY.js +0 -1
  177. package/dist/web/assets/erDiagram-Q63AITRT-iIeyBkVv.js +0 -1
  178. package/dist/web/assets/file-editor-ObsidianFileEditor-D4DiY_3P.js +0 -2
  179. package/dist/web/assets/ganttDiagram-NO4QXBWP-wo784lYB.js +0 -1
  180. package/dist/web/assets/gitGraphDiagram-IHSO6WYX-BY6lbwzB.js +0 -1
  181. package/dist/web/assets/highlighted-body-TPN3WLV5-CDeMvzq_.js +0 -1
  182. package/dist/web/assets/index-1M7_HtDu.js +0 -1
  183. package/dist/web/assets/index-BTavN9lk.js +0 -1
  184. package/dist/web/assets/infoDiagram-FWYZ7A6U-CfoivPz9.js +0 -1
  185. package/dist/web/assets/ishikawaDiagram-FXEZZL3T-Bt6xBkx3.js +0 -1
  186. package/dist/web/assets/journeyDiagram-5HDEW3XC-D_lKOA6h.js +0 -1
  187. package/dist/web/assets/kanban-definition-HUTT4EX6-Ce_DMiiq.js +0 -1
  188. package/dist/web/assets/logo-CVsV06Wq.webp +0 -0
  189. package/dist/web/assets/mermaid-O7DHMXV3-DKlyhw3K.js +0 -2
  190. package/dist/web/assets/mindmap-definition-LN4V7U3C-4KSBnEFJ.js +0 -1
  191. package/dist/web/assets/pegDiagram-2B236MQR-rZKZ-HjO.js +0 -1
  192. package/dist/web/assets/pieDiagram-ENE6RG2P-Fz-HbF4X.js +0 -1
  193. package/dist/web/assets/quadrantDiagram-ABIIQ3AL-G8TsEkFM.js +0 -1
  194. package/dist/web/assets/railroadDiagram-RFXS5EU6-ztb7MjCm.js +0 -1
  195. package/dist/web/assets/requirementDiagram-TGXJPOKE-4Y2Rvrbc.js +0 -1
  196. package/dist/web/assets/sankeyDiagram-HTMAVEWB-BfX7WEmV.js +0 -1
  197. package/dist/web/assets/sequenceDiagram-DBY2YBRQ-BMavjnNv.js +0 -1
  198. package/dist/web/assets/sizeCapture-X5ZJPWSS-DGkFWUNW.js +0 -1
  199. package/dist/web/assets/stateDiagram-2N3HPSRC-Bu42YWoA.js +0 -1
  200. package/dist/web/assets/stateDiagram-v2-6OUMAXLB-BwgU75NJ.js +0 -1
  201. package/dist/web/assets/swimlanes-5IMT3BWC-BGb3og3u.js +0 -2
  202. package/dist/web/assets/swimlanesDiagram-G3AALYLV-D2gngEsl.js +0 -1
  203. package/dist/web/assets/timeline-definition-FHXFAJF6-Bvzb38qw.js +0 -1
  204. package/dist/web/assets/vennDiagram-L72KCM5P-n0xgqOqd.js +0 -1
  205. package/dist/web/assets/wardleyDiagram-EHGQE667-CwAxqpRk.js +0 -1
  206. package/dist/web/assets/xychartDiagram-FW5EYKEG-B6f2c1Rw.js +0 -1
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-DKlyhw3K.js","assets/index-Dx_1eu1W.js","assets/index-B3XA1dVd.css","assets/index-BTavN9lk.js","assets/collectMessageImages-ZyOAE6id.js","assets/clsx-dhsJw0G5.js","assets/index-1M7_HtDu.js","assets/mermaid-O7DHMXV3-CgN6EJ9a.css","assets/ImageViewer-CK5ZHIVv.js","assets/arrow-right-BtC2L5Xy.js","assets/ImageViewer-Fya-Uufq.css","assets/BrowserControlPanel-CkKIuEsj.js","assets/SessionTerminalPanel-D_XqGjcx.js","assets/RemoteWorkspaceSettings-B9yBCaSU.js","assets/key-round-BgAVbd3A.js","assets/RemoteWorkspaceSettings-7jz8oX59.css","assets/FilesControlPanel-CwbB5lm2.js","assets/folder-plus-Cud2L2F4.js","assets/FilesControlPanel-DQpsZVYc.css","assets/LanguageSettingsPanel-BXx4BvyU.js","assets/ChipGroup-YMpjYR9P.js","assets/ThemeSettingsPanel-BAHOGS0L.js","assets/NotificationSettingsPanel-D78c9Tv6.js","assets/NewSessionDialog-CuL1-FFv.js","assets/NewSessionDialog-5JSvL7EJ.css","assets/MarkdownModePanel-VRQHdCgq.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-Cc7o0SoW.js","assets/file-editor-index-C6CU7Fik.js","assets/FileCodeEditor-CW9KijoU.css","assets/file-editor-ObsidianCodeEditor-DKHh91wx.js","assets/file-editor-index-Bg9-IMrE.js","assets/file-editor-index-D5fLCdey.js","assets/file-editor-index-ByGYwqNf.js","assets/file-editor-index-BOi4gj-u.js","assets/file-editor-index-wav2nO7A.js","assets/file-editor-index-DBUZobR-.js","assets/RemoteLifeOSBlock-BjYrjRa2.js","assets/RemoteLifeOSBlock-DVhFsnY2.css","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-D4DiY_3P.js","assets/purify.es-BNLkGfTg.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-CwDZKfvJ.js","assets/_initCloneObject-C781OlVa.js","assets/ObsidianFileEditor-D2QjjPA3.css","assets/GlobalPendingDialog-DqEBvP53.js"])))=>i.map(i=>d[i]);
2
- import{c as e,r as t,j as n,i as s,h as r,m as i,t as o,b as a,d as c,n as l,o as d,p as u,q as h,v as f,w as p,x as m,y as g,z as v,A as y,B as b,C as w,F as x,G as S,f as k,S as I,H as C,u as j,_ as R,D as E,E as M,I as T}from"./index-Dx_1eu1W.js";const A=e("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),N=e("archive",[["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"}]]),D=e("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),P=e("arrow-left-to-line",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]),L=e("arrow-right-to-line",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]),F=e("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),q=e("bell",[["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"}]]),O=e("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),_=e("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),$=e("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),z=e("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),H=e("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),B=e("clipboard",[["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"}]]),U=e("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),W=e("cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]),K=e("code-xml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]),V=e("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),Q=e("corner-up-right",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]),G=e("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),J=e("ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),Z=e("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),X=e("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),Y=e("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),ee=e("file-text",[["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 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),te=e("folder-open",[["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"}]]),ne=e("folder-search",[["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"}]]),se=e("folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]),re=e("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]),ie=e("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),oe=e("git-compare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]),ae=e("globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]),ce=e("hash",[["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"}]]),le=e("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]),de=e("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),ue=e("keyboard",[["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"}]]),he=e("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),fe=e("list-ordered",[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]]),pe=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),me=e("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),ge=e("message-circle",[["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"}]]),ve=e("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]),ye=e("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]),be=e("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]),we=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),xe=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),Se=e("paperclip",[["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"}]]),ke=e("pencil",[["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"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),Ie=e("pin",[["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"}]]),Ce=e("plug-zap",[["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:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]),je=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),Re=e("refresh-cw",[["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"}]]),Ee=e("rotate-ccw",[["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"}]]),Me=e("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]),Te=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),Ae=e("send",[["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"}]]),Ne=e("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),De=e("settings",[["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"}]]),Pe=e("shield-check",[["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"}]]),Le=e("sliders-horizontal",[["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"}]]),Fe=e("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]),qe=e("square-terminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]),Oe=e("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),_e=e("tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]),$e=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),ze=e("trash-2",[["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"}]]),He=e("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),Be=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ue=e("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),We="vibelet:session-workspace-change",Ke="vibelet:session-workspace-before-remove",Ve="vibelet:session-workspace-removing";function Qe(e){window.dispatchEvent(new CustomEvent(We,{detail:e}))}function Ge(e,t){window.dispatchEvent(new CustomEvent(Ve,{detail:{...e,removing:t}}))}function Je(e,t){let n;try{n=JSON.parse(e)}catch{return e}if(!Array.isArray(n)||2!==n.length)return e;if(n[0]===t.daemonId&&n[1]===t.sessionId)return"remove"===t.action?null:JSON.stringify([t.daemonId,t.nextSessionId]);if("string"!=typeof n[0])return e;const s=Je(n[0],t);return null===s?null:s===n[0]?e:JSON.stringify([s,n[1]])}function Ze(e,t){const{value:n,set:s}=Xe(e,t);return[n,s]}function Xe(e,n){const s=t.useRef(new Map),r=t.useRef([]),i=t.useCallback(e=>{let t=e;for(const n of r.current){if(null===t)break;t=Je(t,n)}return t},[]),o=i(e),a=()=>"function"==typeof n?n():n;null===o||s.current.has(o)||s.current.set(o,a());const[c,l]=t.useState(()=>new Map),d=t.useRef(c),u=t.useCallback(e=>{d.current=e,l(e)},[]),h=null===o?a():c.has(o)?c.get(o):s.current.get(o),f=t.useCallback(t=>{const n=i(e);if(null===n)return;const r=d.current,o=r.has(n)?r.get(n):s.current.get(n),a="function"==typeof t?t(o):t;Object.is(o,a)||u(new Map(r).set(n,a))},[e,i,u]),p=t.useCallback((e,t)=>{const n=i(e);null===n||Object.is(d.current.get(n),t)||u(new Map(d.current).set(n,t))},[i,u]),m=t.useCallback(e=>{const t=i(e);return null===t?void 0:d.current.has(t)?d.current.get(t):s.current.get(t)},[i]),g=t.useCallback(()=>new Map([...s.current,...d.current]),[]),v=t.useCallback(e=>{const t=g();let n=!1;for(const[s,r]of t){const i=e(r,s);i!==r&&(t.set(s,i),n=!0)}n&&u(t)},[g,u]);return t.useEffect(()=>{const e=e=>{const t=e.detail;r.current.push(t);const n=e=>{const n=new Map(e);for(const[s,r]of e){const e=Je(s,t);e!==s&&(n.delete(s),null!==e&&n.set(e,r))}return n};s.current=n(s.current),u(n(d.current))};return window.addEventListener(We,e),()=>window.removeEventListener(We,e)},[u]),{value:h,set:f,setForScope:p,getForScope:m,getAll:g,updateAll:v,resolveScope:i}}function Ye(e,t){return JSON.stringify([e??null,t??null])}function et(e,t){try{const[n,s]=JSON.parse(e),[r,i]=JSON.parse(t);return n===r&&null===s&&"string"==typeof i}catch{return!1}}const tt=t.createContext(null);function nt({children:e,scopeKey:s}){const r=function(e="default"){const n=t.useRef(null),s=t.useRef(null),r=t.useRef({browser:0,terminal:0}),[i,o]=t.useState(0),[a,c]=t.useState([]),l=a.filter(t=>(t.scopeKey??"default")===e),[d,u]=Ze(JSON.stringify([e,i]),null),[h,f]=Ze(JSON.stringify([e,i]),()=>({}));t.useEffect(()=>{const e=e=>{const t=e.detail;c(e=>e.flatMap(e=>{const n=Je(e.scopeKey??"default",t);return null===n?[]:n===(e.scopeKey??"default")?[e]:[{...e,scopeKey:n,session:e.session&&"remap"===t.action?{...e.session,sessionId:t.nextSessionId}:e.session}]}))};return window.addEventListener(We,e),()=>window.removeEventListener(We,e)},[]);const[p,m]=t.useState({}),g=t.useCallback((t,n,s,i,o,a)=>{const l=crypto.randomUUID(),d="diff"===t?"center":"right",h=n;return"diff"!==t&&(n=`${n} ${++r.current[t]}`),c(r=>[...r,{id:l,kind:t,title:n,defaultTitle:h,cwd:s,session:i,scope:o,path:a,location:d,scopeKey:e}]),"center"===d?u(l):f(e=>({...e,[t]:l})),l},[e,u,f]),v=t.useRef(new Set),y=t.useCallback((t,s)=>{const r=l.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!v.current.has(e.id)),i=r.find(e=>e.id===h.browser)??r[0],o=i?.id??crypto.randomUUID();i&&v.current.add(o),c(n=>i?n.map(e=>e.id===o?{...e,title:s,url:t,emptyPlaceholder:!1}:e):[...n,{id:o,kind:"browser",location:"right",title:s,defaultTitle:s,url:t,scopeKey:e}]),f(e=>({...e,browser:o})),n.current?.("browser",!0)},[l,h.browser,e,f]),b=t.useCallback((e,t)=>{c(n=>n.map(n=>n.id===e&&n.currentUrl!==t?{...n,currentUrl:t,emptyPlaceholder:!t&&n.emptyPlaceholder}:n))},[]),w=t.useCallback((e,t)=>{const r=l.find(t=>t.id===e);r&&(c(n=>n.map(n=>n.id===e?{...n,location:t}:n)),"center"===t?("right"!==r.location||l.some(t=>t.id!==e&&t.kind===r.kind&&"right"===t.location)||s.current?.(r.kind),u(e),f(t=>({...t,[r.kind]:l.find(t=>t.id!==e&&t.kind===r.kind&&"right"===t.location)?.id}))):(f(t=>({...t,[r.kind]:e})),n.current?.(r.kind),d===e&&u(null)))},[l,d,u,f]),x=t.useCallback(t=>{v.current.delete(t);const n=l.find(e=>e.id===t);if(!n)return;const r=l.find(e=>e.id!==t&&e.kind===n.kind&&e.location===n.location),i=r||"diff"===n.kind||"right"!==n.location&&l.some(e=>e.id!==t&&e.kind===n.kind)?void 0:{id:crypto.randomUUID(),kind:n.kind,location:"right",title:n.defaultTitle??n.title,defaultTitle:n.defaultTitle,cwd:n.cwd,scopeKey:e,autoOpenTerminal:!0,emptyPlaceholder:!0};c(e=>[...e.filter(e=>e.id!==t),...i?[i]:[]]),r||"right"!==n.location||"diff"===n.kind||s.current?.(n.kind),d===t&&u(null),(i||h[n.kind]===t)&&f(e=>({...e,[n.kind]:i?.id??r?.id}))},[l,d,h,e,u,f]),S=t.useCallback(e=>{c(t=>t.map(t=>t.id===e&&t.emptyPlaceholder?{...t,emptyPlaceholder:!1}:t))},[]),k=t.useCallback((e,t)=>c(n=>n.map(n=>n.id===e&&n.title!==t?{...n,title:t}:n)),[]),I=t.useCallback((e,t)=>m(n=>{if(n[e]===t||!n[e]&&!t)return n;const s={...n};return t?s[e]=t:delete s[e],s}),[]),C=t.useCallback(()=>{v.current.clear(),c([]),u(null),f({}),o(e=>e+1)},[u,f]);return t.useMemo(()=>({scopeKey:e,allItems:a,openRight:n,closeRight:s,openBrowser:y,updateBrowserUrl:b,activate:S,epoch:i,items:l,center:d,right:h,hosts:p,add:g,move:w,close:x,rename:k,register:I,reset:C,setCenter:u,setRight:f}),[e,a,y,b,S,i,l,d,h,p,g,w,x,k,I,C])}(s);return n.jsx(tt.Provider,{value:r,children:e})}function st(){const e=t.useContext(tt);if(!e)throw new Error("Dock workspace provider missing");return e}function rt(){return t.useContext(tt)}const it="application/x-vibelet-workspace-tab",ot="vibelet:file-operation-before",at="vibelet:file-operation-done";function ct(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,r=[];for(const i of s.split("/"))i&&"."!==i&&(".."===i?r.pop():r.push(i));return`${s.startsWith("/")?"/":""}${r.join("/")}`}function lt(e,t,n){const s=ct(e,n),r=ct(t,n);return s===r||s.startsWith(`${r}/`)}async function dt(e,t){const n=new CustomEvent(ot,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const s=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),r=await s.text();let i;try{i=JSON.parse(r)}catch{throw new Error(404===s.status||/^Vibelet Daemon v/.test(r)?"daemon_update_required":"operation_failed")}if(404===s.status&&"ENOENT"!==i.error)throw new Error("daemon_update_required");if(!s.ok)throw new Error(i.error??"operation_failed");return window.dispatchEvent(new CustomEvent(at,{detail:{...i,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),i}function ut(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function ht(e){return Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function ft(e,t={}){return ht(e)?`cd ${ut(e.cwd||".")} && ${function(e,t={}){if(!ht(e))return"";const n=e.approvalMode??e.observedApprovalMode,s="claude"===e.agent?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId],r=t.codexBackend??e.runtime?.codexBackend;return"codex"!==e.agent||"standalone"!==r&&(r||"@vibelet/cli"!==e.originator)||s.push("--no-daemon"),"autoApprove"===n?s.push("claude"===e.agent?"--dangerously-skip-permissions":"--dangerously-bypass-approvals-and-sandbox"):"claude"===e.agent&&"acceptEdits"===n&&s.push("--permission-mode","acceptEdits"),[...t.vibeletChannel?["npx",`vibelet@${t.vibeletChannel}`]:[],...s].map(ut).join(" ")}(e,t)}`:""}const pt="vibelet.web.notificationSettings",mt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function gt(e=s()){try{const t=e.getItem(pt);if(!t)return{...mt};const n=JSON.parse(t);return gn(n)?{enabled:"boolean"==typeof n.enabled?n.enabled:mt.enabled,approvals:"boolean"==typeof n.approvals?n.approvals:mt.approvals,questions:"boolean"==typeof n.questions?n.questions:mt.questions,replies:"boolean"==typeof n.replies?n.replies:mt.replies,hiddenOnly:"boolean"==typeof n.hiddenOnly?n.hiddenOnly:mt.hiddenOnly}:{...mt}}catch{return{...mt}}}function vt(e=("undefined"==typeof Notification?void 0:Notification)){return r().notifications?r().notifications.permission():e?.permission??"unsupported"}function yt(e){if(Number.isFinite(Date.parse(e.timestamp??"")))return e;const t=e.localClientMessageId??e.historyKey?.match(/^client:(.+)$/)?.[1],n=t?.match(/^(?:msg|cmd_msg)_([0-9a-z]+)_[0-9a-z]+$/)?.[1];if(!n)return e;const s=Number.parseInt(n,36);return!Number.isSafeInteger(s)||s<=0||!Number.isFinite(new Date(s).getTime())?e:{...e,timestamp:new Date(s).toISOString()}}function bt(e,t){return t?.length?e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e}function wt(e,t){const n={...e,...t};return!Number.isFinite(Date.parse(t.timestamp??""))&&Number.isFinite(Date.parse(e.timestamp??""))&&(n.timestamp=e.timestamp),n}function xt(e){return"user"===e.role?bt(e.content,e.images):e.content}function St(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&xt(e)===xt(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function kt(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"user"!==e.role||"user"!==t.role||!St(e,t))return!1;const n=Date.parse(e.timestamp??""),s=Date.parse(t.timestamp??"");return Number.isFinite(n)&&Number.isFinite(s)&&s>=n-1e3}function It(e,t){if(e.historyKey&&t.historyKey)return e.historyKey===t.historyKey;const n=e.timestamp?Date.parse(e.timestamp):NaN;return Number.isFinite(n)&&n>0&&n===Date.parse(t.timestamp??"")&&St(e,t)}function Ct(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function jt(e,t,n){let s=e.map(yt);const r=new Set,i=s.flatMap((e,t)=>e.localClientMessageId&&e.historyKey?.startsWith("client:")?[t]:[]),o=new Map;i.length&&s.forEach((e,t)=>{const n=Date.parse(e.timestamp??"");if(e.historyKey?.startsWith("client:")||!Number.isFinite(n))return;const s=`${e.role}:${n}`,r=o.get(s)??[];r.push(t),o.set(s,r)});for(const d of t){const e=o.get(`${d.role}:${Date.parse(d.timestamp??"")}`)?.find(e=>It(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=i.find(e=>!r.has(e)&&kt(s[e],d)&&Date.parse(s[e].timestamp)<=Date.parse(d.timestamp));if(void 0===t)continue;const n=s[e].historyKey;s[e]={...s[t],...s[e],localDelivery:"delivered"},n||delete s[e].historyKey,r.add(t)}r.size&&(s=s.filter((e,t)=>!r.has(t)));const a=new Map,c=[];s.forEach((e,t)=>{e.historyKey&&!a.has(e.historyKey)&&a.set(e.historyKey,t),e.historyKey&&!e.historyKey.startsWith("client:")||c.push(t)});const l=new Set;for(const d of t){const e=d.historyKey?a.get(d.historyKey)??-1:-1;if(e>=0){d.delivery&&(s[e]={...wt(s[e],d),localDelivery:"delivered"}),n?.(d,s[e]);continue}const t=(d.historyKey?c:s.map((e,t)=>t)).find(e=>{const t=s[e];return!l.has(e)&&(!!It(t,d)||!!kt(t,d)||!(t.historyKey&&!t.historyKey.startsWith("client:"))&&(t.liveReply&&(e===s.length-1||s.slice(e+1).every(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")))&&"assistant"===d.role&&"info"!==d.type?t.content.length>0&&d.content.startsWith(t.content):Boolean(d.historyKey&&!d.historyKey.startsWith("client:")&&t.historyKey?.startsWith("client:")&&"user"===t.role&&e===Ct(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&St(t,d))))})??-1;if(t<0)d.historyKey&&a.set(d.historyKey,s.length),d.historyKey&&!d.historyKey.startsWith("client:")||c.push(s.length),s.push({...d});else{l.add(t);const e=s[t].historyKey;e&&e!==d.historyKey&&a.delete(e);const r=!d.historyKey&&kt(s[t],d);s[t]=wt(s[t],d),r&&(delete s[t].historyKey,s[t].localDelivery="delivered"),s[t].historyKey&&a.set(s[t].historyKey,t),s[t].localClientMessageId&&d.historyKey&&!d.historyKey.startsWith("client:")&&(s[t].localDelivery="delivered"),delete s[t].liveReply,n?.(d,s[t])}}return s}function Rt(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function Et(e,t){if(!t?.trim())return e.slice();let n=-1;for(let a=e.length-1;a>=0;a--)if("user"===e[a]?.role){n=a;break}const s=[];for(let a=n+1;a<e.length;a++)"assistant"===e[a]?.role&&"info"!==e[a]?.type&&s.push(a);const r=s.at(-1),i=void 0!==r&&e.slice(r+1).some(e=>"tool"===e.role);let o=t;for(const a of s){if(a===r&&!i)break;const t=e[a].content;if(t.trim().startsWith(o.trim()))return e.slice();if(!t||!o.startsWith(t))break;if(o=o.slice(t.length),!o.trim())return e.slice()}if(void 0!==r&&!i){const t=e[r],n=t.content.trim().startsWith(o.trim())?t.content:o,s=e.slice();return s[r]={...t,content:n},Rt(s)}return Rt([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function Mt(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function Tt(e,t){return!t||e.length<2?e:e.map((e,n)=>({session:e,index:n,regularIndex:t[e.sessionId]})).sort((e,t)=>("number"==typeof e.regularIndex&&Number.isFinite(e.regularIndex)?e.regularIndex:Number.POSITIVE_INFINITY)-("number"==typeof t.regularIndex&&Number.isFinite(t.regularIndex)?t.regularIndex:Number.POSITIVE_INFINITY)||e.index-t.index).map(({session:e})=>e)}function At(e){return e.length<2?e:e.map((e,t)=>({session:e,index:t,activityAt:Date.parse(e.lastActivityAt)})).sort((e,t)=>{const n=Number.isFinite(e.activityAt),s=Number.isFinite(t.activityAt);return n&&s&&e.activityAt!==t.activityAt?t.activityAt-e.activityAt:n!==s?n?-1:1:(t.session.pinnedAt??0)-(e.session.pinnedAt??0)||e.index-t.index}).map(({session:e})=>e)}function Nt(e,t,n){if(0===t.length)return e;const s=new Set(t),r=[];for(const i of t){const e=n.get(i);e&&r.push(e)}for(const i of e)s.has(i.sessionId)||r.push(i);if(r.length!==e.length)return r;for(let i=0;i<e.length;i+=1)if(r[i]!==e[i])return r;return e}function Dt(e,t=Date.now(),n=i){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const r=t-s,o=36e5,a=24*o;return r<6e4?n.timeNow:r<o?n.timeMinutesAgo(Math.floor(r/6e4)):r<a?n.timeHoursAgo(Math.floor(r/o)):n.timeDaysAgo(Math.floor(r/a))}function Pt(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}const Lt="<oai-mem-citation>";function Ft(e){let t,n=0;for(const s of e.split("\n")){const r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(r){const e=r[1][0];t?e===t.marker&&r[1].length>=t.length&&!r[2].trim()&&(t=void 0):t={marker:e,length:r[1].length}}else if(!t){const t=s.replace(/^ {0,3}/,""),r=t.startsWith("<oai-mem")&&Lt.startsWith(t);if(t.startsWith(Lt)||r){const t=e.slice(n).trimStart(),s=t.indexOf("</oai-mem-citation>");if(s<0||!t.slice(s+19).trim())return e.slice(0,n).trimEnd()}}n+=s.length+1}return e}const qt=e=>e.replace(/\r\n?/g,"\n").trim(),Ot=/^\[Attached image: ([^\n]+)\]$/gm;function _t(e){return"codex"===e?"Codex":"claude"===e?"Claude":e}function $t(e){const t=[],n=new Set;for(const s of e.matchAll(Ot)){const e=s[1];e&&0!==e.trim().length&&!n.has(e)&&(n.add(e),t.push(e))}return t}function zt(e,t){if("assistant"===e.type)return qt(e.content);const n=qt(function(e){return e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").replace(/\n{3,}/g,"\n\n").trim()}(e.content)),s=function(e){const t=new Set,n=[];for(const s of e)0===s.trim().length||t.has(s)||(t.add(s),n.push(s));return n}([...$t(e.content),...e.images??[]]).map(e=>`- ${t.attachedImage}: \`${e}\``);return n&&s.length>0?`${n}\n\n${s.join("\n")}`:n||s.join("\n")}const Ht="pair",Bt="vibelet.web.pairing",Ut="vibelet.web.deviceId";class Wt extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function Kt(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Vt(e){const[t,n,s,r,i,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:"relay"===t?"relay":"direct",host:n,port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function Qt(e){if(!Kt(e))return null;const{kind:t,host:n,port:s,source:r,stability:i,secure:o}=e;return"direct"!==t&&"relay"!==t||"string"!=typeof n||!n.trim()||"number"!=typeof s||!Number.isFinite(s)||s<=0||"string"!=typeof r||"string"!=typeof i?null:{kind:t,host:n.trim(),port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function Gt(e){const t=e.trim().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"").toLowerCase();if("localhost"===t||t.endsWith(".localhost"))return!0;if("::1"===t||"0:0:0:0:0:0:0:1"===t)return!0;const n=t.split(".");if(4!==n.length||n.some(e=>!/^\d+$/.test(e)))return!1;const s=n.map(Number);return s.every(e=>e>=0&&e<=255)&&127===s[0]}function Jt(e,t){return"https:"===t.protocol&&!0!==e.secure?null:`${!0===e.secure?"wss":"ws"}://${function(e){const t=e.trim();return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}(e.host)}:${e.port}`}function Zt(e){return function(e){const t=e.trim().split(".");if(4!==t.length)return!1;const n=t.map(e=>/^\d+$/.test(e)?Number(e):Number.NaN);if(n.some(e=>!Number.isInteger(e)||e<0||e>255))return!1;const[s,r]=n;return 10===s||172===s&&r>=16&&r<=31||192===s&&168===r}(e.host)?0:"local_network"===e.source?1:"configured_host"===e.source?2:3}function Xt(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||"number"!=typeof n||!Number.isFinite(n))return[];const r=Math.floor(n);return[{kind:"direct",host:s,port:r,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(e=>({kind:"direct",host:e,port:r,source:"fallback",stability:"stable"}))]}function Yt(e,t,n=window.location,s=!0){if(s&&Gt(n.hostname))return;const r=[...t?.connections??[],...e.connections??[],...Xt(e,t)].map(Qt).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>Zt(e)-Zt(t));for(const i of r){const e=Jt(i,n);if(e)return e}}function en(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Ht);if(!n)return null;try{const e=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(4*Math.ceil(t.length/4),"=");return decodeURIComponent(Array.from(atob(n),e=>`%${e.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}(n));if(!Kt(e))return null;if("vp"===e.t)return function(e){if(!e.d||!e.c)return null;const t=Array.isArray(e.o)?e.o.map(Vt).filter(e=>Boolean(e)):void 0;return{daemonId:e.d,pairNonce:e.c,...e.n?{displayName:e.n}:{},...e.h?{canonicalHost:e.h}:{},...Number.isFinite(e.p)?{port:e.p}:{},...Array.isArray(e.f)?{fallbackHosts:e.f.filter(e=>"string"==typeof e)}:{},...t?.length?{connections:t}:{},...e.e?{expiresAt:e.e}:{}}}(e);if("vibelet-pair"===e.type)return function(e){return e.daemonId&&e.pairNonce?{daemonId:e.daemonId,displayName:e.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:e.port,connections:e.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt}:null}(e)}catch{return null}return null}function tn(e){const t=e.getItem(Bt);if(!t)return null;try{const e=JSON.parse(t);return e.daemonId&&e.deviceId&&e.pairToken?{daemonId:e.daemonId,displayName:e.displayName,deviceId:e.deviceId,pairToken:e.pairToken,pairedAt:e.pairedAt??(new Date).toISOString(),webSocketUrl:"string"==typeof e.webSocketUrl?e.webSocketUrl:void 0}:null}catch{return null}}function nn(e){if("undefined"==typeof window)return null;try{return e===s()?window.sessionStorage:null}catch{return null}}function sn(e=s(),t=nn(e)){const n=tn(e);if(n)return n;const r=t?tn(t):null;return r?(e.setItem(Bt,JSON.stringify(r)),t?.removeItem(Bt),r):null}function rn(e,t=s(),n=nn(t)){t.setItem(Bt,JSON.stringify(e)),n?.removeItem(Bt)}function on(e=s(),t=nn(e)){e.removeItem(Bt),t?.removeItem(Bt)}async function an(e,t){try{return await async function(e,t=function(e=s()){const t=e.getItem(Ut);if(t)return t;const n="function"==typeof crypto.randomUUID?crypto.randomUUID():`web_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;return e.setItem(Ut,n),n}()){if(function(e,t=Date.now()){if(!e.expiresAt)return!1;const n=new Date(e.expiresAt).getTime();return Number.isFinite(n)&&n<t}(e))throw new Wt("pair_window_expired","Pairing link expired.");const n=await fetch("/pair/create",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({daemonId:e.daemonId,pairNonce:e.pairNonce,deviceId:t,deviceName:"Vibelet Web"})});if(!n.ok)throw await async function(e){const t=await e.text().catch(()=>"");try{const e=JSON.parse(t);if(Kt(e)&&"pair_window_expired"===e.error)return new Wt("pair_window_expired","Pairing link expired.")}catch{}return new Wt("pairing_failed",t||"Pairing failed.")}(n);const r=await n.json();return{daemonId:r.daemonId,displayName:r.displayName||e.displayName,deviceId:r.deviceId,pairToken:r.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:Yt(e,r,window.location,!0)}}(e,t?.deviceId)}catch(n){if(n instanceof Wt&&"pair_window_expired"===n.code&&t?.daemonId===e.daemonId)return t;throw n}}class cn{timer=null;sentAt=null;listeners=new Set;value=null;subscribe(e){return this.listeners.add(e),e(this.value),()=>{this.listeners.delete(e)}}start(e,t){this.stop();const n=()=>{if(null!==this.sentAt)return this.stop(),void t();this.sentAt=performance.now(),e()};n(),this.timer=setInterval(n,3e4)}acknowledge(){if(null===this.sentAt)return;const e=Math.max(0,Math.round(performance.now()-this.sentAt));this.sentAt=null,this.publish(e)}stop(){null!==this.timer&&clearInterval(this.timer),this.timer=null,this.sentAt=null,this.publish(null)}publish(e){this.value=e,this.listeners.forEach(t=>t(e))}}class ln extends Error{name="VibeletRequestRejectedError"}class dn extends Error{name="VibeletRequestTimeoutError"}function un(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class hn{heartbeat=new cn;onLatency=e=>this.heartbeat.subscribe(e);capabilities={};socket=null;authenticated=!1;authentication=null;pending=new Map;messageListeners=new Set;closeListeners=new Set;connect(e){this.disconnect();const t=this.openAuthenticatedSocket(e);return this.authentication=t,t}async openAuthenticatedSocket(e){const t=new WebSocket(function(e,t=window.location,n=!0){const s=`${"https:"===t.protocol?"wss:":"ws:"}//${t.host}`;return n&&Gt(t.hostname)?s:e?.webSocketUrl?e.webSocketUrl:s}(e));let n;this.socket=t;const s=new Promise((e,s)=>{n=s,t.onopen=()=>e(),t.onerror=()=>s(new Error("WebSocket connection failed."))});if(t.onmessage=e=>{this.socket===t&&this.handleSocketMessage(e.data)},t.onclose=()=>{n(new Error("WebSocket disconnected.")),this.socket===t&&(this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.socket=null,this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(e=>e()))},await s,this.socket!==t)throw new Error("WebSocket disconnected.");const r=await this.requestOnSocket({action:"auth.hello",id:un("auth"),pairToken:e.pairToken,daemonId:e.daemonId,deviceId:e.deviceId,locale:navigator.language});if(this.socket!==t)throw new Error("WebSocket disconnected.");return this.authenticated=!0,this.capabilities=r.capabilities??{},this.heartbeat.start(()=>t.send(JSON.stringify({action:"ping"})),()=>t.close()),r}async request(e,t={}){const n=this.socket;if(!this.authenticated){if(!this.authentication)throw new Error("WebSocket is not connected.");await this.authentication}if(this.socket!==n||!this.isConnected)throw new Error("WebSocket disconnected.");return this.requestOnSocket(e,t)}requestOnSocket(e,t={}){return this.socket&&this.socket.readyState===WebSocket.OPEN?new Promise((n,s)=>{const r={action:e.action,resolve:n,reject:s};t.timeoutMs&&t.timeoutMs>0&&(r.timeoutId=setTimeout(()=>{this.pending.delete(e.id),s(new dn(t.timeoutMessage||`Request timed out (${e.action}).`))},t.timeoutMs)),this.pending.set(e.id,r),this.socket?.send(JSON.stringify(e))}):Promise.reject(new Error("WebSocket is not connected."))}send(e){this.isConnected&&this.socket?.send(JSON.stringify(e))}onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}get supportsSessionSteer(){return this.isConnected&&!0===this.capabilities.sessionSteer}get supportsQueueSendNow(){return this.isConnected&&!0===this.capabilities.queueSendNow}get supportsDirectoryWatch(){return this.isConnected&&!0===this.capabilities.directoryWatch}disconnect(){this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.capabilities={},this.rejectPending(new Error("WebSocket disconnected."));const e=this.socket;this.socket=null,e?.close(1e3,"client disconnect")}get isConnected(){return this.authenticated&&this.socket?.readyState===WebSocket.OPEN}makeId(e){return un(e)}handleSocketMessage(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}if("pong"!==t.type){if("error"===t.type&&!t.sessionId){const e=/unsupported action "([^"]+)"/.exec(t.message)?.[1];if(e){let n=!1;for(const[s,r]of this.pending)r.action===e&&(this.pending.delete(s),r.timeoutId&&clearTimeout(r.timeoutId),r.reject(new ln(t.message)),n=!0);if(n)return}}if("response"===t.type){const e=this.pending.get(t.id);if(e)return this.pending.delete(t.id),e.timeoutId&&clearTimeout(e.timeoutId),void(t.ok?e.resolve(t.data):e.reject(new ln(t.error||"Request failed.")))}this.messageListeners.forEach(e=>e(t))}else this.heartbeat.acknowledge()}rejectPending(e){for(const t of this.pending.values())t.timeoutId&&clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}}function fn(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;return"string"==typeof t.lastActivityAt&&"string"==typeof t.sessionId?{lastActivityAt:t.lastActivityAt,sessionId:t.sessionId}:void 0}const pn=".",mn="normal";function gn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function vn(e){if(!Number.isFinite(e))return"unknown";const t=e??0;return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1048576).toFixed(1)} MB`}function yn(e,t){const n=e[e.length-1];return"assistant"===n?.role&&"info"!==n.type?[...e.slice(0,-1),{...n,content:`${n.content}${t}`}]:[...e,{role:"assistant",content:t,timestamp:(new Date).toISOString()}]}function bn(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:fn(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function wn(e){return e.split("/").filter(Boolean).at(-1)??e}function xn(e){return 0===Object.entries(e).length?"No structured input.":JSON.stringify(e,null,2)}function Sn(e){return Object.fromEntries(e.questions.map(e=>[e.id,e.options[0]?[e.options[0].label]:[]]))}function kn(e){return e.trim()||void 0}function In(e){const t=864e5;return"7d"===e?Date.now()-7*t:"30d"===e?Date.now()-30*t:"90d"===e?Date.now()-90*t:void 0}function Cn(e,t){const n=new Map;for(const s of e)n.set(s.sessionId,s);for(const s of t){const e=n.get(s.sessionId),t=e&&(s.cwd!==e.cwd||Object.hasOwn(s,"branch")&&s.branch!==e.branch);n.set(s.sessionId,{...e,...t?{pullRequest:void 0,branchUrl:void 0,branch:void 0,diffStat:void 0}:{},...s,interruptReason:s.interruptReason,stallWarning:s.stallWarning})}return Array.from(n.values()).sort((e,t)=>{const n=e.pinned?e.pinnedAt??0:0,s=t.pinned?t.pinnedAt??0:0;return n!==s?s-n:Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)})}let jn=0;function Rn(e,t,n=(new Date).toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function En(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...r}=e;return{...r,[n]:s}}function Mn(e,t,n){if(!t||!n||t===n||!e.has(t))return e;const s=new Set(e);return s.delete(t),s.add(n),s}function Tn(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n&&"."!==n?`${n}/${t}`:t}function An(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(!t||"/"===t||"~"===t||"."===t)return null;const n=t.lastIndexOf("/");return n<0?".":0===n?"/":t.slice(0,n)}function Nn(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Dn(e,t,n=window.location.origin){const s=new URL("/file",n);return s.searchParams.set("path",e),t&&s.searchParams.set("cwd",t),s.toString()}function Pn(e,t){return e.get(t)||void 0}function Ln(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":a(c().language);return"en"===e?"Computer features are free. Update Vibelet on the paired computer and reconnect.":"zh-TW"===e?"電腦端功能免費。請更新配對電腦上的 Vibelet,再重新連線。":"电脑端功能免费。请更新配对电脑上的 Vibelet,再重新连接。"}return"skillNotFound"===e?"Skill not found on the paired computer.":"skillResolveFailed"===e?"Could not load the skill on the paired computer.":e}const Fn=t.createContext(null),qn=()=>t.useContext(Fn);function On({workspace:e,children:s}){const[i,o]=Ze(Ye(e.pairing?.daemonId,e.activeSessionId),void 0),a=t.useCallback((t,n=e.cwd)=>{const s=ct(t,n);o({path:s}),e.setControlTabAndOpen("files"),e.listDirectory(An(s)??n,{updateRoute:!0})},[e.cwd,e.listDirectory,e.setControlTabAndOpen,o]),c=t.useMemo(()=>({request:i,reveal:a}),[i,a]);return n.jsx(Fn.Provider,{value:"desktop"===r().kind?c:null,children:s})}async function _n(e){const t=r().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e))}catch{}const n=document.activeElement,s=window.getSelection(),i=s?Array.from({length:s.rangeCount},(e,t)=>s.getRangeAt(t).cloneRange()):[],o=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd,n.selectionDirection]:void 0,a=document.createElement("textarea");a.value=e,a.setAttribute("readonly",""),a.style.position="fixed",a.style.opacity="0",document.body.append(a);try{if(a.focus({preventScroll:!0}),a.select(),!document.execCommand("copy"))throw new Error("Clipboard copy was rejected")}finally{if(a.remove(),n instanceof HTMLElement&&n.focus({preventScroll:!0}),o&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&null!==o[0]&&null!==o[1]&&n.setSelectionRange(o[0],o[1],o[2]??void 0),s){s.removeAllRanges();for(const e of i)s.addRange(e)}}}const $n="vibelet.web.savedTargets";function zn(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e))return null;if("string"!=typeof e.daemonId||"string"!=typeof e.deviceId||"string"!=typeof e.pairToken||"string"!=typeof e.pairedAt)return null;const t="string"==typeof e.displayName?e.displayName:void 0,n="string"==typeof e.label&&e.label.trim()?e.label.trim():t||e.daemonId.slice(0,10);return{daemonId:e.daemonId,deviceId:e.deviceId,pairToken:e.pairToken,pairedAt:e.pairedAt,displayName:t,webSocketUrl:"string"==typeof e.webSocketUrl?e.webSocketUrl:void 0,label:n,lastConnectedAt:"string"==typeof e.lastConnectedAt?e.lastConnectedAt:void 0}}function Hn(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=zn(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function Bn(e=s()){const t=e.getItem($n);if(!t)return[];try{return Hn(JSON.parse(t))}catch{return[]}}function Un(e,t=s()){t.setItem($n,JSON.stringify(Hn(e)))}const Wn={version:"",latestVersion:"",loading:!1,error:null};function Kn(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Vn(e,t){return function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(Kn),s=t.split(/[+-]/,1)[0].split(".").map(Kn),r=Math.max(n.length,s.length);for(let i=0;i<r;i+=1){const e=n[i]??0,t=s[i]??0;if(e<t)return-1;if(e>t)return 1}return 0}(e,t)<0}const Qn="vibelet.web.sessionListCache";function Gn(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e)||"string"!=typeof e.daemonId||!e.daemonId)return null;const t=bn(e.page);return{daemonId:e.daemonId,page:{...t,sessions:t.sessions.slice(0,120)},cachedAt:"string"==typeof e.cachedAt?e.cachedAt:new Date(0).toISOString()}}function Jn(e){try{const t=JSON.parse(e.getItem(Qn)||"null");return(Array.isArray(t)?t:[t]).map(Gn).filter(e=>null!==e).slice(0,8)}catch{return[]}}function Zn(e){return e instanceof Error&&"auth_failed"===e.message}const Xn="vibelet.web.composerDrafts",Yn={draftsBySessionId:{},newSessionDraft:""};function es(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function ts(e){return es(e)?{draftsBySessionId:es(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:Yn}function ns(e=s()){const t=e.getItem(Xn);if(!t)return Yn;try{return ts(JSON.parse(t))}catch{return Yn}}function ss(e,t=s()){t.setItem(Xn,JSON.stringify(ts(e)))}function rs(e,t,n){if(!t)return{...e,newSessionDraft:n};const s={...e.draftsBySessionId};return n.trim()?s[t]=n:delete s[t],{...e,draftsBySessionId:s}}function is(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function os(e){switch(e instanceof Error?e.message:String(e)){case"The active turn changed before guidance was accepted":return"turn-changed";case"Claude turn is no longer active":case"Session has no active turn to guide":return"no-active-turn";case"Session is not ready to send queued messages":case"Codex turn is not ready to accept steering input":return"not-ready";case"Selected queued messages are no longer available":case"Queued message is no longer available for guiding":return"stale-selection";case"Resolve the pending request before guiding this turn":case"Resolve the pending request before sending queued messages":return"pending-request";case"The active driver does not support guiding a running turn":return"unsupported";default:return null}}function as(e){const t=e.toLowerCase();return/subscription|required|upgrade|billing/u.test(t)?"subscription":/skillnotfound|not found|missing/u.test(t)?"missing-resource":/permission|forbidden|unauthorized|denied/u.test(t)?"permission":/failed to reconnect|startup deadline exceeded/u.test(t)?"reconnect":/timeout|timed out/u.test(t)?"timeout":/process exited|reconnected concurrently/u.test(t)?"reconnect":/websocket|network|disconnect|connection|offline|closed/u.test(t)?"network":"unknown"}const cs=13e4;function ls(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function ds(e,t,n){return t&&0!==n.length?{...e,[t]:jt(e[t]??[],n)}:e}function us(e,t){const n=new Map,s=jt(e,t,(e,t)=>{t.localClientMessageId&&n.set(e,t)}),r=t.map(e=>{const t=n.get(e);return t?{...e,timestamp:Number.isFinite(Date.parse(e.timestamp??""))?e.timestamp:t.timestamp,localClientMessageId:t.localClientMessageId,localDelivery:t.localDelivery}:{...e}}),i=new Set(r.map(e=>e.localClientMessageId));return function(e,t,n){const s=e.map(e=>{if(e.liveReply){const t=n.slice().reverse().find(t=>t.liveReply&&t.content.length>0&&(e.content.startsWith(t.content)||t.content.startsWith(e.content)));if(t?.timestamp)return{...e,timestamp:t.timestamp}}return e});for(const r of t){const e=Date.parse(r.timestamp??"");let t=Number.isFinite(e)?s.findIndex(t=>{const s=Date.parse(t.timestamp??"");if(s!==e)return s>e;if("assistant"!==t.role)return!1;const i=n.findIndex(e=>t.historyKey&&e.historyKey===t.historyKey||t.liveReply&&e.liveReply&&e.timestamp===t.timestamp);return i<0||n.indexOf(r)<i}):-1;if(!Number.isFinite(e)){const e=n.indexOf(r),i=n.slice(e+1);if(t=s.findIndex(e=>i.some(t=>t===e||t.historyKey&&t.historyKey===e.historyKey)),t<0){const r=n.slice(0,e);t=s.findLastIndex(e=>r.some(t=>t===e||t.historyKey&&t.historyKey===e.historyKey))+1}}s.splice(t<0?s.length:t,0,r)}return s}(r,s.filter(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")&&!i.has(e.localClientMessageId)),e)}function hs(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}async function fs(e){return{[e]:"desktop-free"}}const ps={en:{mode:"Default send mode",queue:"Queue",queueHelp:"Wait until the current turn finishes.",guide:"Guide",guideHelp:"Guide the active turn; queue when unavailable.",unsupported:"This daemon does not support guidance; the message remains queued."},zh:{mode:"默认发送方式",queue:"排队",queueHelp:"等待当前回合完成后发送。",guide:"引导",guideHelp:"引导当前回合,暂不可用时排队。",unsupported:"此服务不支持引导,消息已保留在队列。"},"zh-TW":{mode:"預設傳送方式",queue:"排隊",queueHelp:"等待目前回合完成後傳送。",guide:"引導",guideHelp:"引導目前回合,暫不可用時排隊。",unsupported:"此服務不支援引導,訊息已保留在佇列。"}};function ms(){return ps[a(c().language)]}async function gs(e,t,n,s){const i=c(),o="desktop"===r().kind&&"guide"===i.composer.sendMode,a=await e.request(t,n);if(!o||!gn(a)||!0!==a.queued)return a;const l=ms();try{if(!e.supportsSessionSteer)throw new Error(l.unsupported);await e.request({action:"session.steer",id:e.makeId("guide"),sessionId:"string"==typeof a.sessionId?a.sessionId:t.sessionId,clientMessageId:t.clientMessageId,message:t.message,images:t.images},n)}catch(d){s(`${l.guide}: ${d instanceof Error?d.message:String(d)}`)}return a}function vs(){let e=[];const t=new Set,n=new Set,s=()=>{e=[...t].map(e=>({...e})),n.forEach(e=>e())};return{getSnapshot:()=>e,has:e=>[...t].some(t=>t.sessionId===e),subscribe:e=>(n.add(e),()=>{n.delete(e)}),start(e){const n={sessionId:e};return t.add(n),s(),{remap(e){t.has(n)&&(n.sessionId=e,s())},finish(){t.delete(n)&&s()}}}}}const ys=/^[A-Za-z][A-Za-z0-9_-]*$/,bs=[{name:"clear",commandName:"clear",title:"Clear session",description:"Clear this session in place.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"new",commandName:"new",title:"New session",description:"Start a fresh session with the same assistant and directory.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"exit",commandName:"exit",title:"Archive session",description:"Archive this session and return to the session list.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"quit",commandName:"exit",title:"Archive session",description:"Alias for /exit.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"q",commandName:"exit",title:"Archive session",description:"Alias for /exit.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"compact",commandName:"compact",title:"Compact context",description:"Ask the assistant runtime to compact the current session.",source:"Native",agents:["claude","codex"],argsHint:""},{name:"goal",commandName:"goal",title:"Goal",description:"View, set, pause, resume, or clear the current goal.",source:"Native",agents:["claude","codex"],argsHint:"[objective|status|pause|resume|clear]"}];function ws(e){return bs.filter(t=>!e||t.agents.includes(e))}function xs(e){return e.trim().toLowerCase()}function Ss(e){if(!e.startsWith("/")||e.startsWith("//"))return null;const t=/^\/([A-Za-z0-9_-]*)$/.exec(e);if(!t)return null;const n=t[1]??"";return n&&!ys.test(n)?null:{start:0,end:e.length,keyword:xs(n)}}function ks(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function Is(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),r=Boolean(e.argsHint&&!n);return`/${e.name}${r||s?" ":""}`}function Cs(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const s=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!s)return null;const r=xs(s[1]??""),i=ws(t).find(e=>e.name===r);if(!i)return null;const o=s[2]?.trim()??"";switch(i.commandName){case"clear":return{raw:n,command:{name:"clear"}};case"new":return{raw:n,command:{name:"new"}};case"exit":return{raw:n,command:{name:"exit"}};case"compact":return{raw:n,command:{name:"compact"}};case"goal":{const e=o.toLowerCase();return o&&"status"!==e&&"show"!==e&&"usage"!==e&&"help"!==e?"clear"===e||"reset"===e?{raw:n,command:{name:"goal",operation:"clear"}}:"pause"===e||"paused"===e?{raw:n,command:{name:"goal",operation:"pause"}}:"resume"===e||"active"===e?{raw:n,command:{name:"goal",operation:"resume"}}:{raw:n,command:{name:"goal",operation:"set",objective:o}}:{raw:n,command:{name:"goal",operation:"status"}}}}}function js(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}const Rs=/^[A-Za-z_][A-Za-z0-9._:-]*$/,Es=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function Ms(e){return e.trim().toLowerCase()}function Ts(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:Ms(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function As(e){const t=Es.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!Rs.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:Ms(n)}}function Ns(e,t,n){const s=is(e.composerDraftsRef.current,e.activeSessionId),r=s===t?s:[s,t].filter(Boolean).join("\n\n"),i=rs(e.composerDraftsRef.current,e.activeSessionId,r);e.composerDraftsRef.current=i,e.setComposerDrafts(i),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(r);try{ss(i)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}const Ds=e=>e?.trim()?e:void 0,Ps="Session send timed out.";function Ls(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Fs(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function qs(e=window.location.search){const t=new URLSearchParams(e),n=Fs(t.get("folder")),s=Fs(t.get("file")),r=Fs(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...r?{cwd:r}:{}}}function Os(e,t={}){const n=t.history??window.history,s=t.location??window.location,r=[];e.folder&&r.push("file","cwd"),e.file&&r.push("folder");const i=function(e,t,n=[]){const s=new URLSearchParams(e);for(const i of n)s.delete(i);for(const[i,o]of Object.entries(t))o?s.set(i,o):s.delete(i);const r=s.toString();return r?`?${r}`:""}(s.search,e,r),o=`${s.pathname}${i}${s.hash}`;t.replace?n.replaceState(null,"",o):n.pushState(null,"",o)}const _s={en:{rewind:"Rewind to here",rewinding:"Rewinding conversation… The selected message will return to the composer when ready.",confirmRewind:"Continue in a new branch before this message? The original conversation will be archived and preserved. The selected message will become a draft; no message will be sent. Files will not change.",incompleteHistory:"This conversation has older history that is not loaded. Rewinding is unavailable to avoid selecting the wrong turn.",unavailable:"This message is no longer available.",rewindFailed:"Unable to rewind this conversation.",invalidResponse:"Invalid rewind response.",mediaError:"This format cannot be played here. Download the file to open it.",remoteSettings:"Sessions and remote devices",htmlPreview:"HTML preview",pdfPreview:"PDF preview",audioPreview:"Audio preview",videoPreview:"Video preview"},zh:{rewind:"回退到这里",rewinding:"正在回退会话…完成后,所选消息会回到输入框。",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",incompleteHistory:"此会话还有未加载的历史,暂时不能回退,以免选错消息位置。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",rewinding:"正在回退對話…完成後,所選訊息會回到輸入框。",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",incompleteHistory:"此對話還有未載入的歷史,暫時不能回退,以免選錯訊息位置。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function $s(){return _s[a(c().language)]}const zs="vibelet.web.sessionSettings";function Hs(e,n){t.useEffect(()=>{e.current=n},[e,n])}async function Bs(e,t,n){for(let r=0;r<2&&n();r++)try{return await e.request(t(),{timeoutMs:135e3})}catch(s){if(!(s instanceof Error&&/timeout|timed out/i.test(s.message)))return}}function Us(e){for(let t=(e?.length??0)-1;t>=0;t-=1){const n=e[t];if("user"===n.role)return"failed"===n.localDelivery?n:void 0}}class Ws{constructor(e,t,n){this.storage=e,this.key=t,this.isReading=n;try{const n=JSON.parse(e?.getItem(t)??"null");if(n&&"object"==typeof n){const e=n,t=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[];if(this.observed=new Set(t(e.observed)),this.unseen=new Set(t(e.unseen)),Array.isArray(e.failed))for(const n of e.failed)Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)&&this.failed.set(n[0],n[1])}}catch{}this.recovered=new Set(this.observed),this.snapshot=new Set([...this.unseen,...this.failed.values()])}observed=new Set;failed=new Map;unseen=new Set;recovered=new Set;suppressed=new Set;runtime=new Map;listeners=new Set;snapshot=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;save(){try{this.storage?.setItem(this.key,JSON.stringify({observed:[...this.observed].slice(-256),unseen:[...this.unseen].slice(-256),failed:[...this.failed].slice(-256)}))}catch{}const e=new Set([...this.unseen,...this.failed.values()]);this.snapshot.size===e.size&&[...e].every(e=>this.snapshot.has(e))||(this.snapshot=e,this.listeners.forEach(e=>e()))}deliveryChanged=(e,t,n)=>{if("failed"===n){if(this.failed.get(t)===e)return;this.failed.set(t,e)}else if(!this.failed.delete(t))return;this.save()};reconcileDeliveries=(e,t)=>{for(const[s,r]of this.failed)r===e&&this.failed.delete(s);const n=Us(t);n?.localClientMessageId&&this.failed.set(n.localClientMessageId,e),this.save()};deliveryRemoved=(e,t)=>{this.failed.delete(t)&&this.save()};observe=e=>{this.suppressed.delete(e),this.observed.has(e)||(this.observed.add(e),this.save())};complete=e=>{this.observed.delete(e)&&(this.suppressed.add(e),this.recovered.delete(e),this.isReading(e)?this.unseen.delete(e):this.unseen.add(e),this.save())};reconcile=(e,t)=>{const n=this.runtime.get(e);this.runtime.set(e,t),t?this.suppressed.has(e)||!0===n||this.observe(e):((!0===n||this.recovered.has(e))&&this.observed.has(e)&&this.complete(e),this.suppressed.delete(e))};acknowledgeOpened=e=>{this.unseen.delete(e)&&this.save()};acknowledgeVisible=()=>{let e=!1;for(const t of this.unseen)this.isReading(t)&&(this.unseen.delete(t),e=!0);e&&this.save()};remap=(e,t)=>{for(const n of[this.observed,this.unseen,this.suppressed,this.recovered])n.delete(e)&&n.add(t);this.runtime.has(e)&&(this.runtime.set(t,this.runtime.get(e)),this.runtime.delete(e));for(const[n,s]of this.failed)s===e&&this.failed.set(n,t);this.save()}}function Ks(e){return!("undefined"==typeof document||"visible"!==document.visibilityState||!document.hasFocus())&&[...document.querySelectorAll(".message-scroll")].some(t=>t.dataset.sessionId===e&&t.getClientRects().length>0&&"false"===t.dataset.historyLoading)}const Vs=new Set;function Qs(e){return Vs.add(e),()=>{Vs.delete(e)}}const Gs="vibelet.workspace.flush";async function Js(e,t,n,s){const r=AbortSignal.timeout(12e4),i=await fetch(`/upload?name=${encodeURIComponent(e.name)}`,{method:"POST",signal:AbortSignal.any([n,r]),headers:{authorization:`Bearer ${t}`,"content-type":e.type||"application/octet-stream"},body:e});if(!i.ok)throw new Error(await i.text().catch(()=>s.uploadFailed)||s.uploadFailed);const o=function(e){const t=e;return"string"==typeof t.path?t.path:null}(await i.json());if(!o)throw new Error(s.uploadPathMissing);return{path:o,name:e.name,type:e.type||"application/octet-stream",size:e.size}}function Zs(e,t,n){const s=t.split(";")[0].trim().toLowerCase();return s.startsWith("image/")?"image":"text/html"===s||/\.html?$/i.test(e)?"html":"application/pdf"===s||/\.pdf$/i.test(e)?"pdf":s.startsWith("audio/")||/\.(mp3|wav|m4a|ogg|flac)$/i.test(e)?"audio":s.startsWith("video/")||/\.(mp4|m4v|webm|mov|ogv)$/i.test(e)?"video":n?"text":"unsupported"}function Xs(e){return`<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: blob: https:; media-src data: blob:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'">${e}`}const Ys=e=>/^(https?:|data:|blob:)/i.test(e.path)?e.path:ct(e.path,e.cwd);function er(e){return e.historyKey?`key:${e.historyKey}`:e.timestamp?JSON.stringify([e.timestamp,e.role,e.type,e.content,e.images,e.toolName,e.toolInput]):void 0}const tr="vibelet.web.historyDiskCache.v1";function nr(){try{const e=JSON.parse(s().getItem(tr)||"[]");return Array.isArray(e)?e.filter(e=>e&&"string"==typeof e.daemonId&&"string"==typeof e.sessionId&&Array.isArray(e.messages)&&e.messages.every(e=>e&&["user","assistant","tool"].includes(e.role)&&"string"==typeof e.content)).slice(0,40):[]}catch{return[]}}function sr(e,t){try{const n=nr().filter(n=>n.daemonId!==e||!Object.hasOwn(t,n.sessionId));for(const[s,i]of Object.entries(t)){if(!i)continue;const t={daemonId:e,sessionId:s,messages:i.slice(-1e3)};for(;t.messages.length&&(new TextEncoder).encode(JSON.stringify(t)).length>524288;)t.messages.shift();(t.messages.length||0===i.length)&&n.unshift(t)}const r=n.slice(0,40);for(;r.length&&(new TextEncoder).encode(JSON.stringify(r)).length>2097152;)r.pop();s().setItem(tr,JSON.stringify(r))}catch{}}const rr=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function ir(e){return e instanceof TypeError?"TypeError":e instanceof RangeError?"RangeError":e instanceof SyntaxError?"SyntaxError":e instanceof Error?"Error":"string"==typeof e?"string":typeof e}function or(e,t){return t.has(e.sessionId)||!0===e.runtime?.isResponding||"daemonActive"===e.runtime?.state||"externalRunning"===e.runtime?.state}function ar(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}class cr{cleared=new Map;live(e,t,n){const s=new Set(n.map(e=>e.clientMessageId)),r=this.cleared.get(t)??new Set;for(const i of e[t]??[])i.clientMessageId&&!s.has(i.clientMessageId)&&r.add(i.clientMessageId);for(const i of s)i&&r.delete(i);return this.cleared.set(t,r),{...e,[t]:n}}confirmRemoval(e,t){const n=this.cleared.get(e)??new Set;t.forEach(e=>n.add(e)),this.cleared.set(e,n)}snapshot(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.filter(t=>!t.clientMessageId||!this.cleared.get(e)?.has(t.clientMessageId))]))}remap(e,t){const n=this.cleared.get(e);n&&(this.cleared.set(t,new Set([...this.cleared.get(t)??[],...n])),this.cleared.delete(e))}}const lr="vibelet.shortcuts.changed",dr="vibelet.workspace.command",ur=[{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"quickSearch",zh:"快速定位会话 / 标签",en:"Quick switch sessions / tabs",default:"mod+k"},{id:"searchMessages",zh:"搜索聊天内容",en:"Search conversation",default:"mod+f"},{id:"files",zh:"打开文件树",en:"Open files",default:"mod+alt+e"},{id:"terminal",zh:"打开终端",en:"Open terminal",default:"mod+j"},{id:"browser",zh:"打开浏览器",en:"Open browser",default:"mod+alt+b"},{id:"browserAddress",zh:"聚焦浏览器地址栏",en:"Focus browser address",default:"mod+l"},{id:"browserCopyUrl",zh:"复制浏览器地址",en:"Copy browser address",default:"mod+shift+c"},{id:"newTab",zh:"新建终端 / 浏览器标签",en:"New terminal / browser tab",default:"mod+t"},{id:"previousTab",zh:"上一个标签",en:"Previous tab",default:"mod+shift+["},{id:"nextTab",zh:"下一个标签",en:"Next tab",default:"mod+shift+]"},{id:"closeTab",zh:"关闭当前标签",en:"Close current tab",default:"mod+w"},{id:"moveTab",zh:"在中间区域与右侧栏间移动标签",en:"Move tab between workspace and sidebar",default:"mod+shift+m"},{id:"diff",zh:"查看 Git 变更",en:"View Git changes",default:"mod+alt+g"}];function hr(){return/Mac|iPhone|iPad/.test(navigator.platform)}const fr={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function pr(e,t=hr()){const n=fr[e.code]||(/^Key[A-Z]$/.test(e.code)?e.code.slice(3).toLowerCase():/^Digit\d$/.test(e.code)?e.code.slice(5):e.key.toLowerCase());return["meta","control","alt","shift","dead"].includes(n)||!(e.metaKey||e.ctrlKey||e.altKey)?null:[t?e.metaKey&&"mod":e.ctrlKey&&"mod",t?e.ctrlKey&&"ctrl":e.metaKey&&"meta",e.altKey&&"alt",e.shiftKey&&"shift",n].filter(Boolean).join("+")}function mr(e,t=hr()){const n=t?{mod:"⌘",ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",space:"Space"}:{mod:"Ctrl",ctrl:"Ctrl",meta:"Win",alt:"Alt",shift:"Shift",space:"Space"};return e.split("+").map(e=>n[e]||e.toUpperCase()).join(t?"":"+")}function gr(e,t,n){return t?"mod+w"===t?"closeTab"===e?null:"reserved":["mod+n","mod+,","mod+q","mod+c","mod+v","mod+x","mod+a","mod+z","mod+shift+z","mod+s","mod+r","mod+h","mod+m","mod+-","mod+=","mod+shift+="].includes(t)?"reserved":ur.find(s=>s.id!==e&&function(e,t={}){return t[e]??ur.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const vr="vibelet.web.shortcuts";function yr(){try{const e=JSON.parse(s().getItem(vr)||"{}");return Object.fromEntries(ur.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function br(e,t=yr()){return t[e]??("closeTab"===e&&"browser"===r().kind?"mod+alt+w":ur.find(t=>t.id===e).default)}function wr(e,t){const n=br(t);return n?`${e} (${mr(n)})`:e}const xr="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='-3%20-3%2041%2041'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M-3%20-3h41v41H-3z'/%3e%3cpath%20stroke='%23000000'%20d='M1%201.5h7m2%200h2m2%200h1m2%200h1m1%200h2m1%200h1m1%200h1m2%200h7M1%202.5h1m5%200h1m2%200h1m3%200h5m3%200h1m2%200h1m1%200h1m5%200h1M1%203.5h1m1%200h3m1%200h1m1%200h1m1%200h1m2%200h1m1%200h2m1%200h6m2%200h1m1%200h3m1%200h1M1%204.5h1m1%200h3m1%200h1m1%200h3m3%200h4m1%200h4m1%200h1m1%200h1m1%200h3m1%200h1M1%205.5h1m1%200h3m1%200h1m1%200h1m2%200h3m1%200h1m1%200h3m1%200h2m3%200h1m1%200h3m1%200h1M1%206.5h1m5%200h1m1%200h2m2%200h6m3%200h2m3%200h1m5%200h1M1%207.5h7m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h7M9%208.5h1m1%200h1m4%200h1m3%200h4M1%209.5h1m1%200h5m2%200h1m1%200h7m1%200h1m2%200h1m1%200h1m1%200h5M3%2010.5h2m1%200h1m2%200h2m1%200h1m3%200h2m1%200h4m1%200h1m2%200h2m1%200h2M1%2011.5h2m1%200h1m2%200h5m4%200h1m4%200h1m1%200h1m1%200h2m2%200h1m1%200h2M1%2012.5h3m1%200h1m2%200h3m2%200h1m1%200h1m3%200h2m1%200h3m1%200h1m2%200h5M2%2013.5h1m1%200h1m2%200h3m1%200h3m2%200h1m2%200h1m3%200h2m1%200h1m1%200h1m1%200h1m1%200h1M2%2014.5h3m1%200h1m3%200h2m3%200h3m1%200h3m2%200h2m6%200h2M1%2015.5h2m1%200h1m1%200h2m4%200h3m3%200h1m2%200h2m2%200h3m1%200h4M1%2016.5h1m1%200h3m2%200h1m2%200h2m1%200h1m2%200h1m1%200h1m1%200h8m1%200h2M3%2017.5h7m1%200h2m1%200h2m1%200h2m4%200h4m1%200h2m1%200h1m1%200h1M2%2018.5h2m4%200h1m1%200h2m1%200h1m2%200h13m1%200h4M1%2019.5h1m2%200h5m1%200h1m1%200h7m7%200h1m1%200h2m1%200h1M1%2020.5h3m5%200h1m1%200h2m1%200h1m2%200h8m2%200h5m1%200h1M1%2021.5h1m1%200h6m1%200h1m1%200h1m1%200h1m2%200h1m2%200h1m1%200h2m1%200h2m1%200h3M1%2022.5h1m1%200h2m1%200h1m1%200h2m1%200h6m1%200h2m1%200h2m1%200h1m2%200h1m2%200h1m2%200h1M1%2023.5h1m2%200h2m1%200h5m2%200h4m1%200h1m1%200h1m3%200h2m2%200h1m2%200h1M1%2024.5h1m2%200h1m5%200h1m1%200h5m3%200h4m1%200h3m1%200h3m1%200h1M1%2025.5h1m3%200h3m4%200h3m1%200h1m1%200h1m4%200h7m1%200h2M9%2026.5h1m1%200h2m1%200h2m3%200h2m1%200h1m1%200h2m3%200h1m1%200h1m1%200h1M1%2027.5h7m2%200h1m1%200h2m1%200h3m1%200h1m1%200h1m2%200h2m1%200h1m1%200h1m1%200h2M1%2028.5h1m5%200h1m1%200h9m3%200h5m3%200h3m1%200h1M1%2029.5h1m1%200h3m1%200h1m1%200h2m2%200h2m1%200h1m2%200h1m1%200h1m3%200h6M1%2030.5h1m1%200h3m1%200h1m1%200h4m1%200h5m2%200h1m1%200h2m1%200h1m2%200h2m1%200h2M1%2031.5h1m1%200h3m1%200h1m1%200h2m1%200h2m7%200h2m1%200h5m1%200h2M1%2032.5h1m5%200h1m2%200h2m2%200h2m1%200h1m1%200h4m1%200h1m2%200h1m1%200h3M1%2033.5h7m1%200h5m4%200h1m2%200h1m1%200h3m1%200h2m3%200h1'/%3e%3c/svg%3e",Sr="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2041%2041'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M0%200h41v41H0z'/%3e%3cpath%20stroke='%23000000'%20d='M4%204.5h7m3%200h5m3%200h1m2%200h2m3%200h7M4%205.5h1m5%200h1m1%200h1m2%200h1m4%200h2m2%200h2m2%200h1m1%200h1m5%200h1M4%206.5h1m1%200h3m1%200h1m1%200h1m1%200h1m1%200h1m2%200h1m3%200h3m1%200h1m2%200h1m1%200h3m1%200h1M4%207.5h1m1%200h3m1%200h1m1%200h2m1%200h1m2%200h2m1%200h1m1%200h3m1%200h2m1%200h1m1%200h3m1%200h1M4%208.5h1m1%200h3m1%200h1m3%200h1m6%200h3m1%200h1m1%200h1m2%200h1m1%200h3m1%200h1M4%209.5h1m5%200h1m4%200h1m1%200h1m6%200h1m5%200h1m5%200h1M4%2010.5h7m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h7M12%2011.5h1m3%200h1m3%200h1m2%200h2m1%200h1m1%200h1M4%2012.5h1m5%200h1m1%200h1m1%200h1m1%200h4m1%200h2m3%200h5m2%200h3M6%2013.5h4m4%200h2m1%200h3m1%200h3m3%200h2m3%200h4M4%2014.5h1m2%200h5m1%200h2m2%200h3m2%200h1m1%200h3m2%200h2m1%200h1m1%200h2M5%2015.5h1m1%200h2m2%200h2m2%200h3m1%200h2m2%200h1m2%200h10M5%2016.5h1m4%200h1m1%200h3m2%200h1m1%200h2m2%200h2m2%200h2m1%200h2m4%200h1M6%2017.5h3m2%200h5m3%200h1m1%200h4m2%200h1m1%200h3m1%200h4M7%2018.5h2m1%200h1m3%200h3m1%200h4m3%200h1m2%200h3m3%200h2M5%2019.5h1m1%200h2m3%200h2m5%200h1m3%200h1m2%200h2m1%200h1m1%200h1m2%200h1m1%200h1M4%2020.5h1m4%200h2m3%200h1m1%200h3m1%200h2m1%200h1m2%200h1m2%200h1m1%200h2m3%200h1M6%2021.5h4m1%200h1m2%200h1m1%200h1m1%200h3m1%200h3m1%200h2m2%200h1m2%200h2m1%200h1M5%2022.5h2m3%200h3m2%200h3m1%200h1m1%200h1m1%200h2m1%200h3m1%200h2m1%200h2m1%200h1M5%2023.5h1m1%200h1m3%200h5m2%200h3m1%200h3m1%200h1m1%200h1m3%200h3M6%2024.5h3m1%200h1m1%200h4m2%200h1m1%200h1m1%200h2m2%200h1m2%200h1m1%200h3m1%200h2M4%2025.5h1m7%200h1m3%200h1m3%200h1m2%200h1m2%200h2m3%200h3M4%2026.5h1m2%200h1m2%200h2m1%200h5m1%200h1m2%200h1m1%200h2m7%200h3M4%2027.5h1m3%200h1m4%200h2m5%200h1m8%200h1m1%200h1m1%200h4M4%2028.5h3m1%200h1m1%200h3m5%200h3m3%200h1m3%200h5m3%200h1M12%2029.5h1m1%200h2m3%200h1m3%200h1m1%200h1m1%200h2m3%200h1m1%200h1m1%200h1M4%2030.5h7m7%200h2m2%200h1m1%200h1m1%200h3m1%200h1m1%200h1m1%200h2M4%2031.5h1m5%200h1m2%200h3m4%200h1m1%200h1m4%200h2m3%200h5M4%2032.5h1m1%200h3m1%200h1m2%200h1m3%200h3m1%200h2m3%200h1m1%200h6m1%200h1M4%2033.5h1m1%200h3m1%200h1m2%200h2m4%200h1m2%200h4m2%200h2m1%200h2m1%200h3M4%2034.5h1m1%200h3m1%200h1m4%200h3m2%200h6m1%200h2m2%200h3m1%200h2M4%2035.5h1m5%200h1m2%200h2m1%200h2m1%200h1m2%200h1m1%200h1m4%200h1m1%200h4M4%2036.5h7m1%200h6m2%200h2m4%200h1m1%200h2m1%200h1m3%200h1'/%3e%3c/svg%3e";function kr(){const e=a(c().language);return"en"===e?{close:"Close",title:"Continue on your phone",free:"Mac and Web are free",description:"Step away from your desk. Check progress, respond to approvals and continue your sessions on your phone.",download:"Scan to install",ios:"Get the iPhone app",android:"Get the Android app",pairing:"Keep your computer running. On Mac, open Settings → Current device, enable phone access and generate a pairing code. Open Vibelet on your phone and scan it. For a CLI daemon, use the pairing code shown by npx vibelet.",pro:"Explore the mobile app first. Upgrade to Vibelet Pro on your phone when you need its advanced features. Existing mobile purchases can be restored there."}:"zh-TW"===e?{close:"關閉",title:"在手機上繼續",free:"Mac 與 Web 免費使用",description:"離開電腦,也能查看任務進度、處理審批,繼續同一段對話。",download:"掃碼安裝",ios:"取得 iPhone 版",android:"取得 Android 版",pairing:"保持電腦運行。在 Mac「設定 → 當前裝置」開啟手機存取並產生配對碼,再用手機 Vibelet 掃碼。使用 CLI 時,掃描 npx vibelet 顯示的配對碼。",pro:"先體驗手機端,需要進階功能時再於手機升級 Vibelet Pro。已有手機端購買可在手機恢復。"}:{close:"关闭",title:"在手机上继续",free:"Mac 与 Web 免费使用",description:"离开电脑,也能查看任务进度、处理审批,继续同一段对话。",download:"扫码安装",ios:"获取 iPhone 版",android:"获取 Android 版",pairing:"保持电脑运行。在 Mac「设置 → 当前设备」开启手机访问并生成配对码,再用手机 Vibelet 扫码。使用 CLI 时,扫描 npx vibelet 显示的配对码。",pro:"先体验手机端,需要高级功能时再在手机升级 Vibelet Pro。已有手机端购买可在手机恢复。"}}function Ir(){const e=kr();return n.jsxs("section",{className:"mobile-companion-panel control-section",children:[n.jsx("p",{className:"mobile-companion-free",children:e.free}),n.jsx("h2",{children:e.title}),n.jsx("p",{children:e.description}),n.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:Sr,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:xr,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>n.jsxs("div",{children:[n.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),n.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),n.jsx("p",{children:e.pairing}),n.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function Cr({onClose:e}){const s=t.useRef(null);t.useEffect(()=>{const e=document.activeElement,t=document.getElementById("vibelet-workspace"),n=t?.inert;return t&&(t.inert=!0),s.current?.focus(),()=>{t&&(t.inert=Boolean(n)),e?.focus()}},[]);const r=kr().title;return k.createPortal(n.jsx("div",{className:"mobile-companion-backdrop",onClick:t=>{t.target===t.currentTarget&&e()},children:n.jsxs("section",{ref:s,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":r,tabIndex:-1,onKeyDown:t=>{if("Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),e()),"Tab"!==t.key)return;const n=Array.from(t.currentTarget.querySelectorAll("button,a[href]")),r=n[0],i=n.at(-1);!t.shiftKey||document.activeElement!==r&&document.activeElement!==s.current?t.shiftKey||document.activeElement!==i||(t.preventDefault(),r?.focus()):(t.preventDefault(),i?.focus())},children:[n.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":kr().close,title:kr().close,onClick:e,children:n.jsx(Be,{"aria-hidden":"true"})}),n.jsx(Ir,{})]})}),document.body)}function jr({activeSession:e,client:s,busy:i,controlsOpen:o,pendingCount:a=0,t:c,onOpenControls:l,onRefreshSessions:d,onRestoreSnapshot:u,onToggleArchived:h,onTogglePinned:f,onViewChanges:p}){const[m,g]=t.useState(!1),[v,y]=t.useState(!1),b=t.useRef(null);t.useEffect(()=>{if(!v)return;const e=e=>{e.target instanceof Node&&!b.current?.contains(e.target)&&y(!1)},t=e=>{"Escape"===e.key&&y(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[v]);const w=e=>{y(!1),e()},x=r(),S=n.jsxs("div",{className:"header-actions",children:[e&&x.renderSessionShare?.(e,s),("desktop"!==x.kind||a>0)&&n.jsxs("button",{type:"button",className:"icon-button header-pending-button","aria-label":c.pendingActionCount(a),title:c.pendingActionCount(a),onClick:()=>window.dispatchEvent(new Event("vibelet.pending.open")),children:[n.jsx(q,{"aria-hidden":"true"}),a>0&&n.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:a})]}),m&&n.jsx(Cr,{onClose:()=>g(!1)}),e?null:n.jsx("button",{"aria-label":c.refreshSessions,className:"icon-button",onClick:d,title:c.refreshSessions,type:"button",children:n.jsx(Re,{"aria-hidden":"true"})}),n.jsx("button",{"aria-expanded":o,"aria-label":o?c.collapseControlsSidebar:c.workspaceTools,title:wr(o?c.collapseControlsSidebar:c.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:l,type:"button",children:n.jsx(xe,{"aria-hidden":"true"})}),e||x.openSettings?n.jsxs("div",{className:"header-more-wrap",ref:b,children:[n.jsx("button",{"aria-expanded":v,"aria-haspopup":"menu","aria-label":c.moreActions,className:"icon-button",onClick:()=>y(e=>!e),title:c.moreActions,type:"button",children:n.jsx(J,{"aria-hidden":"true"})}),v?n.jsxs("div",{className:"header-action-menu",role:"menu",children:["desktop"===x.kind&&0===a&&n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>window.dispatchEvent(new Event("vibelet.pending.open"))),children:[n.jsx(q,{"aria-hidden":"true"}),n.jsx("span",{children:c.pendingActionCount(a)})]}),e&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:()=>w(()=>p(e.sessionId)),role:"menuitem",type:"button",children:[n.jsx(oe,{"aria-hidden":"true"}),n.jsx("span",{children:c.viewChanges})]}),n.jsxs("button",{disabled:i,onClick:()=>w(f),role:"menuitem",type:"button",children:[n.jsx(Ie,{"aria-hidden":"true"}),n.jsx("span",{children:e.pinned?c.unpin:c.pin})]}),n.jsxs("button",{disabled:i,onClick:()=>w(h),role:"menuitem",type:"button",children:[n.jsx(N,{"aria-hidden":"true"}),n.jsx("span",{children:e.archived?c.unarchive:c.archive})]}),n.jsxs("button",{onClick:()=>w(u),role:"menuitem",type:"button",children:[n.jsx(Ee,{"aria-hidden":"true"}),n.jsx("span",{children:c.restoreSnapshot})]})]}),n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>g(!0)),children:[n.jsx(I,{"aria-hidden":"true"}),n.jsx("span",{children:kr().title})]}),n.jsxs("button",{onClick:()=>w(d),role:"menuitem",type:"button",children:[n.jsx(Re,{"aria-hidden":"true"}),n.jsx("span",{children:c.refreshSessions})]})]}):null]}):null]}),C=x.toolbarTarget?.("right");return C?k.createPortal(S,C):S}function Rr(e,n,s,r,i,o,a){const c=JSON.stringify([n,s,r,i]),[l,d]=t.useState(null);if(t.useEffect(()=>{if("codex"!==n||!e)return;let t,i=!1,o=0,a=0,l=!1,u=!1;const h=()=>{i||u||l||void 0!==t||a>=5||(t=setTimeout(g,1e3*2**Math.max(0,a-1)))},f=t=>{u=Boolean(t?.defaultModel),d({client:e,key:c,state:t,loading:!u&&a<5})};d({client:e,key:c,state:null,loading:!0});const p=e.onMessage(e=>{i||"session.model"!==e.type||e.sessionId!==r||(o++,clearTimeout(t),t=void 0,f(e),h())}),m=e.onClose(()=>{i=!0,clearTimeout(t),d({client:e,key:c,state:null,loading:!1})});async function g(){if(t=void 0,i||!e)return;l=!0,a++;const n=o;try{const t=await e.request({action:"model.status",id:e.makeId("model-status"),...r?{sessionId:r}:{cwd:s}},{timeoutMs:15e3});i||o!==n||f(t)}catch{i||o!==n||f(null)}finally{l=!1,h()}}return t=setTimeout(g,200),()=>{i=!0,clearTimeout(t),p(),m()}},[e,n,s,r,i,c]),"codex"!==n)return o;const u=l&&l.client===e&&l.key===c?l:null,h={value:"",label:`CLI · ${u?.state?.defaultModel||(!e||u&&!u.loading?a.unknown:a.remoteModelChecking)}`,desc:"config"===u?.state?.defaultSource?a.remoteModelConfig:"recommended"===u?.state?.defaultSource?a.remoteModelRecommended:a.unknown};return o.some(e=>""===e.value)?o.map(e=>""===e.value?{...e,...h}:e):[h,...o]}function Er({title:e,hint:t}){return n.jsxs("div",{className:"empty-state compact",children:[n.jsx(Pe,{"aria-hidden":"true"}),n.jsx("h2",{children:e}),n.jsx("p",{children:t})]})}function Mr(e,t){return!t.altKey&&(!(!t.metaKey&&!t.ctrlKey)||("enter"===e?!t.shiftKey:"shiftEnter"===e&&t.shiftKey))}const Tr=new RegExp("((?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)[^\\n`<>\"')\\]},。!?;:、]*?\\.(?:png|jpg|jpeg|gif|webp|svg|heic|heif)(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?)","gi"),Ar=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Nr="\\s`<>\"')\\]},。!?;:、",Dr="`<>\"')\\]},。!?;:、\\n\\r\\t",Pr=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Nr}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),Lr=new RegExp(`(^|[\\s([{>])((?=[^${Dr}]*\\/)[^${Dr}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Nr}]+)?)(?=$|[${Nr}])`,"g");function Fr(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function qr(e,t){return!!e&&!/^[a-z]+:\/\//i.test(e)&&!e.startsWith("streamdown:")&&(!("~"!==e&&!e.startsWith("~/"))||!!(e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))||!(!/^[A-Za-z]:[\\/]/.test(e)&&!e.startsWith("\\\\"))||!(!e.includes("/")&&!e.includes("\\"))||Boolean(t?.allowBareFilename)&&/^[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+$/.test(e))}function Or(e){let t=Fr(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const e=t.slice(0,n);qr(e,{allowBareFilename:!0})&&(t=e)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const e=s[1]??"";qr(e,{allowBareFilename:!0})&&(t=e)}return Fr(t)}function _r(e,t){return e.start<t.end&&t.start<e.end}function $r(e){if(e.startsWith("/")||e.startsWith("~/")||e.startsWith("./")||e.startsWith("../"))return!0;const t=e.indexOf("/");if(t<=0)return!1;const n=e.slice(0,t).trim();return!!/^\d+\s+\S/.test(n)||!/\s/.test(n)&&/[^\p{ASCII}]/u.test(n)}function zr(e){if($r(e.rawCandidate))return e;const t=e.rawCandidate.indexOf("/");if(t<=0)return e;const n=e.rawCandidate.slice(0,t);for(let s=n.indexOf(" ");s>=0;s=n.indexOf(" ",s+1)){const t=s+1,n=e.rawCandidate.slice(t);if($r(n))return{start:e.start+t,end:e.end,rawCandidate:n}}return e}function Hr(e,t){return qr(Or(e),t)}function Br(e){const t=Or(e).toLowerCase();return Hr(t,{allowBareFilename:!0})&&Ar.some(e=>t.endsWith(e))}const Ur="vibelet:image-gallery";function Wr(e){window.dispatchEvent(new CustomEvent(Ur,{detail:e}))}const Kr=/^[a-z][a-z0-9+.-]*:/i,Vr=/^[a-z]:[\\/]/i,Qr=/\.(?:md|markdown)$/i,Gr="https://vibelet.local",Jr="/__vibelet_markdown__",Zr=`${Gr}${Jr}`;function Xr(e){const t=e?.trim()??"";if(!t||t.startsWith("#")||t.startsWith("//"))return null;const n=function(e){let t;try{t=new URL(e)}catch{return null}if(t.origin!==Gr)return null;if(t.pathname!==Jr)return null;const n=t.searchParams.get("path");return n&&Qr.test(n)?n:null}(t);if(n)return n;if(Kr.test(t)&&!Vr.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return Qr.test(s)?function(e){try{return decodeURIComponent(e)}catch{return e}}(s):null}function Yr(e){const t=e.split("\n");let n=null;return t.map(e=>{const t=e.match(/^ {0,3}(`{3,}|~{3,})/);if(t){const s=t[1][0];return n===s?n=null:n||(n=s),e}return n?e:function(e){let t="",n=0;for(;n<e.length;){if("`"===e[n]){const s=ei(e,n);t+=e.slice(n,s),n=s;continue}if("["===e[n]&&"!"!==e[n-1]){const s=ti(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}(e)}).join("\n")}function ei(e,t){let n=0;for(;"`"===e[t+n];)n+=1;const s="`".repeat(n),r=e.indexOf(s,t+n);return r<0?e.length:r+n}function ti(e,t){const n=function(e,t){let n=!1;for(let s=t+1;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if("]"===t)return s}else n=!0}return-1}(e,t);if(n<0||"("!==e[n+1])return null;const s=n+2,r=function(e,t){let n=!1;for(let s=t;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if(")"===t)return s}else n=!0}return-1}(e,s);if(r<0)return null;const i=function(e){const t=e.match(/^\s*/)?.[0]??"",n=e.match(/\s*$/)?.[0]??"",s=e.slice(t.length,e.length-n.length);if(s.startsWith("<")){const e=s.indexOf(">");if(e<0)return null;const r=ni(s.slice(1,e));return r?`${t}<${r}>${s.slice(e+1)}${n}`:null}const r=s.match(/^(\S+)([\s\S]*)$/);if(!r)return null;const i=ni(r[1]);return i?`${t}${i}${r[2]}${n}`:null}(e.slice(s,r));return i?{text:`${e.slice(t,s)}${i})`,end:r+1}:null}function ni(e){const t=Xr(e);return t?`${Zr}?path=${encodeURIComponent(t)}`:null}const si="https://vibelet.local/__vibelet_file__";function ri(e){if(!e)return null;const t=Xr(e);if(t)return t;let n=e.trim();if(n.startsWith(si))try{const e=new URL(n);if("https://vibelet.local"!==e.origin||"/__vibelet_file__"!==e.pathname)return null;n=e.searchParams.get("path")??""}catch{return null}else if(/^file:\/\//i.test(n))try{const e=new URL(n);if(e.hostname&&"localhost"!==e.hostname)return null;n=e.pathname}catch{return null}else if(/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(n)&&!/^[a-z]:[\\/]/i.test(n))return null;try{n=decodeURIComponent(n.split("?")[0])}catch{}return n=Or(n),Hr(n,{allowBareFilename:!0})?n:null}const ii=e=>`${si}?path=${encodeURIComponent(e)}`;function oi(e){return e.value??e.children?.map(oi).join("")??""}function ai(){return e=>{const t=e=>{if("link"===e.type||"image"===e.type){const t=ri(e.url);return void(t&&(e.url=ii(t),Br(t)&&(e.alt=e.alt||oi(e)||t.split(/[\\/]/).at(-1),e.type="image",delete e.children)))}e.children&&!["code","inlineCode","html"].includes(e.type)&&(e.children=e.children.flatMap(e=>"text"===e.type?function(e){const t=[],n=new RegExp(`(?:file://(?:localhost)?(?=/))?${Tr.source}`,Tr.flags);let s=0;const r=e=>{for(const n of function(e){if(!e)return[];const t=[];let n=0;for(const s of function(e){const t=[];for(const n of e.matchAll(Pr)){const e=n[1]??"",s=n[2]??"",r=(n.index??0)+e.length;t.push({start:r,end:r+s.length,rawCandidate:s})}for(const n of e.matchAll(Lr)){const e=n[1]??"",s=n[2]??"",r=(n.index??0)+e.length,i=zr({start:r,end:r+s.length,rawCandidate:s}),o=t.filter(e=>_r(e,i));if(0!==o.length){if($r(i.rawCandidate)){for(const e of o){const n=t.indexOf(e);n>=0&&t.splice(n,1)}t.push(i)}}else t.push(i)}return t.sort((e,t)=>e.start-t.start||e.end-t.end)}(e)){s.start>n&&t.push({type:"text",value:e.slice(n,s.start)});const r=Fr(s.rawCandidate),i=Or(r),o=s.rawCandidate.slice(r.length);Hr(r)&&!Br(r)?(t.push({type:"path",value:r,target:i||r}),o&&t.push({type:"text",value:o})):t.push({type:"text",value:s.rawCandidate}),n=s.end}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length>0?t:[{type:"text",value:e}]}(e))t.push("path"===n.type?{type:"link",url:ii(n.target??n.value),children:[{type:"text",value:n.value}]}:{type:"text",value:n.value})};for(const i of e.matchAll(n)){const n=ri(i[0]);n&&Br(n)&&(r(e.slice(s,i.index)),t.push({type:"image",url:ii(n),alt:n.split(/[\\/]/).at(-1)}),s=i.index+i[0].length)}return r(e.slice(s)),t}(e.value??""):(t(e),[e])))};t(e)}}const ci=20971520,li=new class{constructor(e=128,t=67108864,n=3e4){this.maxEntries=e,this.maxBytes=t,this.ttl=n}scope="";bytes=0;entries=new Map;get(e,t,n){this.scope!==e&&(this.entries.clear(),this.bytes=0,this.scope=e);for(const[i,o]of this.entries)o.expires<=Date.now()&&this.remove(i,o);const s=this.entries.get(t);if(s)return this.entries.delete(t),this.entries.set(t,s),s.promise;const r={promise:Promise.resolve(new Blob),bytes:0,expires:1/0};return r.promise=Promise.resolve().then(n).then(e=>(this.entries.get(t)===r&&(r.bytes=e.size,r.expires=Date.now()+this.ttl,this.bytes+=e.size,this.trim()),e),e=>{throw this.remove(t,r),e}),this.entries.set(t,r),this.trim(),r.promise}remove(e,t){this.entries.get(e)===t&&(this.entries.delete(e),this.bytes-=t.bytes)}trim(){for(;this.entries.size>this.maxEntries||this.bytes>this.maxBytes;){const e=this.entries.entries().next().value;if(!e)return;this.remove(...e)}}};function di(e,t){return li.get(t,e,()=>async function(e,t){for(let s=0;;s++){const r=new AbortController;let i;const o=()=>{clearTimeout(i),i=setTimeout(()=>r.abort(new DOMException("Image request timed out","TimeoutError")),3e4)};o();try{const n=await fetch(e,{headers:{authorization:`Bearer ${t}`},signal:r.signal});if(0===s&&[502,503,504].includes(n.status)){await(n.body?.cancel());continue}const i=n.headers.get("content-type")??"";if(!n.ok||Number(n.headers.get("content-length"))>ci||!i.startsWith("image/"))throw await(n.body?.cancel()),new Error("Image unavailable");const a=n.body?.getReader();if(!a)throw new Error("Image unavailable");const c=[];let l=0;try{for(;;){o();const{value:e,done:t}=await a.read();if(t)break;if(l+=e.byteLength,l>ci)throw await a.cancel(),new Error("Unsupported image");c.push(e)}}finally{a.releaseLock()}return new Blob(c,{type:i})}catch(n){if(0===s&&(n instanceof TypeError||r.signal.aborted))continue;throw n}finally{clearTimeout(i)}}}(e,t))}function ui(e,n,s=1600){const r=ri(e),i=sn(),[o,a]=t.useState(null),[c,l]=t.useState(null);return t.useEffect(()=>{if(!r)return;const t=new AbortController;let o;return a(null),l(null),(async()=>{try{if(!i)throw new Error("No pairing");const c=new URL(Dn(r,n));null!==s&&c.searchParams.set("w",String(s));const l=await di(c.toString(),i.pairToken);if(t.signal.aborted)return;o=URL.createObjectURL(l),a({src:e,url:o})}catch{t.signal.aborted||l(e)}})(),()=>{t.abort(),o&&URL.revokeObjectURL(o)}},[e,r,n,s,i?.pairToken,i?.webSocketUrl]),{url:r?o?.src===e?o.url:void 0:e,error:c===e,fail:()=>l(e)}}function hi({src:e,alt:t,cwd:s,onOpen:r,gallery:i}){const o=ri(e),{url:l,error:d,fail:u}=ui(e,s),h=b[a(c().language)],f=t||wn(o??e);return n.jsx("button",{className:"message-image-preview","data-image-src":e,"data-image-cwd":s,type:"button",title:o??e,"aria-label":`${h.preview}: ${f}`,onClick:async t=>{t.preventDefault(),t.stopPropagation();const n=await(i?.())??[{src:e,alt:f,cwd:s}],a=n.findIndex(t=>t.src===e||o&&ri(t.src)===o);Wr({images:a<0?[{src:e,alt:f,cwd:s}]:n,index:Math.max(0,a),onOpen:r})},children:d?n.jsxs("span",{className:"message-image-placeholder",children:[n.jsx(le,{"aria-hidden":"true"}),f," · ",h.fileOpenFailed]}):l?n.jsx("img",{src:l,alt:f,loading:"lazy",onError:u}):n.jsxs("span",{className:"message-image-placeholder",children:[n.jsx(pe,{className:"session-running-icon","aria-hidden":"true"}),f]})})}function fi({attachments:e,uploadBusy:t,onRemove:s,onOpen:r,t:i}){if(!e.length&&!t)return null;const o=e.filter(e=>e.type.startsWith("image/")||Br(e.path)||Br(e.name)),a=()=>o.map(e=>({src:e.path,alt:e.name||wn(e.path)}));return n.jsxs("div",{className:"attachment-row composer-attachments",children:[e.length>0&&n.jsx("div",{className:"composer-attachment-images",children:e.map(e=>{const t=e.name||wn(e.path),c=o.includes(e);return n.jsxs("div",{className:"composer-attachment-card "+(c?"composer-image-card":"composer-file-card"),children:[c?n.jsx(hi,{src:e.path,alt:t,onOpen:r,gallery:a}):n.jsxs("button",{className:"composer-file-preview",type:"button",title:`${t} · ${vn(e.size)}`,"aria-label":`${i.preview}: ${t}`,onClick:()=>r(e.path),children:[n.jsx(Se,{"aria-hidden":"true"}),n.jsx("span",{children:t}),n.jsx("small",{children:vn(e.size)})]}),n.jsx("button",{className:"composer-image-remove",type:"button",title:`${i.removeAttachment}: ${t}`,"aria-label":`${i.removeAttachment}: ${t}`,onClick:()=>s(e.path),children:n.jsx(Be,{"aria-hidden":"true"})})]},e.path)})}),t&&n.jsxs("span",{className:"attachment-empty",role:"status",children:[n.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),i.uploading]})]})}function pi(e,n,s,r){const[i,o]=t.useState({left:16,top:16,maxHeight:240});return t.useLayoutEffect(()=>{if(!e)return;const t=()=>{const e=n.current?.getBoundingClientRect(),t=s.current;if(!e||!t)return;const i=t.getBoundingClientRect().width,a=Math.max(80,e.top-24),c=Math.min(t.scrollHeight,a);o({left:Math.max(16,Math.min("right"===r?e.right-i:e.left,innerWidth-i-16)),top:Math.max(16,e.top-c-8),maxHeight:a})};t();const i="undefined"==typeof ResizeObserver?null:new ResizeObserver(t);return s.current&&i?.observe(s.current),window.addEventListener("resize",t),document.addEventListener("scroll",t,!0),()=>{i?.disconnect(),window.removeEventListener("resize",t),document.removeEventListener("scroll",t,!0)}},[e,n,s,r]),i}function mi({icon:e,label:s,menuLabel:r,options:i,value:o,onSelect:a,align:c="left",disabled:l,selected:d,wide:u,blendBackground:h,portal:f=!1,tooltipHoverDelay:p}){const[m,g]=t.useState(!1),v=t.useRef(null),y=t.useRef(null),b=t.useRef(null),w=pi(m&&f,b,y,c),x=i.some(e=>e.icon);t.useEffect(()=>{if(!m)return;const e=y.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)'),t=[...e??[]].find(e=>"true"===e.getAttribute("aria-checked"));(t??e?.[0])?.focus();const n=e=>{e.target instanceof Node&&!v.current?.contains(e.target)&&!y.current?.contains(e.target)&&g(!1)};return document.addEventListener("pointerdown",n),()=>document.removeEventListener("pointerdown",n)},[m]);const S=m?n.jsx("div",{ref:y,style:f?w:void 0,"aria-label":r,className:`composer-option-popover ${f?"portal":""} ${h?"blend-background":""} ${x?"":"without-icons"} ${u?"wide":""} ${"right"===c?"align-right":""}`,role:"menu",children:i.map(e=>{const t=e.icon,s=e.value===o;return n.jsxs("button",{"aria-checked":s,className:s?"selected":"",disabled:e.disabled,onClick:()=>{a(e.value),g(!1),b.current?.focus()},role:"menuitemradio","data-tooltip-delay":p,title:e.description??e.label,type:"button",children:[x&&n.jsx("span",{className:"composer-menu-icon",children:t?n.jsx(t,{"aria-hidden":"true"}):null}),n.jsxs("span",{className:"composer-menu-copy",children:[n.jsx("strong",{children:e.label}),e.description?n.jsx("small",{children:e.description}):null]}),n.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:s?n.jsx(O,{className:"composer-menu-check"}):null})]},e.value)})}):null;return n.jsxs("div",{className:"composer-menu",ref:v,onBlur:e=>{const t=e.relatedTarget;t&&(e.currentTarget.contains(t)||y.current?.contains(t))||g(!1)},onKeyDown:e=>{if("Escape"===e.key&&m&&(e.stopPropagation(),e.preventDefault(),g(!1),b.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;if(e.preventDefault(),!m)return void g(!0);const t=[...y.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)')??[]];if(!t.length)return;const n=t.indexOf(document.activeElement),s="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key?1:-1)+t.length)%t.length;t[s]?.focus()},children:[n.jsxs("button",{ref:b,"aria-expanded":m,"aria-haspopup":"menu",className:"composer-option-button "+(m||d?"selected":""),disabled:l,onClick:()=>g(e=>!e),title:r,type:"button",children:[n.jsx(e,{"aria-hidden":"true"}),n.jsx("span",{children:s}),m?n.jsx(z,{"aria-hidden":"true"}):n.jsx(_,{"aria-hidden":"true"})]}),S&&f?k.createPortal(S,document.body):S]})}function gi(e,n,s){const r=t.useRef(null);return t.useEffect(()=>{s&&document.getElementById(`${e}-${n}`)?.scrollIntoView({block:"nearest"})},[e,n,s]),r}function vi({visible:e,listId:t,selectedIndex:s,onHighlight:r,skills:i,onClose:o,onSelect:a,t:c}){const l=gi(t,s,e);return e?n.jsxs("div",{className:"skill-suggestion-popover",children:[n.jsxs("header",{children:[n.jsx("strong",{children:c.skills}),n.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeSkills,children:n.jsx(Be,{"aria-hidden":"true"})})]}),i.length?n.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>n.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":s===i,onMouseEnter:()=>r(i),onClick:()=>a(e),title:e.description??e.name,type:"button",children:[n.jsxs("span",{children:[n.jsxs("strong",{children:["$",e.name]}),e.description?n.jsx("small",{children:e.description}):null]}),n.jsx("em",{children:e.source})]},`${e.source}:${e.name}`))}):n.jsx("p",{children:c.noSkillsFound})]}):null}function yi({visible:e,listId:t,selectedIndex:s,onHighlight:r,commands:i,onClose:o,onSelect:a,t:c}){const l=gi(t,s,e);return e?n.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[n.jsxs("header",{children:[n.jsx("strong",{children:c.commands}),n.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeCommands,children:n.jsx(Be,{"aria-hidden":"true"})})]}),i.length?n.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>n.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":s===i,onMouseEnter:()=>r(i),onClick:()=>a(e),title:e.description,type:"button",children:[n.jsxs("span",{children:[n.jsxs("strong",{children:["/",e.name]}),n.jsx("small",{children:e.argsHint?`${e.title} ${e.argsHint}`:e.title})]}),n.jsx("em",{children:e.source})]},e.name))}):n.jsx("p",{children:c.noCommandsFound})]}):null}function bi({queue:e,controls:s,busy:r,t:i,onCancel:o}){const[a,c]=t.useState(new Set),[l,d]=t.useState(!1),u=t.useId(),h=t.useRef(null),f=t.useRef(0),p=t.useRef(!1),[m,g]=t.useState(null),v=t.useRef(null),y=()=>{v.current=null,g(null)},b=e=>{if(v.current===e)return;const t=e.getBoundingClientRect(),n=Math.min(280,window.innerWidth-16);v.current=e,g({label:e.dataset.queueLabel||"",help:e.dataset.queueHelp||"",left:Math.max(8,Math.min(t.left,window.innerWidth-n-8)),top:t.top<76?t.bottom+7:t.top-7,below:t.top<76})},w=e.length>0&&e.every(e=>e.waitingForStartup),x=w?i.sessionStartingMessage:i.queuedTurns(e.length),S=e.filter(e=>e.clientMessageId),I=S.filter(e=>a.has(e.clientMessageId)),C=r||s.busy,j=I.length?I:S;return t.useLayoutEffect(()=>{e.length>f.current&&(p.current=!0,l&&d(!1)),f.current=e.length,!l&&p.current&&h.current&&(h.current.scrollTop=h.current.scrollHeight,p.current=!1)},[l,e.length]),e.length?n.jsxs("section",{className:"composer-queue-banner","aria-label":x,onPointerMove:e=>{const t=e.target instanceof Element?e.target.closest("button[data-queue-help]"):null;t?b(t):v.current&&y()},onPointerLeave:y,onFocusCapture:e=>{e.target instanceof HTMLButtonElement&&e.target.dataset.queueHelp&&b(e.target)},onBlurCapture:y,onScrollCapture:y,onClickCapture:y,children:[n.jsxs("header",{className:"composer-queue-heading",children:[n.jsx("strong",{"aria-live":"polite",children:x}),n.jsxs("div",{className:"composer-queue-heading-actions",children:[!l&&n.jsx("button",{type:"button","data-queue-label":S.length>0&&I.length===S.length?i.queueClearSelection:i.queueSelectAll,"data-queue-help":i.queueSelectionHelp,disabled:C||!S.length,onClick:()=>c(S.length>0&&I.length===S.length?new Set:new Set(S.map(e=>e.clientMessageId))),children:S.length>0&&I.length===S.length?i.queueClearSelection:i.queueSelectAll}),n.jsx("button",{type:"button",className:"composer-queue-collapse","aria-controls":u,"aria-expanded":!l,"aria-label":l?i.queueExpand:i.queueCollapse,"data-queue-label":l?i.queueExpand:i.queueCollapse,"data-queue-help":l?i.queueExpandHelp:i.queueCollapseHelp,onClick:()=>d(e=>!e),children:l?n.jsx(_,{"aria-hidden":"true"}):n.jsx(z,{"aria-hidden":"true"})})]})]}),n.jsxs("div",{className:"composer-queue-details",id:u,hidden:l,children:[n.jsx("div",{className:"composer-queue-list",ref:h,children:e.map((e,t)=>n.jsxs("div",{className:"composer-queue-item","data-selected":!!e.clientMessageId&&a.has(e.clientMessageId)||void 0,children:[n.jsx("button",{type:"button",className:"queue-select-button","aria-label":i.selectQueuedTurn(t+1),"aria-pressed":!!e.clientMessageId&&a.has(e.clientMessageId),disabled:C||!e.clientMessageId,"data-queue-label":i.selectQueuedTurn(t+1),"data-queue-help":e.content?`${i.queueSelectionHelp}\n${e.content}`:i.queueSelectionHelp,onClick:()=>c(t=>{const n=new Set(t),s=e.clientMessageId;return n.has(s)?n.delete(s):n.add(s),n}),children:n.jsx("span",{children:e.content||i.queuedTurnFallback})}),n.jsxs("div",{className:"queue-row-actions",children:[n.jsxs("span",{className:"queue-remote-receipt",role:"status","aria-label":e.waitingForStartup?i.queuePreparing:i.queueRemoteReceived,title:e.waitingForStartup?i.sessionStartingMessage:i.queueRemoteReceivedHint,children:[n.jsx(W,{"aria-hidden":"true"}),e.waitingForStartup?i.queuePreparing:i.queueRemoteReceived]}),n.jsx("button",{type:"button","data-queue-label":i.queueGuide,"data-queue-help":i.queueGuideHelp,"aria-label":i.guideQueuedTurn(t+1),disabled:C||!e.clientMessageId||!s.canGuide||w,onClick:()=>{s.onAction([e],"guide")},children:n.jsx(Q,{"aria-hidden":"true"})}),n.jsx("button",{type:"button","data-queue-label":i.queueSendNow,"data-queue-help":i.queueSendNowHelp,"aria-label":i.sendQueuedTurnNow(t+1),disabled:C||!e.clientMessageId||!s.canSendNow||w,onClick:()=>{s.onAction([e],"sendNow")},children:n.jsx(Ae,{"aria-hidden":"true"})}),n.jsx("button",{type:"button",className:"queue-withdraw-button","data-queue-label":i.withdraw,"data-queue-help":i.queueWithdrawHelp,"aria-label":i.withdrawQueuedTurn(t+1),disabled:C||!e.clientMessageId,onClick:()=>o(e),children:n.jsx(Be,{"aria-hidden":"true"})})]})]},e.clientMessageId||`${e.enqueuedAt}:${t}`))}),n.jsxs("footer",{className:"queue-batch-actions",children:[I.length>0&&n.jsx("span",{children:i.queueSelectedCount(I.length)}),n.jsxs("button",{type:"button","data-queue-label":I.length?i.queueCollectSelected:i.queueCollectAll,"aria-label":I.length?i.queueCollectSelected:i.queueCollectAll,"data-queue-help":i.queueCollectHelp,disabled:C||j.length<2,onClick:()=>{s.onCollect(j)},children:[n.jsx(he,{"aria-hidden":"true"}),i.queueCollect]}),n.jsx("button",{type:"button","data-queue-label":I.length?i.queueGuideSelected:i.queueGuideAll,"aria-label":I.length?i.queueGuideSelected:i.queueGuideAll,"data-queue-help":i.queueGuideHelp,disabled:C||!j.length||!s.canGuide||w,onClick:()=>{s.onAction(j,"guide")},children:i.queueGuide}),n.jsx("button",{type:"button","data-queue-label":I.length?i.queueSendSelected:i.queueSendAll,"aria-label":I.length?i.queueSendSelected:i.queueSendAll,"data-queue-help":i.queueSendNowHelp,disabled:C||!j.length||!s.canSendNow||w,onClick:()=>{s.onAction(j,"sendNow")},children:i.queueSendNow})]})]}),m&&k.createPortal(n.jsxs("div",{className:"composer-queue-tooltip",role:"tooltip",style:{left:m.left,top:m.top,transform:m.below?void 0:"translateY(-100%)"},children:[n.jsx("strong",{children:m.label}),n.jsx("span",{children:m.help})]}),document.body)]}):null}function wi({replies:e,disabled:s,onSend:r,onChange:i,t:o}){const[a,c]=t.useState(!1),[l,d]=t.useState(""),u=()=>{const t=l.trim();!t||e.length>=20||(e.some(e=>C(e,o)===t)||i?.([...e,t]),d(""),c(!1))};return n.jsxs("div",{className:"quick-reply-row",children:[e.map(t=>{const a=C(t,o);return n.jsxs("span",{className:"quick-reply-item",children:[n.jsx("button",{className:"quick-reply-send",title:a,type:"button",disabled:s||!r,onClick:()=>{r?.(a)},children:a}),i&&n.jsx("button",{className:"quick-reply-remove",type:"button","aria-label":`${o.delete}: ${a}`,title:`${o.delete}: ${a}`,onClick:()=>i(e.filter(e=>e!==t)),children:n.jsx(Be,{"aria-hidden":"true"})})]},t)}),i&&(a?n.jsxs("div",{className:"quick-reply-add-form",children:[n.jsx("input",{autoFocus:!0,"aria-label":o.quickReplyAdd,placeholder:o.quickReplyAdd,value:l,maxLength:1e3,onChange:e=>d(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),u()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),c(!1)))}}),n.jsx("button",{type:"button","aria-label":o.quickReplyAdd,disabled:!l.trim(),onClick:u,children:n.jsx(O,{"aria-hidden":"true"})}),n.jsx("button",{type:"button","aria-label":o.cancel,onClick:()=>c(!1),children:n.jsx(Be,{"aria-hidden":"true"})})]}):n.jsx("button",{type:"button",className:"quick-reply-add","aria-label":o.quickReplyAdd,title:o.quickReplyAdd,disabled:e.length>=20,onClick:()=>c(!0),children:n.jsx(je,{"aria-hidden":"true"})}))]})}function xi(){const e=ms(),[s,r]=t.useState(()=>c().composer.sendMode);return t.useEffect(()=>{const e=()=>r(c().composer.sendMode);return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]),n.jsx(mi,{portal:!0,icon:"guide"===s?Q:fe,label:"guide"===s?e.guide:e.queue,menuLabel:e.mode,value:s,options:[{value:"queue",label:e.queue,description:e.queueHelp},{value:"guide",label:e.guide,description:e.guideHelp}],onSelect:e=>{const t=c();g({...t,composer:{...t.composer,sendMode:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))},align:"right",wide:!0})}function Si({shortcut:e,onChange:t,action:s,t:r}){const i="New session"!==r.newSession,o="傳送快捷鍵"===r.sendShortcut,a="enter"===e?"Enter":"shiftEnter"===e?"Shift+Enter":"Cmd/Ctrl+Enter",c="enter"===e?"shiftEnter":"enter",l="enter"===c?"Enter":"Shift+Enter",d="create"===s?i?"建立":"create":i?r.send:"send",u="create"===s&&i&&!o?"创建":d,h="enter"===e?"Shift+Enter":"Enter",f=i?`${a} ${u};${h} ${o?"換行":"换行"}。${o?"點擊切換為":"点击切换为"} ${l} ${u}`:`${a} to ${d}; ${h} for a newline. Click to switch to ${l} to ${d}`;return n.jsxs("button",{type:"button",className:"submit-shortcut-toggle","data-shortcut":e,"aria-label":f,"aria-pressed":"enter"!==e,onMouseDown:e=>e.preventDefault(),onClick:()=>t(c),children:[n.jsx(ue,{"aria-hidden":"true"}),n.jsx("span",{className:"submit-shortcut-tooltip","aria-hidden":"true",children:f})]})}function ki({leading:e,controls:t,submit:s}){return n.jsxs("div",{className:"composer-toolbar",children:[n.jsxs("div",{className:"composer-scroll-controls",children:[n.jsx("div",{className:"composer-leading-controls",children:e}),n.jsx("div",{className:"composer-control-strip",children:t})]}),s]})}function Ii({label:e,disabled:t,onClick:s}){return n.jsx("button",{type:"button",className:"icon-button",title:e,"aria-label":e,disabled:t,onClick:s,children:n.jsx(je,{"aria-hidden":"true"})})}function Ci({children:e,...t}){return n.jsx("button",{...t,className:"send-button submit-action-button",children:e})}function ji({connected:e,busy:t,sending:s,responding:i,hasDraft:o,uploadBusy:a=!1,shortcut:l,onStop:d,t:u}){const h=s?"sending":i?"replying":"ready",f=i&&!s&&!o,p=s?u.sendingMessage:f?u.stopGenerating:u.send,m=s?u.sendingMessage:i?u.replyingMessage:u.send,v=s?pe:f?Oe:F;return n.jsxs("div",{className:"submit-button-group",children:["desktop"===r().kind&&n.jsx(xi,{}),n.jsx(Si,{shortcut:l,action:"send",t:u,onChange:e=>{const t=c();g({...t,composer:{...t.composer,sendShortcut:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))}}),n.jsxs(Ci,{type:f?"button":"submit","data-state":h,"data-action":f?"stop":"send",disabled:!e||t||s||!f&&(!o||a),"aria-label":p,"aria-description":m,title:f?`${m} · ${u.stopGenerating}`:s?m:`${i?`${m} · `:""}${u.send} · ${"enter"===l?u.sendShortcutEnter:"shiftEnter"===l?u.sendShortcutShiftEnter:u.sendShortcutModEnter}`,onClick:f?d:void 0,children:[i&&!s&&n.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),n.jsx(v,{className:s?"composer-send-spinner":f?"composer-send-stop":void 0,"aria-hidden":"true"}),n.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:m})]})]})}function Ri({value:e,textareaRef:s,onValueChange:r,onKeyDown:i,autoFocus:o,disabled:a,...c}){const l=t.useRef(!1),d=t.useRef(!1);t.useEffect(()=>{if(!o||a||d.current)return;let e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{const e=s.current;if(!e)return;d.current=!0;const t=document.activeElement;t&&t!==document.body&&t!==e||(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length),d.current=!0)})});return()=>cancelAnimationFrame(e)},[o,a,s]);const u=t.useMemo(()=>function(e){let t=0;for(let n=0;n<e.length;n++){const s=e.charCodeAt(n);if(t=s>32&&s<127?t+1:0,t>=4096)return"off"}return"soft"}(e),[e]);return t.useLayoutEffect(()=>{const t=s.current;t&&!l.current&&t.value!==e&&(t.value=e)},[e,s]),n.jsx("textarea",{...c,ref:s,disabled:a,wrap:l.current?s.current?.wrap:u,onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1,r(e.currentTarget.value)},onChange:e=>r(e.currentTarget.value),onKeyDown:e=>{l.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||i?.(e)}})}function Ei(e,t){const n=e.map(e=>({value:e.value,label:e.label,description:e.desc,icon:G}));return n.some(e=>""===e.value)||n.unshift({value:"",label:t.defaultOption,description:t.useDaemonDefaultModel,icon:G}),n}function Mi(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:Pe},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:Le},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:Y},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:Ue}]}function Ti(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:ie},{value:"minimal",label:e.effortMinimal,icon:ie},{value:"low",label:e.effortLow,icon:ie},{value:"medium",label:e.effortMedium,icon:ie},{value:"high",label:e.effortHigh,icon:ie},{value:"xhigh",label:e.effortXHigh,icon:ie},{value:"max",label:e.effortMax,icon:ie},{value:"ultra",label:e.effortUltra,icon:ie}]}function Ai({label:e,triggerContent:s,className:r="",children:i}){const[o,a]=t.useState(!1),c=t.useRef(null),l=t.useId(),d=()=>{a(!1),c.current?.focus()},u=j(d,void 0,o),h=pi(o,c,u,"right");return t.useEffect(()=>{if(!o)return;const e=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&!c.current?.contains(e.target)&&a(!1)},t=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&!c.current?.contains(e.target)&&a(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("focusin",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("focusin",t)}},[o]),n.jsxs("div",{className:`composer-menu ${r}`,onKeyDown:e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),d())},children:[n.jsx("button",{ref:c,type:"button",className:"composer-option-button",title:e,"aria-label":e,"aria-haspopup":"dialog","aria-expanded":o,"aria-controls":o?l:void 0,onClick:()=>a(!o),children:s}),o&&k.createPortal(n.jsx("div",{ref:u,id:l,role:"dialog","aria-label":e,className:"composer-settings-popover",style:h,children:i(d)}),document.body)]})}function Ni(e){const{t}=e;return n.jsxs(n.Fragment,{children:[e.fastMode&&n.jsxs("span",{className:"composer-fast-indicator",role:"status","aria-label":t.fastMode,title:t.fastMode,children:[n.jsx(Ue,{"aria-hidden":"true"}),n.jsx("span",{children:t.fast})]}),n.jsx(Ai,{label:`${t.model} / ${t.effort}`,className:"composer-model-trigger",triggerContent:n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[e.modelLabel," · ",e.effort?e.effortLabel:t.defaultOption]}),n.jsx(_,{"aria-hidden":"true"})]}),children:()=>n.jsxs("div",{className:"composer-model-settings",children:[n.jsx("strong",{children:t.model}),n.jsx(mi,{icon:G,label:e.modelLabel,menuLabel:t.model,tooltipHoverDelay:1500,options:e.modelOptions,value:e.model,onSelect:e.onModelChange,wide:!0}),n.jsx("strong",{children:t.effort}),n.jsx("div",{className:"composer-effort-options",role:"group","aria-label":t.effort,children:e.effortOptions.map(s=>n.jsx("button",{type:"button",disabled:s.disabled,"aria-pressed":e.effort===s.value,title:s.description??s.label,onClick:()=>e.onEffortChange(s.value),children:s.value?s.label:t.defaultOption},s.value))}),n.jsxs("button",{type:"button",role:"switch","aria-checked":e.fastMode,"aria-label":t.fastMode,className:"composer-fast-switch",onClick:()=>e.onFastModeChange(!e.fastMode),children:[n.jsx(ie,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsx("strong",{children:t.fastMode}),n.jsx("small",{children:t.preferFasterResponses})]}),n.jsx("span",{className:"composer-switch-track","aria-hidden":"true",children:n.jsx("span",{})})]})]})})]})}function Di(e){const{t}=e,s=[{label:t.uploadFiles,icon:Se,action:e.onUpload,disabled:e.toolsDisabled},{label:t.skills,icon:Ue,action:e.onSkills,shortcut:"$",disabled:e.toolsDisabled},{label:t.commands,icon:qe,action:e.onCommands,shortcut:"/",disabled:e.toolsDisabled},...e.quickRepliesAvailable?[{label:e.quickRepliesOpen?t.hideQuickReplies:t.showQuickReplies,icon:Fe,action:e.onQuickReplies,disabled:!1}]:[]];return n.jsxs("div",{className:"composer-toolbar desktop-composer-toolbar",children:[n.jsx(Ai,{label:`${t.uploadFiles} / ${t.skills} / ${t.commands}`,className:"composer-tools-trigger",triggerContent:n.jsx(je,{"aria-hidden":"true"}),children:e=>n.jsx("div",{className:"composer-tools-list",children:s.map(({label:t,icon:s,action:r,shortcut:i,disabled:o})=>n.jsxs("button",{type:"button",disabled:o,onClick:()=>{e(),r()},children:[n.jsx(s,{"aria-hidden":"true"}),n.jsx("span",{children:t}),i&&n.jsx("kbd",{children:i})]},t))})}),n.jsx("div",{className:"composer-permission "+("autoApprove"===e.approvalMode?"full-access":""),children:n.jsx(mi,{portal:!0,icon:Pe,label:e.approvalLabel,menuLabel:t.approvalMode,options:e.approvalOptions,value:e.approvalMode,onSelect:e.onApprovalModeChange,wide:!0,blendBackground:!0})}),n.jsx("div",{className:"composer-toolbar-spacer"}),n.jsx(Ni,{...e}),e.voice,e.submit]})}function Pi({onTranscript:e}){const i=r(),[o,l]=t.useState("idle"),[d,u]=t.useState("");t.useEffect(()=>{if(!d||"idle"!==o)return;const e=setTimeout(()=>u(""),5e3);return()=>clearTimeout(e)},[d,o]);const[h,f]=t.useState(0),p=t.useRef(!1);t.useEffect(()=>{if("recording"!==o)return;const e=Date.now();f(0);const t=setInterval(()=>f(Math.floor((Date.now()-e)/1e3)),1e3);return()=>clearInterval(t)},[o]);const[m,g]=t.useState(!1);t.useEffect(()=>{let e=!0;const t=()=>{i.speechSettings?.status().then(t=>{e&&g(t.configured)}).catch(()=>{e&&g(!1)})};return t(),window.addEventListener("vibelet.speech.changed",t),()=>{e=!1,window.removeEventListener("vibelet.speech.changed",t)}},[]);const v=t.useRef(null),y=t.useRef(!0),b=t.useRef(e);b.current=e;const w=a(c().language),x="en"!==w;return t.useEffect(()=>(y.current=!0,()=>{y.current=!1,v.current?.stream.getTracks().forEach(e=>e.stop()),"recording"===v.current?.state&&v.current.stop()}),[]),m&&i.transcribeAudio&&"true"===s().getItem("vibelet.web.voice.enabled")?n.jsxs("span",{className:"voice-input-control","data-voice-state":o,children:[n.jsx("button",{className:"icon-button",type:"button",disabled:"idle"!==o&&"recording"!==o,"aria-label":x?"recording"===o?"停止录音":"语音输入":"recording"===o?"Stop recording":"Voice input",title:"recording"===o?x?"停止录音":"Stop recording":x?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{"recording"===o?"recording"===v.current?.state&&v.current.stop():(async()=>{if(!p.current){p.current=!0,u(""),l("starting");try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});if(!y.current)return void t.getTracks().forEach(e=>e.stop());let n;try{n=new MediaRecorder(t,{mimeType:"audio/webm"})}catch(e){throw t.getTracks().forEach(e=>e.stop()),e}v.current=n;const s=[];let r=0;n.ondataavailable=e=>{s.push(e.data),r+=e.data.size,r>9437184&&"recording"===n.state&&n.stop()};const o=setTimeout(()=>{"recording"===n.state&&n.stop()},6e4);n.onstop=async()=>{if(clearTimeout(o),t.getTracks().forEach(e=>e.stop()),v.current=null,y.current){l("transcribing");try{const e=new Blob(s,{type:"audio/webm"}),t=await(i.speechSettings?.status()),n="system"===t?.engine||"volcengine"===t?.engine?await async function(e){const t=new AudioContext;try{const n=await t.decodeAudioData(await e.arrayBuffer());if(n.duration>61||n.duration<=0)throw new Error("Invalid recording duration");const s=new Uint8Array(44+2*n.length),r=new DataView(s.buffer),i=(e,t)=>[...t].forEach((t,n)=>r.setUint8(e+n,t.charCodeAt(0)));i(0,"RIFF"),r.setUint32(4,s.length-8,!0),i(8,"WAVEfmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,n.sampleRate,!0),r.setUint32(28,2*n.sampleRate,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,"data"),r.setUint32(40,s.length-44,!0);const o=Array.from({length:n.numberOfChannels},(e,t)=>n.getChannelData(t));for(let e=0;e<n.length;e++){const t=Math.max(-1,Math.min(1,o.reduce((t,n)=>t+n[e],0)/o.length));r.setInt16(44+2*e,t*(t<0?32768:32767),!0)}return s}finally{await t.close()}}(e):new Uint8Array(await e.arrayBuffer()),r=await i.transcribeAudio(n,"zh-TW"===w?"zh-TW":x?"zh":"en");if(y.current)if(r.trim()){u("");let e=r;const t=await(i.polishSettings?.status().catch(()=>{}));if(!y.current)return;if(t?.settings.enabled&&i.polishTranscript){l("polishing");try{const t=await i.polishTranscript(r);e=t.text,y.current&&"fallback"===t.status&&u(x?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{y.current&&u(x?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}y.current&&b.current(e)}else u(x?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{y.current&&u(x?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{p.current=!1,y.current&&l("idle")}}};try{n.start(1e3)}catch(e){throw clearTimeout(o),t.getTracks().forEach(e=>e.stop()),v.current=null,e}l("recording")}catch{p.current=!1,y.current&&(l("idle"),u(x?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}})()},children:"recording"===o?n.jsx(Oe,{"aria-hidden":"true"}):"idle"===o?n.jsx(ye,{"aria-hidden":"true"}):n.jsx(pe,{className:"voice-input-spinner","aria-hidden":"true"})}),"idle"!==o&&n.jsxs("span",{className:"voice-input-progress",children:["recording"===o&&n.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[n.jsx("i",{}),n.jsx("i",{}),n.jsx("i",{})]}),n.jsx("span",{role:"status","aria-live":"polite",children:"recording"===o?x?"录音中":"Recording":"polishing"===o?x?"润色中":"Polishing":"transcribing"===o?x?"识别中":"Transcribing":x?"开启麦克风":"Opening microphone"}),"recording"===o&&n.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(h).padStart(2,"0")]})]}),"idle"===o&&d&&n.jsx("span",{className:"voice-input-error",role:"alert",children:d})]}):null}function Li({client:e,activeSessionId:s,activeQueue:i,queueControls:o,agent:a,attachments:c,approvalMode:l,activeModelOptions:d,busy:u,sending:h,responding:f,onStop:p,draft:m,effort:g,fastMode:v,model:y,phase:b,quickReplies:w,onQuickRepliesChange:x,quickRepliesOpen:S=!1,onQuickRepliesOpenChange:k,onSendQuickReply:I,sendShortcut:C,skills:j,uploadBusy:R,t:E,onApprovalModeChange:M,onCancelQueuedTurn:T,onDraftChange:A,onEffortChange:N,onFastModeChange:D,onModelChange:P,onRefreshSkills:L,onRemoveAttachment:F,onOpenRemoteFile:q,onSubmit:O,onUploadFiles:_}){const $=function(e,n,s,i){const o=t.useRef({draft:s,responding:i});o.current={draft:s,responding:i};const[a,c]=t.useState(null);t.useEffect(()=>{if(c(null),!e||!n||"desktop"!==r().kind)return;const t=e.onMessage(t=>{if("sessionId"in t&&t.sessionId===n)if("session.prediction"===t.type){if(o.current.draft||o.current.responding)return;c({client:e,sessionId:n,text:t.text?.trim().slice(0,2e3)??""})}else"text.delta"!==t.type&&"session.interrupted"!==t.type||c(null)}),s=e.onClose(()=>c(null));return()=>{t(),s()}},[e,n]),t.useEffect(()=>{(i||s)&&c(null)},[i,s]);const l=i||s||a?.client!==e||a?.sessionId!==n?"":a?.text??"";return{text:l,handleKeyDown:(e,t)=>!(!l||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey||"Tab"!==e.key&&"Escape"!==e.key||(e.preventDefault(),"Tab"===e.key&&t(l),c(null),0))}}(e,s,m,f||h),z=t.useRef(null),H=t.useRef(null),[B]=t.useState(()=>"desktop"===r().kind||(window.matchMedia?.("(pointer: fine)").matches??!1)),[U,W]=t.useState(!1),[K,V]=t.useState(!1),[Q,J]=t.useState(!1),[Z,X]=t.useState(""),[Y,ee]=t.useState(""),te=t.useRef(null),ne=t.useRef(null),se="connected"===b,re=t.useMemo(()=>ws(a),[a]),oe=t.useMemo(()=>Ss(m),[m]),ae=oe?`${oe.start}:${oe.end}:${oe.keyword}`:"",ce=Boolean(Q||oe&&Y!==ae),le=t.useMemo(()=>function(e,t,n=8){const s=xs(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>ks(e,s)-ks(t,s)):[...e]).slice(0,n)}(re,oe?.keyword??"",8),[re,oe?.keyword]),de=t.useMemo(()=>As(m),[m]),ue=de?`${de.start}:${de.end}:${de.keyword}`:"",he=Boolean(!ce&&(K||de&&Z!==ue)),fe=t.useMemo(()=>function(e,t,n=8){const s=Ms(t);return(s?e.filter(e=>Ms(e.name).includes(s)):e).slice(0,n)}(j,de?.keyword??"",8),[de?.keyword,j]),pe=t.useMemo(()=>Mi(E),[E]),me=t.useMemo(()=>Ti(E),[E]),ge=d.find(e=>e.value===y),ve=ge?.label??(y||E.defaultOption),ye=pe.find(e=>e.value===l)?.label??l,be=me.find(e=>e.value===g)?.label??g,we=Ei(d,E);t.useEffect(()=>{de||(te.current=null,X(""),V(!1))},[de]),t.useEffect(()=>{oe||(ne.current=null,ee(""),J(!1))},[oe]);const xe=()=>{const e=function(e,t){if(!t)return e;const n=As(e);if(!n||n.start!==t.triggerStart)return e;const s=n.start>t.draftBeforeInsertion.length?" ":"";return e.slice(0,n.start)!==`${t.draftBeforeInsertion}${s}`?e:t.draftBeforeInsertion}(m,te.current);te.current=null,e!==m&&A(e),ue&&X(ue),V(!1),H.current?.focus()},Se=()=>{const e=function(e,t){return t&&Ss(e)?t.draftBeforeInsertion:e}(m,ne.current);ne.current=null,e!==m&&A(e),ae&&ee(ae),J(!1),H.current?.focus()},ke=()=>{ce?Se():(ee(""),Ss(m)||0!==m.length||(ne.current={draftBeforeInsertion:m},A("/")),J(!0),H.current?.focus())},Ie=e=>{const t=Ss(m),n=function(e,t,n){return t?function(e,t,n){return`${e.slice(0,t.start)}${Is(n,"")}${e.slice(t.end)}`}(e,t,n):`${Is(n,e)}${e}`}(m,t,e);A(n),ne.current=null,J(!1),ee(""),H.current?.focus()},Ce=()=>{if(he)xe();else{if(L(),X(""),!As(m)){const e=0===m.length||/\s$/.test(m)?"":" ";te.current={draftBeforeInsertion:m,triggerStart:m.length+e.length},A(`${m}${e}$`)}V(!0),H.current?.focus()}},je=e=>{const t=As(m),n=t?function(e,t,n){return`${e.slice(0,t.start)}$${Ms(n)} ${e.slice(t.end)}`}(m,t,e.name):m.trim().length?`${m}${/\s$/.test(m)?"":" "}$${e.name} `:`$${e.name} `;A(n),te.current=null,V(!1),X(""),H.current?.focus()},Re=function({context:e,count:n,onSelect:s,onClose:r}){const i=t.useId(),[o,a]=t.useState({context:"",index:0}),c=o.context===e?Math.min(o.index,Math.max(0,n-1)):0,l=t=>a({context:e,index:t});return{listId:i,selectedIndex:c,selectIndex:l,handleKeyDown:t=>!(!e||t.nativeEvent.isComposing||229===t.nativeEvent.keyCode||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||("Escape"===t.key?(t.preventDefault(),t.stopPropagation(),r(),0):!n||("ArrowDown"===t.key||"ArrowUp"===t.key?(t.preventDefault(),t.stopPropagation(),l((c+("ArrowDown"===t.key?1:-1)+n)%n),0):"Enter"!==t.key&&"Tab"!==t.key||(t.preventDefault(),t.stopPropagation(),s(c),0))))}}({context:ce?`command:${ae}:${le.map(e=>e.name).join(",")}`:he?`skill:${ue}:${fe.map(e=>`${e.source}:${e.name}`).join(",")}`:"",count:ce?le.length:he?fe.length:0,onSelect:e=>ce?Ie(le[e]):je(fe[e]),onClose:ce?Se:xe});return n.jsxs("form",{className:"composer "+(U?"dragging":""),onDragEnter:e=>{e.preventDefault(),W(!0)},onDragLeave:()=>W(!1),onDragOver:e=>e.preventDefault(),onDrop:e=>{(async e=>{e.preventDefault(),W(!1),se&&await _(e.dataTransfer.files)})(e)},onSubmit:e=>{e.preventDefault(),se&&O(e)},children:[n.jsx(bi,{queue:i,controls:o,busy:u,t:E,onCancel:T}),S&&n.jsx(wi,{replies:w,disabled:!se||u||h||R,onSend:I,onChange:x,t:E}),n.jsx(vi,{visible:he,skills:fe,listId:Re.listId,selectedIndex:Re.selectedIndex,onHighlight:Re.selectIndex,onClose:xe,onSelect:je,t:E}),n.jsx(yi,{visible:ce,commands:le,listId:Re.listId,selectedIndex:Re.selectedIndex,onHighlight:Re.selectIndex,onClose:Se,onSelect:Ie,t:E}),n.jsx(Ri,{textareaRef:H,autoFocus:B,"aria-controls":ce||he?Re.listId:void 0,"aria-activedescendant":ce&&le.length||he&&fe.length?`${Re.listId}-${Re.selectedIndex}`:void 0,"aria-autocomplete":"list",value:m,onValueChange:A,onPaste:e=>{(async e=>{se&&e.clipboardData.files.length&&await _(e.clipboardData.files)})(e)},onKeyDown:e=>{Re.handleKeyDown(e)||$.handleKeyDown(e,A)||"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||Mr(C,e)&&(e.preventDefault(),se&&!e.repeat&&O())},placeholder:$.text?`${$.text} ⇥ Tab`:E.messagePlaceholder,rows:3}),n.jsx(fi,{attachments:c,uploadBusy:R,onRemove:F,onOpen:q,t:E}),n.jsx("input",{ref:z,type:"file",multiple:!0,hidden:!0,onChange:e=>{(async(e,t)=>{await _(e),t.value=""})(e.currentTarget.files,e.currentTarget)}}),"desktop"===r().kind?n.jsx(Di,{t:E,approvalMode:l,approvalLabel:ye,approvalOptions:pe,onApprovalModeChange:M,model:y,modelLabel:ve,modelOptions:we,onModelChange:P,effort:g,effortLabel:be||E.effort,effortOptions:me,onEffortChange:N,fastMode:v,onFastModeChange:D,toolsDisabled:!se||R,onUpload:()=>z.current?.click(),onSkills:Ce,onCommands:ke,quickRepliesAvailable:w.length>0||!!x,quickRepliesOpen:S,onQuickReplies:()=>k?.(!S),voice:n.jsx(Pi,{onTranscript:e=>A(m?`${m} ${e}`:e)}),submit:n.jsx(ji,{connected:se,busy:u,sending:h,responding:f,hasDraft:!!m.trim()||c.length>0,uploadBusy:R||c.some(e=>e.uploading),shortcut:C,onStop:p,t:E})}):n.jsx(ki,{leading:n.jsxs(n.Fragment,{children:[n.jsx(Pi,{onTranscript:e=>A(m?`${m} ${e}`:e)}),n.jsx(Ii,{label:E.uploadFiles,disabled:!se||R,onClick:()=>z.current?.click()}),w.length>0||x?n.jsx("button",{className:"icon-button quick-replies-toggle "+(S?"selected":""),type:"button",title:S?E.hideQuickReplies:E.showQuickReplies,"aria-label":S?E.hideQuickReplies:E.showQuickReplies,"aria-pressed":S,onClick:()=>k?.(!S),children:n.jsx(Fe,{"aria-hidden":"true"})}):null,n.jsx("button",{className:"icon-button "+(he?"selected":""),type:"button",title:E.skills,"aria-label":E.skills,onClick:Ce,disabled:!se||R,children:n.jsx(Ue,{"aria-hidden":"true"})}),n.jsx("button",{className:"icon-button "+(ce?"selected":""),type:"button",title:E.commands,"aria-label":E.commands,onClick:ke,disabled:!se||R,children:n.jsx(qe,{"aria-hidden":"true"})})]}),controls:n.jsxs(n.Fragment,{children:[n.jsx(mi,{portal:!0,icon:"autoApprove"===l?Ue:Pe,label:ye,menuLabel:E.approvalMode,blendBackground:!0,options:pe,value:l,onSelect:M,wide:!0}),n.jsx(mi,{portal:!0,icon:G,label:ve,menuLabel:E.model,tooltipHoverDelay:1500,options:we,value:y,onSelect:P,align:"right",wide:!0}),n.jsx(mi,{portal:!0,icon:ie,label:be||E.effort,menuLabel:E.effort,options:me,value:g,onSelect:N,align:"right"}),n.jsx(mi,{portal:!0,icon:Ue,label:v?E.fast:E.normal,menuLabel:E.fastMode,options:[{value:"off",label:E.normal,description:E.standardExecution,icon:ie},{value:"on",label:E.fast,description:E.preferFasterResponses,icon:Ue}],value:v?"on":"off",onSelect:e=>D("on"===e),align:"right",selected:v,wide:!0})]}),submit:n.jsx(ji,{connected:se,busy:u,sending:h,responding:f,hasDraft:!!m.trim()||c.length>0,uploadBusy:R||c.some(e=>e.uploading),shortcut:C,onStop:p,t:E})})]})}function Fi({terminals:e,t:s}){const[r,i]=t.useState(Date.now),o=e?.length??0;return t.useEffect(()=>{if(!o)return;i(Date.now());const e=window.setInterval(()=>i(Date.now()),1e3);return()=>window.clearInterval(e)},[o]),o?n.jsxs("details",{className:"background-terminals",children:[n.jsxs("summary",{children:[n.jsx($e,{"aria-hidden":"true"}),n.jsx("span",{role:"status",children:s.backgroundTerminalsRunning(o)}),n.jsx(_,{className:"background-terminal-chevron","aria-hidden":"true"})]}),n.jsx("p",{children:s.backgroundTerminalsHint}),n.jsx("ul",{children:e.map(e=>{const t=Date.parse(e.startedAt),i=Number.isFinite(t)?Math.max(0,Math.floor((r-t)/1e3)):0;return n.jsxs("li",{children:[n.jsxs("span",{children:[s.backgroundTerminalLabel," #",e.id]}),n.jsxs("time",{children:[Math.floor(i/60),":",String(i%60).padStart(2,"0")]})]},e.id)})})]}):null}function qi(e,n){const[s,r]=t.useState(null),i=t.useRef(null);return t.useEffect(()=>()=>{null!==i.current&&window.clearTimeout(i.current)},[]),{copyText:t.useCallback(async t=>{try{await _n(t),r({message:e,tone:"success"})}catch{r({message:n,tone:"error"})}null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r(null),2400)},[n,e]),feedback:s}}function Oi({feedback:e}){if(!e)return null;const t="success"===e.tone?O:Be;return n.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[n.jsx(t,{"aria-hidden":"true"}),e.message]})}function _i({message:e,retryLabel:t,onRetry:s,onDismiss:r,closeLabel:i}){return n.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[r?n.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:r,children:n.jsx(Be,{"aria-hidden":"true"})}):n.jsx(H,{"aria-hidden":"true"}),n.jsx("span",{children:e}),n.jsxs("button",{className:"chat-notice-retry",onClick:s,type:"button",children:[n.jsx(Re,{"aria-hidden":"true"}),t]})]})}function $i({label:e}){return n.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[n.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),n.jsxs("div",{className:"history-loading-copy",children:[n.jsx("strong",{children:e}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("span",{"aria-hidden":"true"})]})]})}function zi({failedSend:e,onRetry:t,onDismiss:s,t:r}){const i={network:r.sendFailedNetwork,timeout:r.sendFailedTimeout,reconnect:r.sendFailedReconnect,permission:r.sendFailedPermission,subscription:r.sendFailedSubscription,"missing-resource":r.sendFailedMissingResource,unknown:r.sendFailedUnknown}[e.kind];return n.jsxs("div",{className:"failed-send-notice",role:"alert",children:[n.jsx(H,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsx("strong",{children:"timeout"===e.kind?r.sendUnconfirmed:r.sendFailed}),i,e.message&&n.jsx("blockquote",{className:"failed-send-content",children:e.message}),!!e.images?.length&&n.jsx("small",{children:r.failedSendImages(e.images.length)})]}),n.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[n.jsx(Re,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?r.retrying:r.retrySend]}),s&&n.jsx("button",{className:"chat-notice-dismiss",onClick:s,type:"button","aria-label":r.close,title:r.close,children:n.jsx(Be,{"aria-hidden":"true"})})]})}function Hi({label:e,onClick:t}){return n.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:n.jsx(D,{"aria-hidden":"true"})})}const Bi=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Ui=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,Wi=new Set(["","{}","[]","null","undefined",'""']);function Ki(e){return e.replace(/\s+/g," ").trim()}function Vi(e,t){return"string"==typeof e[t]?e[t]:""}function Qi(e,t){return"number"==typeof e[t]?e[t]:void 0}function Gi(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Ji(e){const t=[],n=Vi(e,"file_path")||Vi(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=Qi(e,"offset"),r=Qi(e,"limit");if(void 0!==s||void 0!==r){const e=[];void 0!==s&&e.push(`line ${s+1}`),void 0!==r&&e.push(`to ${void 0!==s?s+r:r}`),t.push({label:"Range",value:e.join(" ")})}return t}function Zi(e){const t=function(e){return"string"!=typeof e?"":e.replace(/\r\n?/g,"\n").replace(Bi,"").replace(Ui,"").trim()}(e);return Wi.has(t)?"":t}function Xi(e){const t=Zi(e);if(!t)return"";try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e)){const t="string"==typeof e.query?Ki(e.query):"";if(t)return t;const n="string"==typeof e.command?Ki(e.command):"";if(n)return n;const s="string"==typeof e.description?Ki(e.description):"";if(s)return s}}catch{}return Ki(t)}function Yi(e){return"tool"===e.role||"info"===e.type&&!/^Error:/i.test(e.content.trim())}function eo(e){const t=[];for(const n of e){const e=n.toolName?.trim();e&&!t.includes(e)&&t.push(e)}return t.length?t.join(", "):e.map(e=>Xi(e.content)).find(Boolean)??""}function to(e,t){return e.historyKey?e.historyKey:`${e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}function no(e){return"en"===e?{title:"Image viewer",previous:"Previous image",next:"Next image",copy:"Copy image",copied:"Image copied",failed:"Could not copy image",open:"Open original in tab",close:"Close",unavailable:"Image unavailable"}:"zh-TW"===e?{title:"圖片檢視器",previous:"上一張",next:"下一張",copy:"複製圖片",copied:"圖片已複製",failed:"圖片複製失敗",open:"在 Tab 開啟原檔案",close:"關閉",unavailable:"無法載入圖片"}:{title:"图片查看器",previous:"上一张",next:"下一张",copy:"复制图片",copied:"图片已复制",failed:"图片复制失败",open:"在 Tab 打开原文件",close:"关闭",unavailable:"无法加载图片"}}function so({position:e,onClose:s,onCopy:r,onCopyImage:i,copyImageLabel:o,onRevealFile:a,revealFileLabel:c,onRewind:l,onToggleSource:d,sourceOpen:u,t:h}){const f=t.useRef(null),p=t.useRef(s);p.current=s,t.useLayoutEffect(()=>{const t=f.current,n=document.activeElement,s=t.getBoundingClientRect();t.style.left=`${Math.max(8,Math.min(e.x,innerWidth-s.width-8))}px`,t.style.top=`${Math.max(8,Math.min(e.y,innerHeight-s.height-8))}px`,t.querySelector("button")?.focus({preventScroll:!0});const r=()=>p.current(),i=e=>{t.contains(e.target)||r()};return document.addEventListener("pointerdown",i),document.addEventListener("scroll",r,!0),window.addEventListener("resize",r),window.addEventListener("blur",r),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r),window.removeEventListener("blur",r),t.contains(document.activeElement)&&n?.focus({preventScroll:!0})}},[e]);const m=e=>{s(),e()};return k.createPortal(n.jsxs("div",{ref:f,role:"menu","aria-label":h.messageActions,className:"session-context-menu message-context-menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},onKeyDown:e=>{e.stopPropagation();const t=Array.from(f.current.querySelectorAll("button:not(:disabled)")),n=t.indexOf(document.activeElement);["Escape","Tab","ArrowDown","ArrowUp","Home","End"].includes(e.key)&&e.preventDefault(),"Escape"!==e.key&&"Tab"!==e.key||s(),"ArrowDown"===e.key&&t[(n+1)%t.length]?.focus(),"ArrowUp"===e.key&&t[(n-1+t.length)%t.length]?.focus(),"Home"===e.key&&t[0]?.focus(),"End"===e.key&&t.at(-1)?.focus()},children:[i&&n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m(i),children:[n.jsx(V,{"aria-hidden":"true"}),o]}),a&&n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m(a),children:[n.jsx(ne,{"aria-hidden":"true"}),c]}),l&&n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m(l),children:[n.jsx(Ee,{"aria-hidden":"true"}),$s().rewind]}),n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m(r),children:[n.jsx(V,{"aria-hidden":"true"}),h.copyMessage]}),n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m(d),children:[n.jsx(K,{"aria-hidden":"true"}),u?h.hideMarkdownSource:h.viewMarkdownSource]})]}),document.body)}function ro({message:e,t}){return n.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function io(e){if(!(e instanceof Element))return;const t=e.closest("[data-image-src], [data-file-path], a[href]");return t?ri(t.dataset.imageSrc??t.dataset.filePath??t.getAttribute("href"))??void 0:void 0}function oo(e){return"en"===e?"Show in file manager":"zh-TW"===e?"在檔案管理中顯示":"在文件管理中显示"}async function ao(e){const t=new Image;t.crossOrigin="anonymous",t.src=e,await t.decode();const n=document.createElement("canvas");n.width=t.naturalWidth,n.height=t.naturalHeight;const s=n.getContext("2d");if(!s)throw new Error("Canvas unavailable");return s.drawImage(t,0,0),await new Promise((e,t)=>n.toBlob(n=>n?e(n):t(new Error("Image conversion failed")),"image/png"))}async function co(e){const t=r().writeClipboardImage;t?await t(new Uint8Array(await(await ao(e)).arrayBuffer())):await navigator.clipboard.write([new ClipboardItem({"image/png":ao(e)})])}function lo(e){if(!(e instanceof Element))return;const t=e.closest(".message-image-preview");return t?.dataset.imageSrc&&t.querySelector("img")?{src:t.dataset.imageSrc,cwd:t.dataset.imageCwd}:void 0}function uo({field:e}){return e.isDiff?n.jsxs("div",{className:"tool-field diff",children:[n.jsx("span",{children:e.label}),e.diffOld?n.jsxs("pre",{className:"tool-diff old",children:[n.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?n.jsxs("pre",{className:"tool-diff new",children:[n.jsx("b",{children:"+"}),e.diffNew]}):null]}):n.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[n.jsx("span",{children:e.label}),n.jsx("pre",{children:e.value})]})}function ho({message:e,onCopy:t,t:s}){const r=function(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return Ji(t);case"write":{const e=Ji(t),n=Vi(t,"content");return n&&e.push({label:"Content",isDiff:!0,value:"",diffNew:Gi(n,500)}),e}case"edit":{const e=Ji(t),n=Vi(t,"old_string")||Vi(t,"oldString"),s=Vi(t,"new_string")||Vi(t,"newString");return(n||s)&&e.push({label:"Change",isDiff:!0,value:"",diffOld:Gi(n,300),diffNew:Gi(s,300)}),e}case"bash":{const e=Vi(t,"command");return e?[{label:"Command",value:e,isCode:!0}]:[]}case"websearch":{const e=Vi(t,"query");return e?[{label:"Query",value:e}]:[]}case"webfetch":{const e=[],n=Vi(t,"url");n&&e.push({label:"URL",value:n});const s=Vi(t,"prompt");return s&&e.push({label:"Prompt",value:Gi(s,200)}),e}case"glob":{const e=Vi(t,"pattern");return e?[{label:"Pattern",value:e}]:[]}case"grep":{const e=[],n=Vi(t,"pattern");n&&e.push({label:"Pattern",value:n,isCode:!0});const s=Vi(t,"path");return s&&e.push({label:"In",value:s,isFilePath:!0}),e}default:{const e=[],n=Vi(t,"command");if(n)return[{label:"Command",value:n,isCode:!0}];const s=Vi(t,"file_path")||Vi(t,"filePath");s&&e.push({label:"Path",value:s,isFilePath:!0});const r=Vi(t,"description");r&&e.push({label:"Description",value:Gi(r,200)});const i=Vi(t,"query");i&&e.push({label:"Query",value:i});const o=Vi(t,"url");return o&&e.push({label:"URL",value:o}),e}}}(e.toolName,e.toolInput),i=Xi(e.content),o=Zi(e.content),a=function(e){return Zi(e).length>0}(e.content)&&!r.length,c=e.toolName??s.tool;return n.jsxs("section",{className:"tool-detail-card",children:[n.jsxs("header",{children:[n.jsx("span",{className:"tool-detail-icon",children:n.jsx($e,{"aria-hidden":"true"})}),n.jsxs("div",{children:[n.jsx("strong",{children:c}),i?n.jsx("small",{title:i,children:i}):null]}),n.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:s.copyOutput,children:n.jsx(V,{"aria-hidden":"true"})})]}),r.length?n.jsx("div",{className:"tool-fields",children:r.map((e,t)=>n.jsx(uo,{field:e},`${e.label}:${t}`))}):null,a?n.jsx("pre",{className:"json-box compact",children:o}):null]})}function fo({messages:e,showHeader:t=!0,onClose:s,onCopy:r,t:i}){if(!e.length)return null;const o=e.filter(e=>"tool"===e.role).length||e.length,a=i.toolCallCount(o),c=eo(e),l=e.map(e=>e.content).join("\n\n");return n.jsxs("section",{className:"tool-inline-panel","aria-label":i.toolDetails,children:[t?n.jsxs("header",{className:"inline-detail-header",children:[n.jsxs("div",{className:"inline-detail-title",children:[n.jsx("strong",{children:a}),n.jsx("span",{title:c,children:c||i.toolDetail})]}),n.jsxs("div",{className:"row-actions",children:[n.jsx("button",{className:"icon-button",onClick:()=>r(l),type:"button",title:i.copyOutput,children:n.jsx(V,{"aria-hidden":"true"})}),n.jsx("button",{className:"icon-button",onClick:s,type:"button",title:i.closeToolDetails,children:n.jsx(Be,{"aria-hidden":"true"})})]})]}):null,n.jsx("div",{className:"tool-detail-list",children:e.map((e,t)=>n.jsx(ho,{message:e,onCopy:r,t:i},`${e.historyKey??e.timestamp??e.toolName??"tool"}:${t}`))})]})}const po=t.lazy(async()=>R(()=>import("./mermaid-O7DHMXV3-DKlyhw3K.js").then(e=>e.a),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.MessageMarkdown})));function mo({label:e}){return n.jsxs("span",{className:"message-replying-indicator","aria-label":e,role:"status",children:[n.jsxs("span",{"aria-hidden":"true",className:"message-replying-dots",children:[n.jsx("i",{}),n.jsx("i",{}),n.jsx("i",{})]}),n.jsx("span",{children:e})]})}function go({activeMatch:e,baseCwd:s,message:r,onCopy:i,onRewind:o,onCloseTool:l,onOpenRemoteFile:d,onToggleSource:u,onToggleTool:h,sourceOpen:f,toolOpen:p,replying:m,queued:g,t:v}){const y="assistant"===r.role?Ft(r.content):r.content,[b,w]=t.useState(null),x=qn(),[S,k]=t.useState(""),I=no(a(c().language)),C="user"===r.role&&"info"!==r.type?o:void 0,j=function(e,t,n=!1){const s="interrupted"===e.delivery?"interrupted":n||"accepted"===e.delivery?"delivered":e.localDelivery;if("user"!==e.role||!s)return null;const r="浏览器"===t.browser?{interrupted:"已中断",sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可以退出客户端。任务将由 daemon 继续处理。"}:"瀏覽器"===t.browser?{interrupted:"已中斷",sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可以退出客戶端。任務將由 daemon 繼續處理。"}:{interrupted:"Interrupted",sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer. You can quit the client; the daemon will continue processing."};return{state:s,label:r[s],title:"delivered"===s?r.hint:r[s]}}(r,v,g),E=(r.images??[]).filter(e=>Nn(e,"")||/^(?:data:image\/|https?:\/\/|blob:)/i.test(e)),M="tool"===r.role?Xi(r.content):"";return n.jsxs("article",{className:`message ${r.role} ${"info"===r.type?"info":""} ${e?"match":""}`,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w({x:e.clientX,y:e.clientY,image:lo(e.target),file:io(e.target)})},onKeyDown:e=>{if("ContextMenu"!==e.key&&(!e.shiftKey||"F10"!==e.key))return;e.preventDefault(),e.stopPropagation();const t=e.currentTarget.getBoundingClientRect();w({x:t.left+16,y:t.top+16,image:lo(e.target),file:io(e.target)})},children:[b&&n.jsx(so,{position:b,onClose:()=>w(null),onCopy:()=>i(r.content),onCopyImage:b.image?()=>{(async e=>{k("");try{await async function({src:e,cwd:t}){const n=ri(e);if(!n)return co(e);const s=sn();if(!s)throw new Error("No pairing");const r=await di(Dn(n,t),s.pairToken),i=URL.createObjectURL(r);try{await co(i)}finally{URL.revokeObjectURL(i)}}(e),k(I.copied)}catch{k(I.failed)}})(b.image)}:void 0,copyImageLabel:I.copy,onRevealFile:b.file&&x?()=>x.reveal(b.file,s):void 0,revealFileLabel:oo(a(c().language)),onRewind:C,onToggleSource:u,sourceOpen:f,t:v}),S&&n.jsx("div",{className:"message-image-copy-status",role:"status",children:S}),n.jsxs("div",{className:"message-meta",children:[n.jsx("span",{children:Pt(r,v)}),n.jsxs("div",{className:"message-meta-side",children:[j&&n.jsx("span",{className:"message-delivery","data-state":j.state,role:"status","aria-label":j.label,title:j.title,children:j.label}),n.jsx("time",{children:Dt(r.timestamp,Date.now(),v)})]})]}),f?n.jsx(ro,{message:r,t:v}):"tool"===r.role?n.jsxs("button",{className:"tool-inline-summary","aria-expanded":p,onClick:h,type:"button",children:[n.jsxs("span",{children:[n.jsx(He,{"aria-hidden":"true"}),r.toolName??v.tool]}),M?n.jsx("small",{children:M}):null]}):"assistant"===r.role||"user"===r.role?n.jsx(t.Suspense,{fallback:n.jsx("pre",{children:y}),children:n.jsx(po,{baseCwd:s,content:bt(y,r.images),onOpenRemoteFile:d,additionalImages:E})}):n.jsx("pre",{children:r.content}),r.images?.length?n.jsx("div",{className:"message-image-attachments",children:r.images.map(e=>E.includes(e)?n.jsx(hi,{src:e,cwd:s,onOpen:d,gallery:async()=>[...(await R(async()=>{const{collectMessageImages:e}=await import("./collectMessageImages-ZyOAE6id.js");return{collectMessageImages:e}},__vite__mapDeps([4,1,2]))).collectMessageImages(r.content,s),...E.map(e=>({src:e,cwd:s}))]},e):n.jsxs("button",{type:"button",className:"message-file-attachment",title:e,"data-file-path":e,onClick:()=>d(e,s),children:[n.jsx(Se,{size:16,"aria-hidden":"true"}),wn(e)]},e))}):null,"tool"===r.role&&p?n.jsx(fo,{messages:[r],onClose:l,onCopy:i,t:v}):null,m&&n.jsx(mo,{label:v.replyingMessage}),n.jsxs("div",{className:"message-actions","aria-label":v.messageActions,role:"group",children:[C&&n.jsx("button",{type:"button",onClick:C,title:$s().rewind,"aria-label":$s().rewind,children:n.jsx(Ee,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":v.copyMessage,onClick:()=>i(f?r.content:y),title:v.copyMessage,type:"button",children:n.jsx(V,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":v.viewMarkdownSource,"aria-expanded":f,onClick:u,title:f?v.hideMarkdownSource:v.viewMarkdownSource,type:"button",children:n.jsx(K,{"aria-hidden":"true"})})]})]})}function vo(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function yo({activeMatch:e,expanded:t,messages:s,onToggle:r,t:i}){const o=eo(s),a=function(e,t){const n={read:t.interactionRead,read_file:t.interactionRead,edit:t.interactionEdit,write:t.interactionEdit,apply_patch:t.interactionEdit,grep:t.interactionSearch,glob:t.interactionSearch,bash:t.interactionCommand,exec_command:t.interactionCommand},s=new Map;for(const r of e.filter(e=>"tool"===e.role)){const e=r.toolName||"Tool",t=n[e.toLowerCase()]??e;s.set(t,(s.get(t)??0)+1)}return[...s].map(([e,t])=>t>1?`${e} × ${t}`:e).join(" · ")}(s,i)||o;return n.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:r,"aria-expanded":t,"aria-label":o?`${a}: ${o}`:a,children:n.jsxs("span",{className:"tool-group-header",children:[n.jsxs("span",{className:"tool-group-title",children:[n.jsx($,{className:"tool-group-chevron","aria-hidden":"true"}),n.jsx("strong",{children:a})]}),o?n.jsx("span",{className:"tool-group-summary",children:o}):null]})})}const bo=t.memo(function({message:e,index:t,actions:s,messageRefs:r,baseCwd:i,canRewind:o,activeMatch:a,replying:c,queued:l,sourceOpen:d,toolOpen:u,setOpenSourceKey:h,setOpenToolKey:f,copyText:p,failedSend:m,t:g}){const v=to(e,t);return n.jsxs("div",{className:`message-frame ${e.role} ${"info"===e.type?"info":""}`,"data-message-index":t,ref:e=>{r.current[t]=e},children:[n.jsx(go,{activeMatch:a,baseCwd:i,message:e,replying:c,queued:l,onCopy:p,onRewind:o?()=>s.current.onRewindMessage(e):void 0,onCloseTool:()=>f(null),onOpenRemoteFile:(e,t)=>s.current.onOpenRemoteFile(e,t),onToggleSource:()=>h(e=>e===v?null:v),onToggleTool:()=>f(e=>e===v?null:v),sourceOpen:d,toolOpen:u,t:g}),m?n.jsx(zi,{failedSend:m,onRetry:()=>{s.current.retry()},onDismiss:()=>s.current.onDismissFailedSend?.(),t:g}):null]},v)}),wo=t.memo(function({items:e,activeQueue:t,actions:s,messageRefs:r,activeMatchedMessageIndex:i,baseCwd:o,canRewind:a,hiddenLaterItemCount:c,replyingMessageIndex:l,openSourceKey:d,openToolKey:u,setOpenSourceKey:h,setOpenToolKey:f,copyText:p,failedSend:m,t:g}){return n.jsx(n.Fragment,{children:e.map(e=>{if("toolGroup"===e.type){const t=e.entries.map(e=>e.message),s=e.entries.some(e=>i===e.index),o=u===e.id;return n.jsx("div",{className:"message-frame tool info",ref:t=>{for(const n of e.entries)r.current[n.index]=t},children:n.jsxs("div",{className:"inline-message-stack",children:[n.jsx(yo,{t:g,activeMatch:s,expanded:o,messages:t,onToggle:()=>f(t=>t===e.id?null:e.id)}),o?n.jsx(fo,{messages:t,showHeader:!1,onClose:()=>f(null),onCopy:p,t:g}):null]})},e.id)}const{index:v,message:y}=e,b=to(y,v),w=d===b,x=u===b,S=m?.historyKey===y.historyKey?m:null;return n.jsx(bo,{message:y,queued:!!t?.some(e=>!!e.clientMessageId&&(y.historyKey===`client:${e.clientMessageId}`||y.localClientMessageId===e.clientMessageId)),index:v,actions:s,messageRefs:r,baseCwd:o,canRewind:a,activeMatch:i===v,replying:0===c&&v===l,sourceOpen:w,toolOpen:x,setOpenSourceKey:h,setOpenToolKey:f,copyText:p,failedSend:S,t:g},b)})})}),xo={cancelTimeout:"Cancellation is not confirmed. Vibelet still owns this session; retry to return it to the terminal.",releaseUnconfirmed:"The writer lock is not confirmed released. Retry handing back to the terminal.",handoffFailed:"Could not return the session to the terminal",resuming:"Resuming conversation",submitting:"Submitting message",waiting:"Message accepted · waiting for model",compacting:"Compacting context",responding:"Receiving reply",retrying:"Reconnecting to Codex…",noProgress:"No progress for",latestError:"Latest error: ",idle:"No active turn",error:"The turn encountered an error",releasing:"Cancelling and releasing…",released:"Session returned to the terminal",releasedHint:"To continue there, return to the original Codex terminal and press R. You can also send a message here to resume in Vibelet.",dismiss:"Got it",handoff:"Cancel and return to terminal",unavailable:"Execution status unavailable",waitHint:"No new output yet. You can cancel and return to the terminal."},So={cancelTimeout:"尚未确认取消,会话仍由 Vibelet 占用。可重试交还终端。",releaseUnconfirmed:"尚未确认写锁释放,请重试交还终端。",handoffFailed:"尚未交还终端",resuming:"正在恢复会话",submitting:"正在提交消息",waiting:"消息已接收,等待模型",compacting:"正在压缩上下文",responding:"正在接收回复",retrying:"正在重连 Codex…",noProgress:"无进展",latestError:"最近错误:",idle:"当前没有运行中的轮次",error:"本轮执行出错",releasing:"正在取消并释放会话…",released:"已交还终端",releasedHint:"如需在终端继续,请回到原来的 Codex 终端按 R。也可以在这里发送消息,继续在 Vibelet 对话。",dismiss:"知道了",handoff:"取消并交还终端",unavailable:"暂时无法取得执行状态",waitHint:"尚无新输出,可取消本轮并交还终端。"},ko={cancelTimeout:"尚未確認取消,會話仍由 Vibelet 佔用。可重試交還終端。",releaseUnconfirmed:"尚未確認寫鎖釋放,請重試交還終端。",handoffFailed:"尚未交還終端",resuming:"正在恢復會話",submitting:"正在提交訊息",waiting:"訊息已接收,等待模型",compacting:"正在壓縮上下文",responding:"正在接收回覆",retrying:"正在重新連線 Codex…",noProgress:"無進展",latestError:"最近錯誤:",idle:"目前沒有執行中的輪次",error:"本輪執行出錯",releasing:"正在取消並釋放會話…",released:"已交還終端",releasedHint:"如需在終端繼續,請回到原來的 Codex 終端按 R。也可以在這裡傳送訊息,繼續在 Vibelet 對話。",dismiss:"知道了",handoff:"取消並交還終端",unavailable:"暫時無法取得執行狀態",waitHint:"尚無新輸出,可取消本輪並交還終端。"};function Io({client:e,sessionId:s,t:r}){const i=(e=>e===b.zh?So:e===b["zh-TW"]?ko:xo)(r),[o,a]=t.useState(null),[c,l]=t.useState(""),[d,u]=t.useState(!1),[h,f]=t.useState(!1),[p,m]=t.useState(Date.now());t.useEffect(()=>{if(!e)return;let t,n=!1;const r=async()=>{try{const t=await e.request({action:"codex.session.status",id:e.makeId("execution"),sessionId:s},{timeoutMs:5e3});n||(a(t),m(Date.now()),["idle","error"].includes(t.phase)||f(!1))}catch{n||a(null)}n||(t=setTimeout(r,2e3))};r();const i=e.onMessage(e=>{"sessionId"in e&&e.sessionId===s&&["text.delta","session.queue"].includes(e.type)&&f(!1)});return()=>{n=!0,clearTimeout(t),i()}},[e,s]);const g=d?"releasing":h?"released":c?"error":o?.phase;return h||!c&&!d&&"error"!==o?.phase&&"retrying"!==o?.phase?null:n.jsxs("div",{className:"notice codex-session-control",role:"status","data-testid":"codex-session-control",style:{flexWrap:"wrap"},children:[n.jsxs("span",{style:{flex:1},children:[c?i.handoffFailed:g?i[g]:i.unavailable,o&&["compacting","waiting","submitting","retrying","responding"].includes(o.phase)&&!d&&!h&&n.jsxs("small",{style:{display:"block"},children:[i.noProgress," ",Math.max(0,Math.floor((p-(o.lastProgressAt??o.since))/1e3)),"s ·"," ",i.waitHint]}),!h&&!d&&"retrying"===o?.phase&&o.detail&&n.jsxs("small",{style:{display:"block"},children:[i.latestError,o.detail]}),c&&n.jsx("small",{role:"alert",style:{display:"block"},children:c})]}),n.jsx("button",{type:"button",className:"icon-text-button",disabled:!e?.isConnected||d,onClick:()=>{(async()=>{if(e&&!d){u(!0),f(!1),l("");try{const t=await e.request({action:"codex.session.handoff",id:e.makeId("handoff"),sessionId:s},{timeoutMs:25e3});if(!0!==t?.released)throw new Error(i.unavailable);f(!0)}catch(t){const e=t instanceof Error?t.message:String(t);l(e.includes("has not confirmed cancellation")?i.cancelTimeout:e.includes("Cannot confirm the Codex writer lock")?i.releaseUnconfirmed:e)}finally{u(!1)}}})()},children:d?i.releasing:i.handoff})]})}function Co({client:e,activeSession:t,busy:s,rewinding:r,errorText:i,failedSend:o,failedSendVisibleInConversation:a,onClearInterrupt:c,onDismissError:l,onDismissFailedSend:d,onRetry:u,onRetryFailedSend:h,t:f}){return n.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[r&&n.jsx("div",{className:"notice",role:"status","aria-busy":"true",children:$s().rewinding}),!r&&"codex"===t?.agent&&n.jsx(Io,{client:e,sessionId:t.sessionId,t:f},t.sessionId),i?n.jsx(_i,{message:i,retryLabel:e?.isConnected?f.refreshSessions:f.retry,onRetry:u,closeLabel:f.close,onDismiss:l}):null,o&&!a?n.jsx(zi,{failedSend:o,onRetry:h,onDismiss:d,t:f}):null,t?.interruptReason?n.jsxs("div",{className:"notice error",role:"alert",children:[n.jsx(Ue,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsx("strong",{children:f.replyStopped})," ",t.interruptReason.humanText||t.interruptReason.kind]}),n.jsx("button",{className:"icon-text-button",disabled:s,onClick:c,type:"button",children:f.clear})]}):null,t?.stallWarning?n.jsxs("div",{className:"notice warning",children:[n.jsx(U,{"aria-hidden":"true"}),n.jsx("span",{children:t.stallWarning.humanText||f.agentMayBeStalled}),n.jsx("button",{className:"chat-notice-dismiss",type:"button","aria-label":f.close,title:f.close,onClick:c,children:n.jsx(Be,{"aria-hidden":"true"})})]}):null]})}function jo({title:e,draft:s,label:r,disabled:i,onDraftChange:o,onCommit:a}){const[c,l]=t.useState(!1),[d,u]=t.useState(s),h=t.useRef(null),f=t.useRef(null),p=t.useRef(!1),m=t.useRef(!1);t.useLayoutEffect(()=>{c?(h.current?.focus(),h.current?.select()):p.current&&(p.current=!1,f.current?.focus()),c||(m.current=!1)},[c]);const g=()=>{p.current=!0,l(!1)};return c?n.jsx("input",{ref:h,className:"inline-session-title-input","aria-label":r,value:d,onChange:e=>{u(e.target.value),o(e.target.value)},onBlur:()=>{m.current||(d.trim()&&d.trim()!==e&&a(d),l(!1))},onKeyDown:t=>{t.nativeEvent.isComposing||229===t.keyCode||("Enter"===t.key?(t.preventDefault(),m.current=!0,d.trim()&&d.trim()!==e&&a(d),g()):"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),m.current=!0,g()))}}):n.jsx("button",{ref:f,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${r}: ${e}`,disabled:i,onClick:()=>{u(e),o(e),l(!0)},children:e})}const Ro=t.createContext(null);function Eo({matchCount:e,activeMatchIndex:t,query:s,onChange:r,onNext:i,onPrevious:o,onClose:a,t:c}){const l="浏览器"===c.browser?"上一个匹配项":"瀏覽器"===c.browser?"上一個匹配項":"Previous match",d="浏览器"===c.browser?"下一个匹配项":"瀏覽器"===c.browser?"下一個匹配項":"Next match";return n.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[n.jsx(Te,{"aria-hidden":"true"}),n.jsx("input",{autoFocus:!0,"aria-label":c.searchThisSession,value:s,onChange:e=>r(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||(["Enter","ArrowUp","ArrowDown"].includes(e.key)&&(e.preventDefault(),"ArrowUp"===e.key||"Enter"===e.key&&e.shiftKey?o():i()),"Escape"===e.key&&(e.preventDefault(),a()))},placeholder:c.searchThisSession}),n.jsx("span",{className:"message-search-position","aria-live":"polite",title:c.messageSearchMatches(e),children:s.trim()?`${t} / ${e}`:c.allMessages}),n.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":l,title:l,disabled:!e,onClick:o,children:n.jsx(F,{"aria-hidden":"true"})}),n.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":d,title:d,disabled:!e,onClick:i,children:n.jsx(D,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":c.clearMessageSearch,title:c.clearMessageSearch,className:"icon-button mini-button",onClick:a,type:"button",children:n.jsx(Be,{"aria-hidden":"true"})})]})}function Mo({activeSession:e,agent:s,cwd:i,t:a,onOpenDetails:c,onScrollToStart:l,renameTitle:d,busy:u,onRename:h,onRenameTitleChange:f,onViewChanges:p,search:m}){const[g,v]=t.useState(!1),y=t.useRef(null),b=t.useRef(!1);t.useEffect(()=>{const e=()=>{v(!0),requestAnimationFrame(()=>{const e=document.querySelector("#conversation-message-search input");e?.focus(),e?.select()})};return window.addEventListener("vibelet.message-search",e),()=>window.removeEventListener("vibelet.message-search",e)},[]),t.useEffect(()=>{m.query&&v(!0)},[m.query]),t.useLayoutEffect(()=>{!g&&b.current&&(b.current=!1,y.current?.focus())},[g]);const w=e?o(e):a.newSession,x=e?.cwd??(i.trim().length>0&&"."!==i?i:""),S=e?.agent??s,I=t.useContext(Ro),C=r().toolbarTarget?.("conversation")??I,j=n.jsxs("div",{className:"chat-header-title-row",onClick:e=>{e.target instanceof Element&&e.target.closest('button,a,input,textarea,[contenteditable="true"],.message-search-bar')||l()},children:[n.jsxs("div",{className:"chat-title-block",children:[n.jsxs("span",{className:"chat-title-line",children:[n.jsx("button",{className:`agent-status-pill chat-session-details-button ${S}`,type:"button",onClick:c,"aria-label":a.details,title:a.details,disabled:!e,children:"codex"===S?"Codex":"Claude"}),n.jsx("h1",{children:e?n.jsx(jo,{title:w,draft:d,label:a.rename,disabled:u,onDraftChange:f,onCommit:h},e.sessionId):w})]}),x?n.jsx("p",{title:x,children:x}):null,e?.branch||e?.diffStat?n.jsxs("div",{className:"header-metadata",children:[e.branch?n.jsx("span",{children:e.branch}):null,e.runtime.state?n.jsx("span",{children:a.runtimeState(e.runtime.state)}):null,e.terminal?.mode?n.jsx("span",{children:e.terminal.mode}):null]}):null]}),n.jsx("button",{"aria-label":a.scrollToConversationStart,className:"chat-scroll-start-target",onClick:l,title:a.scrollToConversationStart,type:"button"}),e&&!g?n.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":a.viewChanges,title:a.viewChanges,onClick:()=>p(e.sessionId),children:[n.jsx(oe,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?n.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[n.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),n.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,g?n.jsx(Eo,{...m,t:a,onClose:()=>{b.current=!0,m.onChange(""),v(!1)}}):n.jsx("button",{ref:y,className:"icon-button chat-search-toggle",type:"button","aria-label":a.searchThisSession,title:wr(a.searchThisSession,"searchMessages"),"aria-expanded":!1,"aria-controls":"conversation-message-search",onClick:()=>v(!0),children:n.jsx(Te,{"aria-hidden":"true"})})]});return n.jsx("header",{className:"chat-header chat-search-header "+(C?"chat-header-in-titlebar":""),children:C?k.createPortal(j,C):j})}const To={};function Ao(e,t){return No(e,"boolean"!=typeof To.includeImageAlt||To.includeImageAlt,"boolean"!=typeof To.includeHtml||To.includeHtml)}function No(e,t,n){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||n?e.value:"";if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Do(e.children,t,n)}return Array.isArray(e)?Do(e,t,n):""}function Do(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=No(e[r],t,n);return s.join("")}const Po=document.createElement("i");function Lo(e){const t="&"+e+";";Po.innerHTML=t;const n=Po.textContent;return(59!==n.charCodeAt(n.length-1)||"semi"===e)&&n!==t&&n}function Fo(e,t,n,s){const r=e.length;let i,o=0;if(t=t<0?-t>r?0:r+t:t>r?r:t,n=n>0?n:0,s.length<1e4)i=Array.from(s),i.unshift(t,n),e.splice(...i);else for(n&&e.splice(t,n);o<s.length;)i=s.slice(o,o+1e4),i.unshift(t,0),e.splice(...i),o+=1e4,t+=1e4}function qo(e,t){return e.length>0?(Fo(e,e.length,0,t),e):t}const Oo={}.hasOwnProperty;function _o(e){const t={};let n=-1;for(;++n<e.length;)$o(t,e[n]);return t}function $o(e,t){let n;for(n in t){const s=(Oo.call(e,n)?e[n]:void 0)||(e[n]={}),r=t[n];let i;if(r)for(i in r){Oo.call(s,i)||(s[i]=[]);const e=r[i];zo(s[i],Array.isArray(e)?e:e?[e]:[])}}}function zo(e,t){let n=-1;const s=[];for(;++n<t.length;)("after"===t[n].add?e:s).push(t[n]);Fo(e,0,0,s)}function Ho(e,t){const n=Number.parseInt(e,t);return n<9||11===n||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||!(65535&~n)||65534==(65535&n)||n>1114111?"�":String.fromCodePoint(n)}function Bo(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Uo=na(/[A-Za-z]/),Wo=na(/[\dA-Za-z]/),Ko=na(/[#-'*+\--9=?A-Z^-~]/);function Vo(e){return null!==e&&(e<32||127===e)}const Qo=na(/\d/),Go=na(/[\dA-Fa-f]/),Jo=na(/[!-/:-@[-`{-~]/);function Zo(e){return null!==e&&e<-2}function Xo(e){return null!==e&&(e<0||32===e)}function Yo(e){return-2===e||-1===e||32===e}const ea=na(new RegExp("\\p{P}|\\p{S}","u")),ta=na(/\s/);function na(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function sa(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return function(s){return Yo(s)?(e.enter(n),o(s)):t(s)};function o(s){return Yo(s)&&i++<r?(e.consume(s),o):(e.exit(n),t(s))}}const ra={tokenize:function(e){const t=e.attempt(this.parser.constructs.contentInitial,function(n){if(null!==n)return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),sa(e,t,"linePrefix");e.consume(n)},function(t){return e.enter("paragraph"),s(t)});let n;return t;function s(t){const s=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=s),n=s,r(t)}function r(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):Zo(t)?(e.consume(t),e.exit("chunkText"),s):(e.consume(t),r)}}},ia={tokenize:function(e){const t=this,n=[];let s,r,i,o=0;return a;function a(s){if(o<n.length){const r=n[o];return t.containerState=r[1],e.attempt(r[0].continuation,c,l)(s)}return l(s)}function c(e){if(o++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&y();const n=t.events.length;let r,i=n;for(;i--;)if("exit"===t.events[i][0]&&"chunkFlow"===t.events[i][1].type){r=t.events[i][1].end;break}v(o);let a=n;for(;a<t.events.length;)t.events[a][1].end={...r},a++;return Fo(t.events,i+1,0,t.events.slice(n)),t.events.length=a,l(e)}return a(e)}function l(r){if(o===n.length){if(!s)return h(r);if(s.currentConstruct&&s.currentConstruct.concrete)return p(r);t.interrupt=Boolean(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(oa,d,u)(r)}function d(e){return s&&y(),v(o),h(e)}function u(e){return t.parser.lazy[t.now().line]=o!==n.length,i=t.now().offset,p(e)}function h(n){return t.containerState={},e.attempt(oa,f,p)(n)}function f(e){return o++,n.push([t.currentConstruct,t.containerState]),h(e)}function p(n){return null===n?(s&&y(),v(0),void e.consume(n)):(s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:r}),m(n))}function m(n){return null===n?(g(e.exit("chunkFlow"),!0),v(0),void e.consume(n)):Zo(n)?(e.consume(n),g(e.exit("chunkFlow")),o=0,t.interrupt=void 0,a):(e.consume(n),m)}function g(e,n){const a=t.sliceStream(e);if(n&&a.push(null),e.previous=r,r&&(r.next=e),r=e,s.defineSkip(e.start),s.write(a),t.parser.lazy[e.start.line]){let e=s.events.length;for(;e--;)if(s.events[e][1].start.offset<i&&(!s.events[e][1].end||s.events[e][1].end.offset>i))return;const n=t.events.length;let r,a,c=n;for(;c--;)if("exit"===t.events[c][0]&&"chunkFlow"===t.events[c][1].type){if(r){a=t.events[c][1].end;break}r=!0}for(v(o),e=n;e<t.events.length;)t.events[e][1].end={...a},e++;Fo(t.events,c+1,0,t.events.slice(n)),t.events.length=e}}function v(s){let r=n.length;for(;r-- >s;){const s=n[r];t.containerState=s[1],s[0].exit.call(t,e)}n.length=s}function y(){s.write([null]),r=void 0,s=void 0,t.containerState._closeFlow=void 0}}},oa={tokenize:function(e,t,n){return sa(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function aa(e){return null===e||Xo(e)||ta(e)?1:ea(e)?2:void 0}function ca(e,t,n){const s=[];let r=-1;for(;++r<e.length;){const i=e[r].resolveAll;i&&!s.includes(i)&&(t=i(t,n),s.push(i))}return t}const la={name:"attention",resolveAll:function(e,t){let n,s,r,i,o,a,c,l,d=-1;for(;++d<e.length;)if("enter"===e[d][0]&&"attentionSequence"===e[d][1].type&&e[d][1]._close)for(n=d;n--;)if("exit"===e[n][0]&&"attentionSequence"===e[n][1].type&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[d][1]).charCodeAt(0)){if((e[n][1]._close||e[d][1]._open)&&(e[d][1].end.offset-e[d][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[d][1].end.offset-e[d][1].start.offset)%3))continue;a=e[n][1].end.offset-e[n][1].start.offset>1&&e[d][1].end.offset-e[d][1].start.offset>1?2:1;const u={...e[n][1].end},h={...e[d][1].start};da(u,-a),da(h,a),i={type:a>1?"strongSequence":"emphasisSequence",start:u,end:{...e[n][1].end}},o={type:a>1?"strongSequence":"emphasisSequence",start:{...e[d][1].start},end:h},r={type:a>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[d][1].start}},s={type:a>1?"strong":"emphasis",start:{...i.start},end:{...o.end}},e[n][1].end={...i.start},e[d][1].start={...o.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=qo(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=qo(c,[["enter",s,t],["enter",i,t],["exit",i,t],["enter",r,t]]),c=qo(c,ca(t.parser.constructs.insideSpan.null,e.slice(n+1,d),t)),c=qo(c,[["exit",r,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[d][1].end.offset-e[d][1].start.offset?(l=2,c=qo(c,[["enter",e[d][1],t],["exit",e[d][1],t]])):l=0,Fo(e,n-1,d-n+3,c),d=n+c.length-l-2;break}for(d=-1;++d<e.length;)"attentionSequence"===e[d][1].type&&(e[d][1].type="data");return e},tokenize:function(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,r=aa(s);let i;return function(t){return i=t,e.enter("attentionSequence"),o(t)};function o(a){if(a===i)return e.consume(a),o;const c=e.exit("attentionSequence"),l=aa(a),d=!l||2===l&&r||n.includes(a),u=!r||2===r&&l||n.includes(s);return c._open=Boolean(42===i?d:d&&(r||!u)),c._close=Boolean(42===i?u:u&&(l||!d)),t(a)}}};function da(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const ua={name:"autolink",tokenize:function(e,t,n){let s=0;return function(t){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),r};function r(t){return Uo(t)?(e.consume(t),i):64===t?n(t):c(t)}function i(e){return 43===e||45===e||46===e||Wo(e)?(s=1,o(e)):c(e)}function o(t){return 58===t?(e.consume(t),s=0,a):(43===t||45===t||46===t||Wo(t))&&s++<32?(e.consume(t),o):(s=0,c(t))}function a(s){return 62===s?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(s),e.exit("autolinkMarker"),e.exit("autolink"),t):null===s||32===s||60===s||Vo(s)?n(s):(e.consume(s),a)}function c(t){return 64===t?(e.consume(t),l):Ko(t)?(e.consume(t),c):n(t)}function l(e){return Wo(e)?d(e):n(e)}function d(n){return 46===n?(e.consume(n),s=0,l):62===n?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(n),e.exit("autolinkMarker"),e.exit("autolink"),t):u(n)}function u(t){if((45===t||Wo(t))&&s++<63){const n=45===t?u:d;return e.consume(t),n}return n(t)}}},ha={partial:!0,tokenize:function(e,t,n){return function(t){return Yo(t)?sa(e,s,"linePrefix")(t):s(t)};function s(e){return null===e||Zo(e)?t(e):n(e)}}},fa={continuation:{tokenize:function(e,t,n){const s=this;return function(t){return Yo(t)?sa(e,r,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):r(t)};function r(s){return e.attempt(fa,t,n)(s)}}},exit:function(e){e.exit("blockQuote")},name:"blockQuote",tokenize:function(e,t,n){const s=this;return function(t){if(62===t){const n=s.containerState;return n.open||(e.enter("blockQuote",{_container:!0}),n.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(t),e.exit("blockQuoteMarker"),r}return n(t)};function r(n){return Yo(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}}},pa={name:"characterEscape",tokenize:function(e,t,n){return function(t){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(t),e.exit("escapeMarker"),s};function s(s){return Jo(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}},ma={name:"characterReference",tokenize:function(e,t,n){const s=this;let r,i,o=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),a};function a(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),c):(e.enter("characterReferenceValue"),r=31,i=Wo,l(t))}function c(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),r=6,i=Go,l):(e.enter("characterReferenceValue"),r=7,i=Qo,l(t))}function l(a){if(59===a&&o){const r=e.exit("characterReferenceValue");return i!==Wo||Lo(s.sliceSerialize(r))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)}return i(a)&&o++<r?(e.consume(a),l):n(a)}}},ga={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return null===t?n(t):(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r)};function r(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},va={concrete:!0,name:"codeFenced",tokenize:function(e,t,n){const s=this,r={partial:!0,tokenize:function(e,t,n){let r=0;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o};function o(t){return e.enter("codeFencedFence"),Yo(t)?sa(e,c,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===i?(e.enter("codeFencedFenceSequence"),l(t)):n(t)}function l(t){return t===i?(r++,e.consume(t),l):r>=a?(e.exit("codeFencedFenceSequence"),Yo(t)?sa(e,d,"whitespace")(t):d(t)):n(t)}function d(s){return null===s||Zo(s)?(e.exit("codeFencedFence"),t(s)):n(s)}}};let i,o=0,a=0;return function(t){return function(t){const n=s.events[s.events.length-1];return o=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,i=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===i?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),Yo(t)?sa(e,l,"whitespace")(t):l(t))}function l(n){return null===n||Zo(n)?(e.exit("codeFencedFence"),s.interrupt?t(n):e.check(ga,f,y)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),d(n))}function d(t){return null===t||Zo(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(t)):Yo(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),sa(e,u,"whitespace")(t)):96===t&&t===i?n(t):(e.consume(t),d)}function u(t){return null===t||Zo(t)?l(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),h(t))}function h(t){return null===t||Zo(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(t)):96===t&&t===i?n(t):(e.consume(t),h)}function f(t){return e.attempt(r,y,p)(t)}function p(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),m}function m(t){return o>0&&Yo(t)?sa(e,g,"linePrefix",o+1)(t):g(t)}function g(t){return null===t||Zo(t)?e.check(ga,f,y)(t):(e.enter("codeFlowValue"),v(t))}function v(t){return null===t||Zo(t)?(e.exit("codeFlowValue"),g(t)):(e.consume(t),v)}function y(n){return e.exit("codeFenced"),t(n)}}},ya={name:"codeIndented",tokenize:function(e,t,n){const s=this;return function(t){return e.enter("codeIndented"),sa(e,r,"linePrefix",5)(t)};function r(e){const t=s.events[s.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?i(e):n(e)}function i(t){return null===t?a(t):Zo(t)?e.attempt(ba,i,a)(t):(e.enter("codeFlowValue"),o(t))}function o(t){return null===t||Zo(t)?(e.exit("codeFlowValue"),i(t)):(e.consume(t),o)}function a(n){return e.exit("codeIndented"),t(n)}}},ba={partial:!0,tokenize:function(e,t,n){const s=this;return r;function r(t){return s.parser.lazy[s.now().line]?n(t):Zo(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r):sa(e,i,"linePrefix",5)(t)}function i(e){const i=s.events[s.events.length-1];return i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(e):Zo(e)?r(e):n(e)}}},wa={name:"codeText",previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type},resolve:function(e){let t,n,s=e.length-4,r=3;if(!("lineEnding"!==e[r][1].type&&"space"!==e[r][1].type||"lineEnding"!==e[s][1].type&&"space"!==e[s][1].type))for(t=r;++t<s;)if("codeTextData"===e[t][1].type){e[r][1].type="codeTextPadding",e[s][1].type="codeTextPadding",r+=2,s-=2;break}for(t=r-1,s++;++t<=s;)void 0===n?t!==s&&"lineEnding"!==e[t][1].type&&(n=t):t!==s&&"lineEnding"!==e[t][1].type||(e[n][1].type="codeTextData",t!==n+2&&(e[n][1].end=e[t-1][1].end,e.splice(n+2,t-n-2),s-=t-n-2,t=n+2),n=void 0);return e},tokenize:function(e,t,n){let s,r,i=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),o(t)};function o(t){return 96===t?(e.consume(t),i++,o):(e.exit("codeTextSequence"),a(t))}function a(t){return null===t?n(t):32===t?(e.enter("space"),e.consume(t),e.exit("space"),a):96===t?(r=e.enter("codeTextSequence"),s=0,l(t)):Zo(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a):(e.enter("codeTextData"),c(t))}function c(t){return null===t||32===t||96===t||Zo(t)?(e.exit("codeTextData"),a(t)):(e.consume(t),c)}function l(n){return 96===n?(e.consume(n),s++,l):s===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(r.type="codeTextData",c(n))}}};class xa{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){const n=t??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const s=t||0;this.setCursor(Math.trunc(e));const r=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&Sa(this.left,n),r.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),Sa(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Sa(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&0===this.right.length||e<0&&0===this.left.length))if(e<this.left.length){const t=this.left.splice(e,Number.POSITIVE_INFINITY);Sa(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);Sa(this.left,t.reverse())}}}function Sa(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function ka(e){const t={};let n,s,r,i,o,a,c,l=-1;const d=new xa(e);for(;++l<d.length;){for(;l in t;)l=t[l];if(n=d.get(l),l&&"chunkFlow"===n[1].type&&"listItemPrefix"===d.get(l-1)[1].type&&(a=n[1]._tokenizer.events,r=0,r<a.length&&"lineEndingBlank"===a[r][1].type&&(r+=2),r<a.length&&"content"===a[r][1].type))for(;++r<a.length&&"content"!==a[r][1].type;)"chunkText"===a[r][1].type&&(a[r][1]._isInFirstContentOfListItem=!0,r++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,Ia(d,l)),l=t[l],c=!0);else if(n[1]._container){for(r=l,s=void 0;r--;)if(i=d.get(r),"lineEnding"===i[1].type||"lineEndingBlank"===i[1].type)"enter"===i[0]&&(s&&(d.get(s)[1].type="lineEndingBlank"),i[1].type="lineEnding",s=r);else if("linePrefix"!==i[1].type&&"listItemIndent"!==i[1].type)break;s&&(n[1].end={...d.get(s)[1].start},o=d.slice(s,l),o.unshift(n),d.splice(s,l-s+1,o))}}return Fo(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!c}function Ia(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];let o=n._tokenizer;o||(o=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,c=[],l={};let d,u,h=-1,f=n,p=0,m=0;const g=[m];for(;f;){for(;e.get(++r)[1]!==f;);i.push(r),f._tokenizer||(d=s.sliceStream(f),f.next||d.push(null),u&&o.defineSkip(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),u=f,f=f.next}for(f=n;++h<a.length;)"exit"===a[h][0]&&"enter"===a[h-1][0]&&a[h][1].type===a[h-1][1].type&&a[h][1].start.line!==a[h][1].end.line&&(m=h+1,g.push(m),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):g.pop(),h=g.length;h--;){const t=a.slice(g[h],g[h+1]),n=i.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),h=-1;++h<c.length;)l[p+c[h][0]]=p+c[h][1],p+=c[h][1]-c[h][0]-1;return l}const Ca={resolve:function(e){return ka(e),e},tokenize:function(e,t){let n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(t)};function s(t){return null===t?r(t):Zo(t)?e.check(ja,i,r)(t):(e.consume(t),s)}function r(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function i(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}},ja={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),sa(e,r,"linePrefix")};function r(r){if(null===r||Zo(r))return n(r);const i=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(r):e.interrupt(s.parser.constructs.flow,n,t)(r)}}};function Ra(e,t,n,s,r,i,o,a,c){const l=c||Number.POSITIVE_INFINITY;let d=0;return function(t){return 60===t?(e.enter(s),e.enter(r),e.enter(i),e.consume(t),e.exit(i),u):null===t||32===t||41===t||Vo(t)?n(t):(e.enter(s),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),p(t))};function u(n){return 62===n?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),e.exit(s),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),h(n))}function h(t){return 62===t?(e.exit("chunkString"),e.exit(a),u(t)):null===t||60===t||Zo(t)?n(t):(e.consume(t),92===t?f:h)}function f(t){return 60===t||62===t||92===t?(e.consume(t),h):h(t)}function p(r){return d||null!==r&&41!==r&&!Xo(r)?d<l&&40===r?(e.consume(r),d++,p):41===r?(e.consume(r),d--,p):null===r||32===r||40===r||Vo(r)?n(r):(e.consume(r),92===r?m:p):(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(s),t(r))}function m(t){return 40===t||41===t||92===t?(e.consume(t),p):p(t)}}function Ea(e,t,n,s,r,i){const o=this;let a,c=0;return function(t){return e.enter(s),e.enter(r),e.consume(t),e.exit(r),e.enter(i),l};function l(u){return c>999||null===u||91===u||93===u&&!a||94===u&&!c&&"_hiddenFootnoteSupport"in o.parser.constructs?n(u):93===u?(e.exit(i),e.enter(r),e.consume(u),e.exit(r),e.exit(s),t):Zo(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l):(e.enter("chunkString",{contentType:"string"}),d(u))}function d(t){return null===t||91===t||93===t||Zo(t)||c++>999?(e.exit("chunkString"),l(t)):(e.consume(t),a||(a=!Yo(t)),92===t?u:d)}function u(t){return 91===t||92===t||93===t?(e.consume(t),c++,d):d(t)}}function Ma(e,t,n,s,r,i){let o;return function(t){return 34===t||39===t||40===t?(e.enter(s),e.enter(r),e.consume(t),e.exit(r),o=40===t?41:t,a):n(t)};function a(n){return n===o?(e.enter(r),e.consume(n),e.exit(r),e.exit(s),t):(e.enter(i),c(n))}function c(t){return t===o?(e.exit(i),a(o)):null===t?n(t):Zo(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),sa(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),l(t))}function l(t){return t===o||null===t||Zo(t)?(e.exit("chunkString"),c(t)):(e.consume(t),92===t?d:l)}function d(t){return t===o||92===t?(e.consume(t),l):l(t)}}function Ta(e,t){let n;return function s(r){return Zo(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):Yo(r)?sa(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const Aa={name:"definition",tokenize:function(e,t,n){const s=this;let r;return function(t){return e.enter("definition"),function(t){return Ea.call(s,e,i,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function i(t){return r=Bo(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),o):n(t)}function o(t){return Xo(t)?Ta(e,a)(t):a(t)}function a(t){return Ra(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(Na,l,l)(t)}function l(t){return Yo(t)?sa(e,d,"whitespace")(t):d(t)}function d(i){return null===i||Zo(i)?(e.exit("definition"),s.parser.defined.push(r),t(i)):n(i)}}},Na={partial:!0,tokenize:function(e,t,n){return function(t){return Xo(t)?Ta(e,s)(t):n(t)};function s(t){return Ma(e,r,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function r(t){return Yo(t)?sa(e,i,"whitespace")(t):i(t)}function i(e){return null===e||Zo(e)?t(e):n(e)}}},Da={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),s};function s(s){return Zo(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}},Pa={name:"headingAtx",resolve:function(e,t){let n,s,r=e.length-2,i=3;return"whitespace"===e[i][1].type&&(i+=2),r-2>i&&"whitespace"===e[r][1].type&&(r-=2),"atxHeadingSequence"===e[r][1].type&&(i===r-1||r-4>i&&"whitespace"===e[r-2][1].type)&&(r-=i+1===r?2:4),r>i&&(n={type:"atxHeadingText",start:e[i][1].start,end:e[r][1].end},s={type:"chunkText",start:e[i][1].start,end:e[r][1].end,contentType:"text"},Fo(e,i,r-i+1,[["enter",n,t],["enter",s,t],["exit",s,t],["exit",n,t]])),e},tokenize:function(e,t,n){let s=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),r(t)}(t)};function r(t){return 35===t&&s++<6?(e.consume(t),r):null===t||Xo(t)?(e.exit("atxHeadingSequence"),i(t)):n(t)}function i(n){return 35===n?(e.enter("atxHeadingSequence"),o(n)):null===n||Zo(n)?(e.exit("atxHeading"),t(n)):Yo(n)?sa(e,i,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function o(t){return 35===t?(e.consume(t),o):(e.exit("atxHeadingSequence"),i(t))}function a(t){return null===t||35===t||Xo(t)?(e.exit("atxHeadingText"),i(t)):(e.consume(t),a)}}},La=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Fa=["pre","script","style","textarea"],qa={concrete:!0,name:"htmlFlow",resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););return t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e},tokenize:function(e,t,n){const s=this;let r,i,o,a,c;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),l}(t)};function l(a){return 33===a?(e.consume(a),d):47===a?(e.consume(a),i=!0,f):63===a?(e.consume(a),r=3,s.interrupt?t:P):Uo(a)?(e.consume(a),o=String.fromCharCode(a),p):n(a)}function d(i){return 45===i?(e.consume(i),r=2,u):91===i?(e.consume(i),r=5,a=0,h):Uo(i)?(e.consume(i),r=4,s.interrupt?t:P):n(i)}function u(r){return 45===r?(e.consume(r),s.interrupt?t:P):n(r)}function h(r){return r==="CDATA[".charCodeAt(a++)?(e.consume(r),6===a?s.interrupt?t:j:h):n(r)}function f(t){return Uo(t)?(e.consume(t),o=String.fromCharCode(t),p):n(t)}function p(a){if(null===a||47===a||62===a||Xo(a)){const c=47===a,l=o.toLowerCase();return c||i||!Fa.includes(l)?La.includes(o.toLowerCase())?(r=6,c?(e.consume(a),m):s.interrupt?t(a):j(a)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(a):i?g(a):v(a)):(r=1,s.interrupt?t(a):j(a))}return 45===a||Wo(a)?(e.consume(a),o+=String.fromCharCode(a),p):n(a)}function m(r){return 62===r?(e.consume(r),s.interrupt?t:j):n(r)}function g(t){return Yo(t)?(e.consume(t),g):I(t)}function v(t){return 47===t?(e.consume(t),I):58===t||95===t||Uo(t)?(e.consume(t),y):Yo(t)?(e.consume(t),v):I(t)}function y(t){return 45===t||46===t||58===t||95===t||Wo(t)?(e.consume(t),y):b(t)}function b(t){return 61===t?(e.consume(t),w):Yo(t)?(e.consume(t),b):v(t)}function w(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,x):Yo(t)?(e.consume(t),w):S(t)}function x(t){return t===c?(e.consume(t),c=null,k):null===t||Zo(t)?n(t):(e.consume(t),x)}function S(t){return null===t||34===t||39===t||47===t||60===t||61===t||62===t||96===t||Xo(t)?b(t):(e.consume(t),S)}function k(e){return 47===e||62===e||Yo(e)?v(e):n(e)}function I(t){return 62===t?(e.consume(t),C):n(t)}function C(t){return null===t||Zo(t)?j(t):Yo(t)?(e.consume(t),C):n(t)}function j(t){return 45===t&&2===r?(e.consume(t),T):60===t&&1===r?(e.consume(t),A):62===t&&4===r?(e.consume(t),L):63===t&&3===r?(e.consume(t),P):93===t&&5===r?(e.consume(t),D):!Zo(t)||6!==r&&7!==r?null===t||Zo(t)?(e.exit("htmlFlowData"),R(t)):(e.consume(t),j):(e.exit("htmlFlowData"),e.check(Oa,F,R)(t))}function R(t){return e.check(_a,E,F)(t)}function E(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),M}function M(t){return null===t||Zo(t)?R(t):(e.enter("htmlFlowData"),j(t))}function T(t){return 45===t?(e.consume(t),P):j(t)}function A(t){return 47===t?(e.consume(t),o="",N):j(t)}function N(t){if(62===t){const n=o.toLowerCase();return Fa.includes(n)?(e.consume(t),L):j(t)}return Uo(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),N):j(t)}function D(t){return 93===t?(e.consume(t),P):j(t)}function P(t){return 62===t?(e.consume(t),L):45===t&&2===r?(e.consume(t),P):j(t)}function L(t){return null===t||Zo(t)?(e.exit("htmlFlowData"),F(t)):(e.consume(t),L)}function F(n){return e.exit("htmlFlow"),t(n)}}},Oa={partial:!0,tokenize:function(e,t,n){return function(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(ha,t,n)}}},_a={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return Zo(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r):n(t)};function r(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},$a={name:"htmlText",tokenize:function(e,t,n){const s=this;let r,i,o;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),a};function a(t){return 33===t?(e.consume(t),c):47===t?(e.consume(t),w):63===t?(e.consume(t),y):Uo(t)?(e.consume(t),k):n(t)}function c(t){return 45===t?(e.consume(t),l):91===t?(e.consume(t),i=0,f):Uo(t)?(e.consume(t),v):n(t)}function l(t){return 45===t?(e.consume(t),h):n(t)}function d(t){return null===t?n(t):45===t?(e.consume(t),u):Zo(t)?(o=d,N(t)):(e.consume(t),d)}function u(t){return 45===t?(e.consume(t),h):d(t)}function h(e){return 62===e?A(e):45===e?u(e):d(e)}function f(t){return t==="CDATA[".charCodeAt(i++)?(e.consume(t),6===i?p:f):n(t)}function p(t){return null===t?n(t):93===t?(e.consume(t),m):Zo(t)?(o=p,N(t)):(e.consume(t),p)}function m(t){return 93===t?(e.consume(t),g):p(t)}function g(t){return 62===t?A(t):93===t?(e.consume(t),g):p(t)}function v(t){return null===t||62===t?A(t):Zo(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return null===t?n(t):63===t?(e.consume(t),b):Zo(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return 62===e?A(e):y(e)}function w(t){return Uo(t)?(e.consume(t),x):n(t)}function x(t){return 45===t||Wo(t)?(e.consume(t),x):S(t)}function S(t){return Zo(t)?(o=S,N(t)):Yo(t)?(e.consume(t),S):A(t)}function k(t){return 45===t||Wo(t)?(e.consume(t),k):47===t||62===t||Xo(t)?I(t):n(t)}function I(t){return 47===t?(e.consume(t),A):58===t||95===t||Uo(t)?(e.consume(t),C):Zo(t)?(o=I,N(t)):Yo(t)?(e.consume(t),I):A(t)}function C(t){return 45===t||46===t||58===t||95===t||Wo(t)?(e.consume(t),C):j(t)}function j(t){return 61===t?(e.consume(t),R):Zo(t)?(o=j,N(t)):Yo(t)?(e.consume(t),j):I(t)}function R(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),r=t,E):Zo(t)?(o=R,N(t)):Yo(t)?(e.consume(t),R):(e.consume(t),M)}function E(t){return t===r?(e.consume(t),r=void 0,T):null===t?n(t):Zo(t)?(o=E,N(t)):(e.consume(t),E)}function M(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||Xo(t)?I(t):(e.consume(t),M)}function T(e){return 47===e||62===e||Xo(e)?I(e):n(e)}function A(s){return 62===s?(e.consume(s),e.exit("htmlTextData"),e.exit("htmlText"),t):n(s)}function N(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),D}function D(t){return Yo(t)?sa(e,P,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):P(t)}function P(t){return e.enter("htmlTextData"),o(t)}}},za={name:"labelEnd",resolveAll:function(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),"labelImage"===s.type||"labelLink"===s.type||"labelEnd"===s.type){const e="labelImage"===s.type?4:2;s.type="data",t+=e}}return e.length!==n.length&&Fo(e,0,e.length,n),e},resolveTo:function(e,t){let n,s,r,i,o=e.length,a=0;for(;o--;)if(n=e[o][1],s){if("link"===n.type||"labelLink"===n.type&&n._inactive)break;"enter"===e[o][0]&&"labelLink"===n.type&&(n._inactive=!0)}else if(r){if("enter"===e[o][0]&&("labelImage"===n.type||"labelLink"===n.type)&&!n._balanced&&(s=o,"labelLink"!==n.type)){a=2;break}}else"labelEnd"===n.type&&(r=o);const c={type:"labelLink"===e[s][1].type?"link":"image",start:{...e[s][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[s][1].start},end:{...e[r][1].end}},d={type:"labelText",start:{...e[s+a+2][1].end},end:{...e[r-2][1].start}};return i=[["enter",c,t],["enter",l,t]],i=qo(i,e.slice(s+1,s+a+3)),i=qo(i,[["enter",d,t]]),i=qo(i,ca(t.parser.constructs.insideSpan.null,e.slice(s+a+4,r-3),t)),i=qo(i,[["exit",d,t],e[r-2],e[r-1],["exit",l,t]]),i=qo(i,e.slice(r+1)),i=qo(i,[["exit",c,t]]),Fo(e,s,e.length,i),e},tokenize:function(e,t,n){const s=this;let r,i,o=s.events.length;for(;o--;)if(("labelImage"===s.events[o][1].type||"labelLink"===s.events[o][1].type)&&!s.events[o][1]._balanced){r=s.events[o][1];break}return function(t){return r?r._inactive?d(t):(i=s.parser.defined.includes(Bo(s.sliceSerialize({start:r.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelEnd"),a):n(t)};function a(t){return 40===t?e.attempt(Ha,l,i?l:d)(t):91===t?e.attempt(Ba,l,i?c:d)(t):i?l(t):d(t)}function c(t){return e.attempt(Ua,l,d)(t)}function l(e){return t(e)}function d(e){return r._balanced=!0,n(e)}}},Ha={tokenize:function(e,t,n){return function(t){return e.enter("resource"),e.enter("resourceMarker"),e.consume(t),e.exit("resourceMarker"),s};function s(t){return Xo(t)?Ta(e,r)(t):r(t)}function r(t){return 41===t?l(t):Ra(e,i,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function i(t){return Xo(t)?Ta(e,a)(t):l(t)}function o(e){return n(e)}function a(t){return 34===t||39===t||40===t?Ma(e,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):l(t)}function c(t){return Xo(t)?Ta(e,l)(t):l(t)}function l(s){return 41===s?(e.enter("resourceMarker"),e.consume(s),e.exit("resourceMarker"),e.exit("resource"),t):n(s)}}},Ba={tokenize:function(e,t,n){const s=this;return function(t){return Ea.call(s,e,r,i,"reference","referenceMarker","referenceString")(t)};function r(e){return s.parser.defined.includes(Bo(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function i(e){return n(e)}}},Ua={tokenize:function(e,t,n){return function(t){return e.enter("reference"),e.enter("referenceMarker"),e.consume(t),e.exit("referenceMarker"),s};function s(s){return 93===s?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):n(s)}}},Wa={name:"labelStartImage",resolveAll:za.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),r};function r(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),i):n(t)}function i(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},Ka={name:"labelStartLink",resolveAll:za.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),r};function r(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},Va={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),sa(e,t,"linePrefix")}}},Qa={name:"thematicBreak",tokenize:function(e,t,n){let s,r=0;return function(t){return e.enter("thematicBreak"),function(e){return s=e,i(e)}(t)};function i(i){return i===s?(e.enter("thematicBreakSequence"),o(i)):r>=3&&(null===i||Zo(i))?(e.exit("thematicBreak"),t(i)):n(i)}function o(t){return t===s?(e.consume(t),r++,o):(e.exit("thematicBreakSequence"),Yo(t)?sa(e,i,"whitespace")(t):i(t))}}},Ga={continuation:{tokenize:function(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(ha,function(n){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,sa(e,t,"listItemIndent",s.containerState.size+1)(n)},function(n){return s.containerState.furtherBlankLines||!Yo(n)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,r(n)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Za,t,r)(n))});function r(r){return s.containerState._closeFlow=!0,s.interrupt=void 0,sa(e,e.attempt(Ga,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(r)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const s=this,r=s.events[s.events.length-1];let i=r&&"linePrefix"===r[1].type?r[2].sliceSerialize(r[1],!0).length:0,o=0;return function(t){const r=s.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===r?!s.containerState.marker||t===s.containerState.marker:Qo(t)){if(s.containerState.type||(s.containerState.type=r,e.enter(r,{_container:!0})),"listUnordered"===r)return e.enter("listItemPrefix"),42===t||45===t?e.check(Qa,n,c)(t):c(t);if(!s.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(t)}return n(t)};function a(t){return Qo(t)&&++o<10?(e.consume(t),a):(!s.interrupt||o<2)&&(s.containerState.marker?t===s.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),c(t)):n(t)}function c(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||t,e.check(ha,s.interrupt?n:l,e.attempt(Ja,u,d))}function l(e){return s.containerState.initialBlankLine=!0,i++,u(e)}function d(t){return Yo(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),u):n(t)}function u(n){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},Ja={partial:!0,tokenize:function(e,t,n){const s=this;return sa(e,function(e){const r=s.events[s.events.length-1];return!Yo(e)&&r&&"listItemPrefixWhitespace"===r[1].type?t(e):n(e)},"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},Za={partial:!0,tokenize:function(e,t,n){const s=this;return sa(e,function(e){const r=s.events[s.events.length-1];return r&&"listItemIndent"===r[1].type&&r[2].sliceSerialize(r[1],!0).length===s.containerState.size?t(e):n(e)},"listItemIndent",s.containerState.size+1)}},Xa={name:"setextUnderline",resolveTo:function(e,t){let n,s,r,i=e.length;for(;i--;)if("enter"===e[i][0]){if("content"===e[i][1].type){n=i;break}"paragraph"===e[i][1].type&&(s=i)}else"content"===e[i][1].type&&e.splice(i,1),r||"definition"!==e[i][1].type||(r=i);const o={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",r?(e.splice(s,0,["enter",o,t]),e.splice(r+1,0,["exit",e[n][1],t]),e[n][1].end={...e[r][1].end}):e[n][1]=o,e.push(["exit",o,t]),e},tokenize:function(e,t,n){const s=this;let r;return function(t){let o,a=s.events.length;for(;a--;)if("lineEnding"!==s.events[a][1].type&&"linePrefix"!==s.events[a][1].type&&"content"!==s.events[a][1].type){o="paragraph"===s.events[a][1].type;break}return s.parser.lazy[s.now().line]||!s.interrupt&&!o?n(t):(e.enter("setextHeadingLine"),r=t,function(t){return e.enter("setextHeadingLineSequence"),i(t)}(t))};function i(t){return t===r?(e.consume(t),i):(e.exit("setextHeadingLineSequence"),Yo(t)?sa(e,o,"lineSuffix")(t):o(t))}function o(s){return null===s||Zo(s)?(e.exit("setextHeadingLine"),t(s)):n(s)}}},Ya={tokenize:function(e){const t=this,n=e.attempt(ha,function(s){if(null!==s)return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n;e.consume(s)},e.attempt(this.parser.constructs.flowInitial,s,sa(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Ca,s)),"linePrefix")));return n;function s(s){if(null!==s)return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(s)}}},ec={resolveAll:rc()},tc=sc("string"),nc=sc("text");function sc(e){return{resolveAll:rc("text"===e?ic:void 0),tokenize:function(t){const n=this,s=this.parser.constructs[e],r=t.attempt(s,i,o);return i;function i(e){return c(e)?r(e):o(e)}function o(e){if(null!==e)return t.enter("data"),t.consume(e),a;t.consume(e)}function a(e){return c(e)?(t.exit("data"),r(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=s[e];let r=-1;if(t)for(;++r<t.length;){const e=t[r];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}}function rc(e){return function(t,n){let s,r=-1;for(;++r<=t.length;)void 0===s?t[r]&&"data"===t[r][1].type&&(s=r,r++):t[r]&&"data"===t[r][1].type||(r!==s+2&&(t[s][1].end=t[r-1][1].end,t.splice(s+2,r-s-2),r=s+2),s=void 0);return e?e(t,n):t}}function ic(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||"lineEnding"===e[n][1].type)&&"data"===e[n-1][1].type){const s=e[n-1][1],r=t.sliceStream(s);let i,o=r.length,a=-1,c=0;for(;o--;){const e=r[o];if("string"==typeof e){for(a=e.length;32===e.charCodeAt(a-1);)c++,a--;if(a)break;a=-1}else if(-2===e)i=!0,c++;else if(-1!==e){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const r={type:n===e.length||i||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:s.start._bufferIndex+a,_index:s.start._index+o,line:s.end.line,column:s.end.column-c,offset:s.end.offset-c},end:{...s.end}};s.end={...r.start},s.start.offset===s.end.offset?Object.assign(s,r):(e.splice(n,0,["enter",r,t],["exit",r,t]),n+=2)}n++}return e}const oc={42:Ga,43:Ga,45:Ga,48:Ga,49:Ga,50:Ga,51:Ga,52:Ga,53:Ga,54:Ga,55:Ga,56:Ga,57:Ga,62:fa},ac={91:Aa},cc={[-2]:ya,[-1]:ya,32:ya},lc={35:Pa,42:Qa,45:[Xa,Qa],60:qa,61:Xa,95:Qa,96:va,126:va},dc={38:ma,92:pa},uc={[-5]:Va,[-4]:Va,[-3]:Va,33:Wa,38:ma,42:la,60:[ua,$a],91:Ka,92:[Da,pa],93:za,95:la,96:wa},hc={null:[la,ec]},fc=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:ac,disable:{null:[]},document:oc,flow:lc,flowInitial:cc,insideSpan:hc,string:dc,text:uc},Symbol.toStringTag,{value:"Module"})),pc=/[\0\t\n\r]/g,mc=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function gc(e){return e.replace(mc,vc)}function vc(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return Ho(n.slice(t?2:1),t?16:10)}return Lo(n)||e}function yc(e){return e&&"object"==typeof e?"position"in e||"type"in e?wc(e.position):"start"in e||"end"in e?wc(e):"line"in e||"column"in e?bc(e):"":""}function bc(e){return xc(e&&e.line)+":"+xc(e&&e.column)}function wc(e){return bc(e&&e.start)+"-"+bc(e&&e.end)}function xc(e){return e&&"number"==typeof e?e:1}const Sc={}.hasOwnProperty;function kc(e,t,n){return t&&"object"==typeof t&&(n=t,t=void 0),function(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:r(y),autolinkProtocol:d,autolinkEmail:d,atxHeading:r(m),blockQuote:r(function(){return{type:"blockquote",children:[]}}),characterEscape:d,characterReference:d,codeFenced:r(p),codeFencedFenceInfo:i,codeFencedFenceMeta:i,codeIndented:r(p,i),codeText:r(function(){return{type:"inlineCode",value:""}},i),codeTextData:d,data:d,codeFlowValue:d,definition:r(function(){return{type:"definition",identifier:"",label:null,title:null,url:""}}),definitionDestinationString:i,definitionLabelString:i,definitionTitleString:i,emphasis:r(function(){return{type:"emphasis",children:[]}}),hardBreakEscape:r(g),hardBreakTrailing:r(g),htmlFlow:r(v,i),htmlFlowData:d,htmlText:r(v,i),htmlTextData:d,image:r(function(){return{type:"image",title:null,url:"",alt:null}}),label:i,link:r(y),listItem:r(function(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}),listItemValue:function(e){this.data.expectingFirstListItemValue&&(this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0)},listOrdered:r(b,function(){this.data.expectingFirstListItemValue=!0}),listUnordered:r(b),paragraph:r(function(){return{type:"paragraph",children:[]}}),reference:function(){this.data.referenceType="collapsed"},referenceString:i,resourceDestinationString:i,resourceTitleString:i,setextHeading:r(m),strong:r(function(){return{type:"strong",children:[]}}),thematicBreak:r(function(){return{type:"thematicBreak"}})},exit:{atxHeading:a(),atxHeadingSequence:function(e){const t=this.stack[this.stack.length-1];if(!t.depth){const n=this.sliceSerialize(e).length;t.depth=n}},autolink:a(),autolinkEmail:function(e){u.call(this,e),this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)},autolinkProtocol:function(e){u.call(this,e),this.stack[this.stack.length-1].url=this.sliceSerialize(e)},blockQuote:a(),characterEscapeValue:u,characterReferenceMarkerHexadecimal:f,characterReferenceMarkerNumeric:f,characterReferenceValue:function(e){const t=this.sliceSerialize(e),n=this.data.characterReferenceType;let s;n?(s=Ho(t,"characterReferenceMarkerNumeric"===n?10:16),this.data.characterReferenceType=void 0):s=Lo(t),this.stack[this.stack.length-1].value+=s},characterReference:function(e){this.stack.pop().position.end=Ic(e.end)},codeFenced:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}),codeFencedFence:function(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)},codeFencedFenceInfo:function(){const e=this.resume();this.stack[this.stack.length-1].lang=e},codeFencedFenceMeta:function(){const e=this.resume();this.stack[this.stack.length-1].meta=e},codeFlowValue:u,codeIndented:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/(\r?\n|\r)$/g,"")}),codeText:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),codeTextData:u,data:u,definition:a(),definitionDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},definitionLabelString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Bo(this.sliceSerialize(e)).toLowerCase()},definitionTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},emphasis:a(),hardBreakEscape:a(h),hardBreakTrailing:a(h),htmlFlow:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),htmlFlowData:u,htmlText:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),htmlTextData:u,image:a(function(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}),label:function(){const e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];if(this.data.inReference=!0,"link"===n.type){const t=e.children;n.children=t}else n.alt=t},labelText:function(e){const t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=gc(t),n.identifier=Bo(t).toLowerCase()},lineEnding:function(e){const n=this.stack[this.stack.length-1];if(this.data.atHardBreak)return n.children[n.children.length-1].position.end=Ic(e.end),void(this.data.atHardBreak=void 0);!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(d.call(this,e),u.call(this,e))},link:a(function(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}),listItem:a(),listOrdered:a(),listUnordered:a(),paragraph:a(),referenceString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Bo(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType="full"},resourceDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},resourceTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},resource:function(){this.data.inReference=void 0},setextHeading:a(function(){this.data.setextHeadingSlurpLineEnding=void 0}),setextHeadingLineSequence:function(e){this.stack[this.stack.length-1].depth=61===this.sliceSerialize(e).codePointAt(0)?1:2},setextHeadingText:function(){this.data.setextHeadingSlurpLineEnding=!0},strong:a(),thematicBreak:a()}};Cc(t,(e||{}).mdastExtensions||[]);const n={};return function(e){let r={type:"root",children:[]};const a={stack:[r],tokenStack:[],config:t,enter:o,exit:c,buffer:i,resume:l,data:n},d=[];let u=-1;for(;++u<e.length;)"listOrdered"!==e[u][1].type&&"listUnordered"!==e[u][1].type||("enter"===e[u][0]?d.push(u):u=s(e,d.pop(),u));for(u=-1;++u<e.length;){const n=t[e[u][0]];Sc.call(n,e[u][1].type)&&n[e[u][1].type].call(Object.assign({sliceSerialize:e[u][2].sliceSerialize},a),e[u][1])}if(a.tokenStack.length>0){const e=a.tokenStack[a.tokenStack.length-1];(e[1]||Rc).call(a,void 0,e[0])}for(r.position={start:Ic(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Ic(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},u=-1;++u<t.transforms.length;)r=t.transforms[u](r)||r;return r};function s(e,t,n){let s,r,i,o,a=t-1,c=-1,l=!1;for(;++a<=n;){const t=e[a];switch(t[1].type){case"listUnordered":case"listOrdered":case"blockQuote":"enter"===t[0]?c++:c--,o=void 0;break;case"lineEndingBlank":"enter"===t[0]&&(!s||o||c||i||(i=a),o=void 0);break;case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:o=void 0}if(!c&&"enter"===t[0]&&"listItemPrefix"===t[1].type||-1===c&&"exit"===t[0]&&("listUnordered"===t[1].type||"listOrdered"===t[1].type)){if(s){let o=a;for(r=void 0;o--;){const t=e[o];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;r&&(e[r][1].type="lineEndingBlank",l=!0),t[1].type="lineEnding",r=o}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}i&&(!r||i<r)&&(s._spread=!0),s.end=Object.assign({},r?e[r][1].start:t[1].end),e.splice(r||a,0,["exit",s,t[2]]),a++,n++}if("listItemPrefix"===t[1].type){const r={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0};s=r,e.splice(a,0,["enter",r,t[2]]),a++,n++,i=void 0,o=!0}}}return e[t][1]._spread=l,n}function r(e,t){return function(n){o.call(this,e(n),n),t&&t.call(this,n)}}function i(){this.stack.push({type:"fragment",children:[]})}function o(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:Ic(t.start),end:void 0}}function a(e){return function(t){e&&e.call(this,t),c.call(this,t)}}function c(e,t){const n=this.stack.pop(),s=this.tokenStack.pop();if(!s)throw new Error("Cannot close `"+e.type+"` ("+yc({start:e.start,end:e.end})+"): it’s not open");s[0].type!==e.type&&(t?t.call(this,e,s[0]):(s[1]||Rc).call(this,e,s[0])),n.position.end=Ic(e.end)}function l(){return Ao(this.stack.pop())}function d(e){const t=this.stack[this.stack.length-1].children;let n=t[t.length-1];n&&"text"===n.type||(n={type:"text",value:""},n.position={start:Ic(e.start),end:void 0},t.push(n)),this.stack.push(n)}function u(e){const t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=Ic(e.end)}function h(){this.data.atHardBreak=!0}function f(e){this.data.characterReferenceType=e.type}function p(){return{type:"code",lang:null,meta:null,value:""}}function m(){return{type:"heading",depth:0,children:[]}}function g(){return{type:"break"}}function v(){return{type:"html",value:""}}function y(){return{type:"link",title:null,url:"",children:[]}}function b(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}}(n)(function(e){for(;!ka(e););return e}(function(e){const t={constructs:_o([fc,...(e||{}).extensions||[]]),content:n(ra),defined:[],document:n(ia),flow:n(Ya),lazy:{},string:n(tc),text:n(nc)};return t;function n(e){return function(n){return function(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},i=[];let o=[],a=[];const c={attempt:m(function(e,t){g(e,t.from)}),check:m(p),consume:function(e){Zo(e)?(s.line++,s.column=1,s.offset+=-3===e?2:1,v()):-1!==e&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===o[s._index].length&&(s._bufferIndex=-1,s._index++)),l.previous=e},enter:function(e,t){const n=t||{};return n.type=e,n.start=h(),l.events.push(["enter",n,l]),a.push(n),n},exit:function(e){const t=a.pop();return t.end=h(),l.events.push(["exit",t,l]),t},interrupt:m(p,{interrupt:!0})},l={code:null,containerState:{},defineSkip:function(e){r[e.line]=e.column,v()},events:[],now:h,parser:e,previous:null,sliceSerialize:function(e,t){return function(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let o;if("string"==typeof i)o=i;else switch(i){case-5:o="\r";break;case-4:o="\n";break;case-3:o="\r\n";break;case-2:o=t?" ":"\t";break;case-1:if(!t&&r)continue;o=" ";break;default:o=String.fromCharCode(i)}r=-2===i,s.push(o)}return s.join("")}(u(e),t)},sliceStream:u,write:function(e){return o=qo(o,e),function(){let e;for(;s._index<o.length;){const t=o[s._index];if("string"==typeof t)for(e=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===e&&s._bufferIndex<t.length;)f(t.charCodeAt(s._bufferIndex));else f(t)}}(),null!==o[o.length-1]?[]:(g(t,0),l.events=ca(i,l.events,l),l.events)}};let d=t.tokenize.call(l,c);return t.resolveAll&&i.push(t),l;function u(e){return function(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let o;if(n===r)o=[e[n].slice(s,i)];else{if(o=e.slice(n,r),s>-1){const e=o[0];"string"==typeof e?o[0]=e.slice(s):o.shift()}i>0&&o.push(e[r].slice(0,i))}return o}(o,e)}function h(){const{_bufferIndex:e,_index:t,line:n,column:r,offset:i}=s;return{_bufferIndex:e,_index:t,line:n,column:r,offset:i}}function f(e){d=d(e)}function p(e,t){t.restore()}function m(e,t){return function(n,r,i){let o,d,u,f;return Array.isArray(n)?p(n):"tokenize"in n?p([n]):function(e){return function(t){const n=null!==t&&e[t],s=null!==t&&e.null;return p([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(s)?s:s?[s]:[]])(t)}}(n);function p(e){return o=e,d=0,0===e.length?i:m(e[d])}function m(e){return function(n){return f=function(){const e=h(),t=l.previous,n=l.currentConstruct,r=l.events.length,i=Array.from(a);return{from:r,restore:function(){s=e,l.previous=t,l.currentConstruct=n,l.events.length=r,a=i,v()}}}(),u=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?y():e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,g,y)(n)}}function g(t){return e(u,f),r}function y(e){return f.restore(),++d<o.length?m(o[d]):i}}}function g(e,t){e.resolveAll&&!i.includes(e)&&i.push(e),e.resolve&&Fo(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function v(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",s=!0;return function(r,i,o){const a=[];let c,l,d,u,h;for(r=n+("string"==typeof r?r.toString():new TextDecoder(i||void 0).decode(r)),d=0,n="",s&&(65279===r.charCodeAt(0)&&d++,s=void 0);d<r.length;){if(pc.lastIndex=d,c=pc.exec(r),u=c&&void 0!==c.index?c.index:r.length,h=r.charCodeAt(u),!c){n=r.slice(d);break}if(10===h&&d===u&&e)a.push(-3),e=void 0;else switch(e&&(a.push(-5),e=void 0),d<u&&(a.push(r.slice(d,u)),t+=u-d),h){case 0:a.push(65533),t++;break;case 9:for(l=4*Math.ceil(t/4),a.push(-2);t++<l;)a.push(-1);break;case 10:a.push(-4),t=1;break;default:e=!0,t=1}d=u+1}return o&&(e&&a.push(-5),n&&a.push(n),a.push(null)),a}}()(e,t,!0))))}function Ic(e){return{line:e.line,column:e.column,offset:e.offset}}function Cc(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Cc(e,s):jc(e,s)}}function jc(e,t){let n;for(n in t)if(Sc.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function Rc(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+yc({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+yc({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+yc({start:t.start,end:t.end})+") is still open")}const Ec=new WeakMap;function Mc(e){const t=e=>{if("image"===e.type||"html"===e.type)return"";if("string"==typeof e.value)return e.value;const n=["root","list","listItem","blockquote"].includes(e.type)?"\n":"";return(e.children??[]).map(e=>t(e)).join(n)};return t(kc(e))}function Tc(e,t){const n=t.trim().toLowerCase();return n?e.flatMap((e,t)=>{if(Yi(e))return[];let s=Ec.get(e);s?.content!==e.content&&(s={content:e.content,text:Mc(e.content).toLowerCase()},Ec.set(e,s));const r=s.text,i=[];for(let o=r.indexOf(n);o>=0;o=r.indexOf(n,o+n.length))i.push({index:t,message:e,occurrence:i.length});return i}):[]}function Ac(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[];let i="";for(;s.nextNode();){const e=s.currentNode;e.parentElement?.closest('button, [hidden], [aria-hidden="true"]')||(r.push({node:e,start:i.length,end:i.length+e.length}),i+=e.data)}const o=[],a=i.toLowerCase();for(let c=a.indexOf(n);c>=0;c=a.indexOf(n,c+n.length)){const e=c+n.length,t=r.find(e=>e.end>c),s=r.find(t=>t.end>=e);if(!t||!s)continue;const i=document.createRange();i.setStart(t.node,c-t.start),i.setEnd(s.node,e-s.start),o.push(i)}return o}const Nc=128;function Dc(e){return Math.max(0,e-Nc)}const Pc=()=>null,Lc=()=>()=>{};function Fc({activeSession:e,activeUsage:s,messages:r,renameTitle:i,busy:a,t:c,onBrowseFiles:l,onClose:d,onExport:u,onJumpToMessage:h,onRename:f,onRenameTitleChange:p,onToggleArchived:m,onTogglePinned:g,onViewChanges:v}){const[y,b]=t.useState(""),{copyText:w,feedback:x}=qi(c.commandCopied,c.copyResumeFailed),S=t.useRef(null),k=j(d,S),I=t.useMemo(()=>ft(e),[e]),C=t.useMemo(()=>{const e=y.trim().toLowerCase();return e?r.map((e,t)=>({message:e,index:t})).filter(({message:t})=>("user"===t.role||"assistant"===t.role)&&t.content.toLowerCase().includes(e)).slice(0,20):[]},[r,y]);return n.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:k,role:"dialog",tabIndex:-1,children:[n.jsx("div",{className:"drawer-backdrop",onClick:d,"aria-hidden":"true"}),n.jsxs("aside",{className:"session-detail-panel",children:[n.jsxs("header",{className:"drawer-header",children:[n.jsxs("div",{children:[n.jsx("span",{className:"eyebrow",children:e.agent}),n.jsx("strong",{id:"session-detail-title",title:o(e),children:n.jsx(jo,{title:o(e),draft:i,label:c.rename,disabled:a,onDraftChange:p,onCommit:f},e.sessionId)})]}),n.jsx("button",{"aria-label":c.closeSessionDetails,title:c.closeSessionDetails,className:"icon-button",onClick:d,ref:S,type:"button",children:n.jsx(Be,{"aria-hidden":"true"})})]}),n.jsxs("div",{className:"detail-info-grid",children:[n.jsxs("div",{children:[n.jsx(te,{"aria-hidden":"true"}),n.jsx("span",{children:c.workingDirectory}),n.jsx("strong",{title:e.cwd,children:e.cwd})]}),n.jsxs("div",{children:[n.jsx(ge,{"aria-hidden":"true"}),n.jsx("span",{children:c.messages}),n.jsx("strong",{children:r.filter(e=>"user"===e.role||"assistant"===e.role).length})]}),n.jsxs("div",{children:[n.jsx(ce,{"aria-hidden":"true"}),n.jsx("span",{children:c.session}),n.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),n.jsxs("div",{children:[n.jsx($e,{"aria-hidden":"true"}),n.jsx("span",{children:c.runtime}),n.jsx("strong",{children:c.runtimeState(e.runtime.state)})]})]}),e.branch||e.diffStat?n.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:v,children:[n.jsx(oe,{"aria-hidden":"true"}),n.jsx("span",{className:"detail-change-label",children:e.branch??c.changes}),n.jsx("span",{className:"detail-change-stats",role:"group","aria-label":c.changes,children:e.diffStat?n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),n.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,n.jsxs("label",{className:"detail-search",children:[n.jsx(Te,{"aria-hidden":"true"}),n.jsx("input",{value:y,onChange:e=>b(e.target.value),placeholder:c.searchMessages}),y.trim()?n.jsx("small",{children:c.searchResultCount(C.length)}):null]}),y.trim()&&C.length?n.jsx("div",{className:"detail-search-results",children:C.map(({message:e,index:t})=>n.jsxs("button",{type:"button",onClick:()=>{h(t,y),d()},children:[n.jsx("span",{children:Pt(e,c)}),n.jsx("strong",{children:e.content})]},`${e.historyKey??e.timestamp??t}:${t}`))}):null,y.trim()?null:n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"detail-command-card",type:"button",onClick:l,children:[n.jsx(te,{"aria-hidden":"true"}),n.jsx("span",{children:c.browseFiles})]}),I&&n.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{w(I)},children:[n.jsx(B,{"aria-hidden":"true"}),n.jsx("span",{title:I,children:I})]}),n.jsx(Oi,{feedback:x}),n.jsxs("div",{className:"detail-action-grid",children:[n.jsxs("button",{className:"icon-text-button",disabled:a,type:"button",onClick:g,children:[n.jsx(Ie,{"aria-hidden":"true"}),e.pinned?c.unpin:c.pin]}),n.jsxs("button",{className:"icon-text-button",disabled:a,type:"button",onClick:m,children:[n.jsx(N,{"aria-hidden":"true"}),e.archived?c.unarchive:c.archive]}),n.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[n.jsx(E,{"aria-hidden":"true"}),c.exportSession]})]}),s?n.jsxs("p",{className:"detail-usage",children:[c.usage,": ",s.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",s.limits?.weekly?.usedPercent??"-","% weekly"]}):null,n.jsxs("p",{className:"detail-usage",children:[c.created," ",Dt(e.createdAt,Date.now(),c)]})]})]})]})}function qc({activeSession:e,activeUsage:t,busy:s,messages:r,renameTitle:i,t:o,onBrowseFiles:a,onDetailsOpenChange:c,onExportActiveSession:l,onRenameSession:d,onRenameTitleChange:u,onToggleArchived:h,onTogglePinned:f,onViewChanges:p,onJumpToMessage:m}){return e?n.jsx(Fc,{activeSession:e,activeUsage:t,busy:s,messages:r,renameTitle:i,t:o,onBrowseFiles:()=>{c(!1),a()},onClose:()=>c(!1),onExport:l,onJumpToMessage:(e,t)=>{m(e,t)},onRename:d,onRenameTitleChange:u,onToggleArchived:h,onTogglePinned:f,onViewChanges:()=>{c(!1),p(e.sessionId)}}):null}function Oc({client:e,activeSession:s,activeSessionId:r,activeModelOptions:i,activeQueue:o,queueControls:a,activeUsage:c,agent:l,approvalMode:d,attachments:u,busy:h,rewinding:f,cwd:p,draft:m,effort:g,errorText:v,failedSend:y,onDismissFailedSend:b,fastMode:w,historyLoading:x,hasOlderHistory:S,olderHistoryLoading:k,onLoadOlderHistory:I,messages:C,messagesSessionId:j,model:R,phase:E,quickReplies:M,onQuickRepliesChange:T,quickRepliesOpen:A,onQuickRepliesOpenChange:N,onSendQuickReply:D,renameTitle:P,respondingSessionIds:L,sendShortcut:F,skills:q,uploadBusy:O,detailsOpen:_,t:$,onApprovalModeChange:z,onBrowseFiles:H,onCancelQueuedTurn:B,onClearInterrupt:U,onDraftChange:W,onDetailsOpenChange:K,onEffortChange:V,onExportActiveSession:Q,onRewindMessage:G,onFastModeChange:J,onRetryFailedSend:Z,onModelChange:X,onOpenRemoteFile:Y,onInterrupt:ee,onRetry:te,onDismissError:ne,onRefreshSkills:se,onRenameSession:re,onRenameTitleChange:ie,onRemoveAttachment:oe,onSubmit:ae,onToggleArchived:ce,onTogglePinned:le,onUploadFiles:de,onViewChanges:ue}){const he=Rr(e,l,p,r,R,i,$),fe=function(e,n,s,r){const i=t.useSyncExternalStore(e.submission?.subscribe??Lc,e.submission?.getSnapshot??Pc,Pc),o=t.useRef(new Set),a=async e=>{if(!o.current.has(r)){o.current.add(r);try{await e()}finally{o.current.delete(r)}}};return{sending:!!i?.some(e=>e.sessionId===r),submit:t=>{if(t?.preventDefault(),s)return a(()=>e())},retry:()=>a(n)}}(ae,Z,"connected"===E&&!h&&!O&&!u.some(e=>e.uploading)&&(!!m.trim()||u.length>0),r),pe=function(e){const n=t.useRef(e);return t.useLayoutEffect(()=>{n.current=e}),n}({onRewindMessage:G,onOpenRemoteFile:Y,onDismissFailedSend:b,retry:fe.retry}),[me,ge]=t.useState(null),[ve,ye]=t.useState(null),[be,we]=t.useState(!1),xe=function(e,n,s){let r;for(let t=n.length-1;t>=0;t--)if("assistant"===n[t].role&&"info"!==n[t].type){r=n[t];break}const i=r?`${r.historyKey??r.timestamp}:${r.content.length}`:"",o=t.useRef({sessionId:e,revision:i}),[a,c]=t.useState(!1);return t.useEffect(()=>{o.current.sessionId===e&&s?i&&i!==o.current.revision&&c(!0):c(!1),o.current={sessionId:e,revision:i}},[e,i,s]),s&&o.current.sessionId===e&&a}(r,j===r?C:[],be),Se=t.useRef(null),ke=t.useRef([]),Ie=t.useRef(null),Ce=t.useRef(null),je=t.useRef(!1),Re=t.useRef(!1),Ee=t.useRef(!0),Me=t.useRef(0),Te=t.useRef(0),Ae=t.useMemo(()=>function(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];if(!Yi(s)){t.push({type:"message",index:n,message:s});continue}const r=[];let i=n;for(;i<e.length&&Yi(e[i]);)r.push({index:i,message:e[i]}),i+=1;t.push({type:"toolGroup",entries:r,id:`tool-group:${r.map(({index:e,message:t})=>to(t,e)).join("|")}`}),n=i-1}return t}(C),[C]),Ne=Boolean(r&&L.has(r)),De=Ne&&j===r&&!x,Pe=De&&"assistant"===C.at(-1)?.role&&"info"!==C.at(-1)?.type?C.length-1:-1,[Le,Fe]=t.useState(!1),{ensureMessageVisible:qe,hiddenItemCount:Oe,hiddenLaterItemCount:_e,revealAll:$e,revealEarlier:ze,revealLatest:He,revealStart:Be,visibleItems:Ue}=function(e,n,s=!1){const r=n.length,[i,o]=t.useState(()=>({sessionId:e,start:Dc(r),total:r})),a=i.sessionId!==e?Dc(r):s?0:-1===i.start?-1:r>i.total&&i.start+Nc>=i.total?Dc(r):Math.min(i.start,Dc(r));t.useLayoutEffect(()=>{i.sessionId===e&&i.start===a&&i.total===r||o({sessionId:e,start:a,total:r})},[e,a,i,r]);const c=t.useCallback(()=>{o(t=>({sessionId:e,start:Math.max(0,(t.sessionId===e?t.start:Dc(r))-96),total:r}))},[e,r]),l=t.useCallback(t=>{const s=n.findIndex(e=>function(e,t){return"message"===e.type?e.index===t:e.entries.some(e=>e.index===t)}(e,t));if(-1===a||s<0||s>=a&&s<a+Nc)return!1;const i=Math.min(Dc(r),Math.max(0,s-40));return o({sessionId:e,start:i,total:r}),!0},[n,e,a,r]),d=t.useCallback(()=>{o({sessionId:e,start:Dc(r),total:r})},[e,r]),u=t.useCallback(()=>{o({sessionId:e,start:0,total:r})},[e,r]),h=Math.max(0,a),f=-1===a?r:Math.min(r,a+Nc);return{ensureMessageVisible:l,hiddenItemCount:h,hiddenLaterItemCount:Math.max(0,r-f),revealEarlier:c,revealLatest:d,revealStart:u,revealAll:()=>o({sessionId:e,start:-1,total:r}),visibleItems:t.useMemo(()=>n.slice(h,f),[n,h,f])}}(r,Ae,Le),We=t.useRef(!1),Ke=t.useRef(null),Ve=t.useMemo(()=>Boolean(y&&Ue.some(e=>"message"===e.type&&e.message.historyKey===y.historyKey)),[y,Ue]),Qe=t.useRef(null),{copyText:Ge,feedback:Je}=qi($.messageCopied,$.copyFailed),Ze=function(e,n,s,r){const[i,o]=t.useState(""),[a,c]=t.useState(0),l=t.useMemo(()=>Tc(e,i),[e,i]),d=l.length?a%l.length:0,u=l[d],h=t.useRef(r);return h.current=r,t.useEffect(()=>{o(""),c(0)},[n]),t.useEffect(()=>{u&&h.current(u.index)},[i,d,u?.index]),t.useEffect(()=>{const e=s.current;if(!i.trim()||!e||"undefined"==typeof CSS||!CSS.highlights||"undefined"==typeof Highlight)return;let t=0,n=!1;const r=()=>{const t=[],s=[];for(const n of e.querySelectorAll(".message-frame[data-message-index]")){const e=n.querySelector(".message-markdown, .message-markdown-source, .message > pre");if(!e)continue;const r=Ac(e,i);t.push(...r),Number(n.getAttribute("data-message-index"))===u?.index&&r[u.occurrence]&&s.push(r[u.occurrence])}if(CSS.highlights.set("conversation-matches",new Highlight(...t)),CSS.highlights.set("conversation-current",new Highlight(...s)),s[0]&&!n){n=!0;const t=s[0].getBoundingClientRect(),r=e.getBoundingClientRect();(t.top<r.top||t.bottom>r.bottom)&&(e.scrollTop+=t.top-r.top-r.height/2)}},o=()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{t=requestAnimationFrame(r)})},a=new MutationObserver(o);return a.observe(e,{childList:!0,characterData:!0,subtree:!0}),o(),()=>{a.disconnect(),cancelAnimationFrame(t),CSS.highlights.delete("conversation-matches"),CSS.highlights.delete("conversation-current")}},[i,d,u?.index,u?.occurrence,s]),{query:i,matchCount:l.length,activeMatchIndex:l.length?d+1:0,activeMessageIndex:u?.index,onChange:e=>{o(e),c(0)},onJump:(t,n)=>{o(n),c(Math.max(0,Tc(e,n).findIndex(e=>e.index===t)))},onNext:()=>c(e=>l.length?(e+1)%l.length:0),onPrevious:()=>c(e=>l.length?(e+l.length-1)%l.length:0)}}(C,r,Se,e=>((e,t="smooth")=>{Ee.current=!1,Me.current=0;const n=qe(e),s=()=>ke.current[e]?.scrollIntoView({behavior:t,block:"center"});n?requestAnimationFrame(()=>requestAnimationFrame(s)):s()})(e,"instant")),Xe=t.useCallback(()=>{const e=Se.current;e&&(Ee.current=!0,Me.current=0,e.scrollTop=e.scrollHeight,we(!1))},[]),Ye=t.useCallback(e=>{Ee.current=!0,Me.current=0,Re.current=!0,je.current=!1,Qe.current=null;const t=Se.current,n=t?t.scrollHeight-t.scrollTop-t.clientHeight:0,s=e??(0===_e&&t&&n<=t.clientHeight?"smooth":"auto"),r=()=>{const e=Se.current;e&&Re.current&&(e.scrollTo({top:e.scrollHeight,behavior:s}),we(!1),requestAnimationFrame(()=>{Re.current=!1}))};_e>0?(He(),requestAnimationFrame(()=>requestAnimationFrame(r))):r()},[_e,He]),et=()=>{const e=Se.current;e&&(Qe.current=function(e,t){const n=e.querySelector(".message-frame"),s=t[0];return{element:n,message:"message"===s?.type?s.message:s?.entries[0]?.message,top:n?n.getBoundingClientRect().top-e.getBoundingClientRect().top:e.scrollTop,height:e.scrollHeight}}(e,Ue))},tt=async()=>{if(!r||!S||!I||x||k||Ke.current)return;const e=r;Ke.current=e,We.current=!0,Ee.current=!1,je.current=!0,et(),Fe(!0);try{await I()}finally{Ke.current===e&&(Ke.current=null,Fe(!1))}},nt=()=>{const e=Se.current;if(!e)return;Me.current>0&&e.scrollTop<160&&j===r&&!je.current&&!Re.current&&(Oe>0?(je.current=!0,et(),ze()):tt());const t=e.scrollTop>Te.current;Te.current=e.scrollTop;const n=e.scrollHeight-e.scrollTop-e.clientHeight;Me.current>0&&!Re.current&&!je.current&&(Ee.current=t&&n<=2&&0===_e),we(n>180||_e>0)};t.useLayoutEffect(()=>{_e>0&&we(!0)},[_e]);const st=function(e,t,n,s,r,i,o,a=0){const c=()=>{const o=t.current||s.current;n.current=null,s.current=!1,t.current=!1,r.current=performance.now();const a=e.current;i.current=a?.scrollTop??0,o&&a?.scrollTo({top:a.scrollTop,behavior:"auto"})};return{toStart:()=>{const c=e.current;c&&(n.current=null,s.current=!1,t.current=!1,r.current=performance.now(),i.current=0,c.scrollTo({top:c.scrollTop,behavior:"auto"}),a>0&&o?.(),requestAnimationFrame(()=>requestAnimationFrame(()=>e.current?.scrollTo({top:0,behavior:a>0?"auto":"smooth"}))))},onWheel:t=>{if(!t.deltaY)return;const n=e.current;(t.deltaY<0||n&&n.scrollHeight-n.scrollTop-n.clientHeight>2)&&c()},onPointerDown:e=>{const t=e.currentTarget.getBoundingClientRect();(1===e.button||e.clientX>=t.right-16)&&c()},onTouchStart:c,onKeyDown:e=>{e.target instanceof Element&&e.target.closest('input,textarea,[contenteditable="true"]')||["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&c()}}}(Se,Ee,Ce,Re,Me,Te,Be,Oe),rt=function(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}(C);t.useLayoutEffect(()=>{Ie.current!==r&&(Qe.current=null,je.current=!1,We.current=!1,Ke.current=null,Fe(!1));const e=Qe.current,t=Se.current;if(e&&t){if(Le)return;return Oe>0&&We.current?void Be():(function(e,t,n,s){const r=t.message,i=r?n.findIndex(e=>e===r||(r.historyKey?e.historyKey===r.historyKey:e.role===r.role&&e.timestamp===r.timestamp&&e.content===r.content)):-1,o=i>=0?s[i]:t.element;e.scrollTop+=o?.isConnected?o.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top:e.scrollHeight-t.height}(t,e,C,ke.current),Qe.current=null,je.current=!1,void(We.current=!1))}if(Ie.current!==r&&(Ie.current=r,Ce.current=r,ge(null),ye(null)),!Se.current)return;const n=j===r;if(null!==r&&Ce.current===r&&n&&(!x||C.length>0)){Xe();let e=0,t=-1,n=0;const s=performance.now(),i=()=>{if(Ce.current!==r)return;Xe();const o=Se.current?.scrollHeight??0;n=o===t?n+1:0,t=o;const a=performance.now()-s>=1400;!x&&n>=4||!x&&a?Ce.current=null:a||(e=requestAnimationFrame(i))};return e=requestAnimationFrame(i),we(!1),()=>cancelAnimationFrame(e)}Ee.current&&0===_e&&Xe()},[r,Oe,_e,x,rt,Le,Be,C.length,j,E,De,Xe]),t.useLayoutEffect(()=>{const e=Se.current;if(!e)return;const t=new ResizeObserver(()=>{Ee.current&&0===_e&&Xe()});t.observe(e);for(const n of e.children)t.observe(n);return()=>t.disconnect()},[r,rt,Oe,_e,De,Xe]);const it=Ze.activeMessageIndex;return function(e,n,s){const r=t.useRef(s);r.current=s;const i=t.useRef(!1),[o,a]=t.useState(0);t.useLayoutEffect(()=>{i.current=!1;const t=t=>{"focusin"===t.type&&t.target instanceof Element&&t.target.contains(e.current)||(i.current=t.target instanceof Element&&Boolean(e.current?.contains(t.target))&&!t.target.closest("input,textarea,select")&&!t.target.isContentEditable)},n=[["pointerdown",t],["focusin",t],["keydown",e=>{i.current&&!e.isComposing&&(!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"a"!==e.key.toLowerCase()||(e.preventDefault(),r.current(),a(e=>e+1)))}]];return n.forEach(([e,t])=>document.addEventListener(e,t,!0)),()=>n.forEach(([e,t])=>document.removeEventListener(e,t,!0))},[e,n]),t.useLayoutEffect(()=>{if(!i.current)return;const t=e.current?.querySelectorAll(".message-frame"),n=t?.[t.length-1];n&&window.getSelection()?.setBaseAndExtent(t[0],0,n,n.childNodes.length)},[o,e,n])}(Se,r,()=>{et(),$e()}),n.jsxs("section",{className:"chat-pane","aria-label":$.chat,children:[n.jsx(Mo,{activeSession:s,agent:l,cwd:p,t:$,onOpenDetails:()=>s&&K(!0),onScrollToStart:st.toStart,renameTitle:P,busy:h,onRename:re,onRenameTitleChange:ie,onViewChanges:ue,search:Ze}),n.jsxs("div",{className:"message-scroll","data-session-id":j===r?r??void 0:void 0,"aria-busy":x,"data-history-loading":x?"true":"false","data-rendered-items":Ue.length,"data-hidden-items":Oe,"data-hidden-later-items":_e,"data-total-messages":C.length,ref:Se,onScroll:nt,...st,onWheel:e=>{st.onWheel(e),e.deltaY<0&&nt()},children:[x&&0===C.length?n.jsx($i,{label:$.loadingHistory}):null,x||0!==C.length||De?null:n.jsx(Er,{title:s?$.noVisibleMessages:$.startDaemonSession,hint:$.emptyChatHint}),S&&0===Oe?n.jsx("div",{className:"conversation-window-gate",children:n.jsx("button",{type:"button",disabled:k,onClick:()=>{tt()},children:k?$.loadingHistory:$.loadEarlierMessages})}):null,Oe>0?n.jsx("div",{className:"conversation-window-gate",children:n.jsx("button",{type:"button",onClick:()=>{je.current=!0,et(),ze()},children:$.showEarlierMessages(Oe)})}):null,n.jsx(wo,{items:Ue,activeQueue:j===r?o:void 0,actions:pe,messageRefs:ke,activeMatchedMessageIndex:it,baseCwd:s?.cwd,canRewind:!h&&!Ne,hiddenLaterItemCount:_e,replyingMessageIndex:Pe,openSourceKey:me,openToolKey:ve,setOpenSourceKey:ge,setOpenToolKey:ye,copyText:Ge,failedSend:y,t:$}),De&&0===_e&&Pe<0?n.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:n.jsx("div",{className:"message assistant replying-placeholder",children:n.jsx(mo,{label:$.replyingMessage})})}):null,_e>0?n.jsx("div",{className:"conversation-window-gate",children:n.jsx("button",{type:"button",onClick:()=>Ye("auto"),children:$.showLatestMessages(_e)})}):null,n.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"})]}),be?n.jsx(Hi,{label:xe?$.interactionNewReply:$.interactionLatest,onClick:()=>Ye()}):null,n.jsx(Oi,{feedback:Je}),n.jsx(Fi,{terminals:s?.runtime.backgroundTerminals,t:$},`terminals:${r}`),n.jsx(Co,{rewinding:f,client:e,activeSession:s,busy:h,errorText:v,failedSend:y,failedSendVisibleInConversation:Ve,onClearInterrupt:U,onDismissError:ne,onDismissFailedSend:b,onRetry:te,onRetryFailedSend:()=>{fe.retry()},t:$}),t.createElement(Li,{client:e,activeSessionId:r,key:r,activeModelOptions:he,activeQueue:o,queueControls:{...a,onAction:(e,t)=>(Ye("auto"),a.onAction(e,t))},agent:l,approvalMode:d,attachments:u,busy:h,sending:fe.sending,responding:Ne,onStop:ee,draft:m,effort:g,fastMode:w,model:R,phase:E,quickReplies:M,onQuickRepliesChange:T,quickRepliesOpen:A,onQuickRepliesOpenChange:N,onSendQuickReply:D,sendShortcut:F,skills:q,uploadBusy:O,onApprovalModeChange:z,onCancelQueuedTurn:B,onDraftChange:W,onEffortChange:V,onFastModeChange:J,onModelChange:X,onRemoveAttachment:oe,onOpenRemoteFile:Y,onRefreshSkills:se,onSubmit:e=>(Ye("auto"),fe.submit(e)),onUploadFiles:de,t:$}),_?n.jsx(qc,{activeSession:s,activeUsage:c,busy:h,messages:C,renameTitle:P,t:$,onBrowseFiles:H,onDetailsOpenChange:K,onExportActiveSession:Q,onRenameSession:re,onRenameTitleChange:ie,onToggleArchived:ce,onTogglePinned:le,onViewChanges:ue,onJumpToMessage:Ze.onJump}):null]})}const _c=["accountActivationCode","account-activation-code","activationCode","activation-code","apiKey","api_key","api-key","x-api-key","accessKey","access-key","accessKeyId","access-key-id","password","secret","secretAccessKey","secret-access-key","token","access-token","refresh-token","security-token","cookie","set-cookie","authorization","proxy-authorization","x-amz-credential","x-amz-security-token","x-amz-signature"],$c=["authorization","proxy-authorization"],zc=["cookie","set-cookie"],Hc=[...$c,...zc],Bc=(e,t)=>t.length-e.length,Uc=[..._c].sort(Bc).join("|"),Wc=_c.filter(e=>!Hc.includes(e)).sort(Bc).join("|"),Kc=[...$c].sort(Bc).join("|"),Vc=[...zc].sort(Bc).join("|"),Qc=new RegExp(`(?:${Uc}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),Gc=new RegExp(`(["']?(?:${Kc})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Jc=new RegExp(`(["']?(?:${Vc})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),Zc=new RegExp(`(["']?(?:${Wc})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),Xc=new RegExp(`([?&](?:${Uc})=)[^&\\s]+`,"gi");function Yc(e){return function(e){return e.replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gim,"$1[LOCAL_PATH]").replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)(?:\/[^\s"'<>]*)?/gim,"$1[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gi,"[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\\\\[^\s\\"'<>]+\\[^\r\n"'<>]+/g,"[LOCAL_PATH]").replace(/\bcontent:\/\/[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\b(?:[\w.-]+\/)+(?:[\w.-]+\.(?:md|txt|json|ya?ml|pdf|docx?|xlsx?|csv|log|db|sqlite|png|jpe?g|webp|gif))\b/gi,"[RELATIVE_PATH]")}(function(e,t="[REDACTED]"){const n=(e,n,s)=>{const r='"'===s[0]||"'"===s[0]?s[0]:"";if(!r)return`${n}${t}`;const i=s.slice(1,-1).trim(),o=/^(Basic|Bearer)\b/i.exec(i)?.[1];return`${n}${r}${o?`${o} `:""}${t}${r}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(Gc,n).replace(Jc,n).replace(Zc,n).replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,`Bearer ${t}`).replace(/\bBasic\s+[A-Za-z0-9+/=_-]+/gi,`Basic ${t}`).replace(/\bsk(?:-proj)?-[A-Za-z0-9_-]{8,}/g,t).replace(/\bgh[pousr]_[A-Za-z0-9]{16,}\b/gi,t).replace(/\bgithub_pat_[A-Za-z0-9_]{16,}\b/gi,t).replace(/\bglpat-[A-Za-z0-9_-]{16,}\b/gi,t).replace(/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/gi,t).replace(/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{12,}\b/gi,t).replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g,t).replace(/\bAKIA[0-9A-Z]{16}\b/g,t).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,t).replace(/(https?:\/\/)[^/\s:@]+:[^@\s/]+@/gi,`$1${t}@`).replace(Xc,`$1${t}`)}(e)).replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,"[EMAIL]").replace(new RegExp("(?<![\\w])(?:\\+?\\d[\\d\\s().-]{7,}\\d)(?![\\w])","g"),"[PHONE]")}async function el(e){const t=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body,signal:e.signal});return{status:t.status,statusText:t.statusText,body:await t.text()}}async function tl(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let r;try{const i=(t.transport??el)({url:t.endpoint??"https://service.lifeos.vip/feedback",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((e,t)=>{r=setTimeout(()=>{n.abort(),t(new Error("Feedback request timed out"))},s)}),a=await Promise.race([i,o]),c=function(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(a.body);if(a.status<200||a.status>=300||0!==c.code)throw new Error(c.message||a.statusText||"Feedback request failed");if("string"!=typeof c.data?.id||!c.data.id||"string"!=typeof c.data.createdAt)throw new Error("Feedback response is invalid");return{id:c.data.id,createdAt:c.data.createdAt,issueFingerprint:"string"==typeof c.data?.issueFingerprint?c.data.issueFingerprint:void 0,issueOccurrence:"number"==typeof c.data?.issueOccurrence?c.data.issueOccurrence:void 0}}finally{r&&clearTimeout(r)}}const nl=new Set(["action","app","automatic","browser","buildNumber","contextSchemaVersion","correlationId","debugEnabled","deviceFingerprint","diagnosticSchemaVersion","entry","errorCode","errorMessage","module","pagePath","pageTitle","pageUrl","pluginId","privacy","providerPreset","reportKind","resultKind","runtime","screen","storageType","updateChannel","userAgent"]);function sl(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))nl.has(n)&&void 0!==s&&(t[n]=s);return function(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),s=Math.max(0,t.maxArrayEntries??50),r=Math.max(0,t.maxDepth??8),i=Math.max(0,t.maxObjectEntries??80),o=Math.max(0,t.maxStringLength??4e3),a={remaining:n},c=new WeakSet,l=(e,t)=>{if(a.remaining<=0)return"[TRUNCATED]";if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if("bigint"==typeof e)return e.toString();if("string"==typeof e){const t=Yc(e).slice(0,Math.min(o,a.remaining));return a.remaining-=t.length,t}if(t>=r)return"[MAX_DEPTH]";if("object"!=typeof e)return Yc(String(e)).slice(0,Math.min(200,a.remaining));if(c.has(e))return"[Circular]";if(c.add(e),Array.isArray(e))return e.slice(0,s).map(e=>l(e,t+1));const n={};for(const[s,r]of Object.entries(e).slice(0,i)){if(a.remaining<=0)break;const e=Yc(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=Qc.test(s)?"[REDACTED]":l(r,t+1)}return n};return l(e,0)}(t)}const rl={title:"Feedback",subtitle:"Report a problem or suggest an improvement.",bug:"Problem",feature:"Suggestion",description:"Description",descriptionPlaceholder:"What happened, or what would you like to improve?",email:"Email (optional)",emailPlaceholder:"For a reply from the team",includeDiagnostics:"Include privacy-safe diagnostics",privacyNotice:"Only include diagnostics when needed. Recognized credentials, personal identifiers, and local paths are removed before sending.",submit:"Send feedback",sending:"Sending…",success:"Thank you. Your feedback has been sent.",error:"Could not send feedback. Please try again.",close:"Close"},il={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},ol={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function al(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?ol:t.startsWith("zh")?il:rl}const cl=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function ll(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!cl.has(e.mimeType))throw new Error("Feedback image type is not supported");const t=function(e){if(!e||e.length%4!=0||!/^[A-Za-z0-9+/]*={0,2}$/u.test(e))return;const t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}(e.base64);if(!Number.isSafeInteger(e.size)||e.size<=0||t!==e.size)throw new Error("Feedback image size does not match its data");return{name:Yc(e.name.trim()||"image").slice(0,255),mimeType:e.mimeType,size:e.size,base64:e.base64}});if(t.reduce((e,t)=>e+t.size,0)>20971520)throw new Error("Feedback images are too large");return t}function dl({language:e,entry:s="web-settings"}){const i=a(e),o=t.useMemo(()=>al(i),[i]),[c,l]=t.useState("bug"),[d,u]=t.useState(""),[h,f]=t.useState(""),[p,m]=t.useState("idle");return n.jsxs("section",{className:"control-section compact-section",children:[n.jsx("h2",{children:o.title}),n.jsx("p",{className:"empty-copy",children:o.subtitle}),n.jsxs("div",{className:"feedback-type-grid",children:[n.jsx("button",{className:"bug"===c?"primary-button":"",type:"button","aria-pressed":"bug"===c,onClick:()=>l("bug"),children:o.bug}),n.jsx("button",{className:"feature"===c?"primary-button":"",type:"button","aria-pressed":"feature"===c,onClick:()=>l("feature"),children:o.feature})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:o.description}),n.jsx("textarea",{rows:5,maxLength:8e3,value:d,placeholder:o.descriptionPlaceholder,onChange:e=>u(e.target.value)})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:o.email}),n.jsx("input",{type:"email",maxLength:320,value:h,placeholder:o.emailPlaceholder,onChange:e=>f(e.target.value)})]}),n.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===p,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==p){m("sending");try{await tl(function(e){const t=function(e){return Yc(e.trim()).slice(0,8e3)}(e.description);if(!t)throw new Error("Feedback description is required");const n=!1!==e.includeLogs&&e.logs?function(e,t=6e4){const n=Yc(e);return n.length<=t?n:`[truncated ${n.length-t} chars]\n${n.slice(-t)}`}(e.logs):"",s=e.email?.trim().slice(0,320);return{product:e.product,source:e.source,type:e.type,description:t,email:s||void 0,appVersion:e.appVersion?.trim().slice(0,64)||"unknown",locale:e.locale?.trim().slice(0,64)||"unknown",platform:e.platform?.trim().slice(0,128)||"unknown",logsIncluded:Boolean(n),logs:n||void 0,metadata:sl(e.metadata),images:ll(e.images)}}({product:"vibelet",source:"desktop"===r().kind?"desktop":"web",type:c,description:d,email:h,appVersion:r().appVersion||"web",locale:i,platform:navigator.platform||"web",metadata:{app:"desktop"===r().kind?"vibelet-desktop":"vibelet-web",entry:s,screen:"connection-guide"===s?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),u(""),m("success")}catch{m("error")}}})()},children:"sending"===p?o.sending:o.submit}),"success"===p?n.jsx("p",{className:"empty-copy success-copy",children:o.success}):null,"error"===p?n.jsx("p",{className:"empty-copy error-copy",children:o.error}):null]})}const ul=[[0,.024],[.05,.078],[.25,.157],[.5,.243],[.75,.325],[.9,.4],[.97,.459],[.995,.506],[1,.533]];function hl(e,t,n){let s=374761393*e+668265263*t+2147483647*n|0;return s=Math.imul(s^s>>>13,1274126177),s^=s>>>16,(s>>>0)/4294967295}function fl(e,t,n,s){const r=Math.floor(e),i=Math.floor(t),o=e-r,a=t-i,c=o*o*o*(o*(6*o-15)+10),l=a*a*a*(a*(6*a-15)+10),d=e=>(e%n+n)%n,u=hl(d(r),i,s),h=hl(d(r+1),i,s),f=hl(d(r),i+1,s);return u+(h-u)*c+(f-u)*l+(u-h-f+hl(d(r+1),i+1,s))*c*l}function pl(e,t,n,s){const r=new Float32Array(e*e);for(let i=0;i<e;i++)for(let o=0;o<e;o++){let a=0,c=1,l=0;for(let r=0;r<n;r++){const n=t<<r;a+=c*fl(o/e*n,i/e*(n/2),n,s+97*r),l+=c,c*=.5}r[i*e+o]=a/l}return r}function ml(e,t,n){let s=0;for(const a of e)s+=a;const r=s/e.length;let i=0;for(const a of e)i+=(a-r)**2;const o=Math.sqrt(i/e.length)||1;return e.map(e=>t+(e-r)/o*n)}function gl(e,t,n){const s=Math.floor(6*e),r=6*e-s,i=n*(1-t),o=n*(1-r*t),a=n*(1-(1-r)*t);switch((s%6+6)%6){case 0:return[n,a,i];case 1:return[o,n,i];case 2:return[i,n,a];case 3:return[i,o,n];case 4:return[a,i,n];default:return[n,i,o]}}let vl=null;const yl=["fixed","gradient-2","gradient-3","spectrum"],bl=["none","brighten","flow","spotlight"],wl={color:"#b126ff",colorMode:"spectrum",color2:"#ff177c",color3:"#35d3ff",fixedColor:!1,speed:.7,paused:!1,phase:0,feather:95,projectionScale:174,intensity:1.15,grain:.035,seed:7},xl=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t)),Sl=e=>{let t=e.replace(/^#/,"");return/^[\da-f]{3}$/i.test(t)&&(t=Array.from(t,e=>e+e).join("")),/^[\da-f]{6}$/i.test(t)||(t="b126ff"),[0,2,4].map(e=>parseInt(t.slice(e,e+2),16)/255)};function kl({columns:e=1,rows:s=1,gap:r=0,colorSpread:i=0,centerProjectionScale:o,borderRadius:a,hoverEffect:c="none",...l}){const d=t.useRef(null),u=t.useRef(null),h=()=>({...wl,...Object.fromEntries(Object.entries(l).filter(([,e])=>void 0!==e)),colorMode:l.colorMode??(l.fixedColor?"fixed":"spectrum"),columns:e,rows:s,gap:r,colorSpread:i,centerProjectionScale:o,borderRadius:a,hoverEffect:c}),f=t.useRef(h());return t.useEffect(()=>{f.current=h(),u.current?.()}),t.useEffect(()=>{const e=d.current,t=e.parentElement instanceof HTMLButtonElement?e.parentElement:null,n=e.getContext("webgl",{alpha:!0,premultipliedAlpha:!0,antialias:!1});if(!n)return;let s=null,r=null,i=null,o=null,a=null,c=!1,l={},h=0,p=0,m=0,g=0,v=0,y=!1,b=!1,w=[0,0],x=!0,S=!1,k=!1,I=1,C=1;const j=matchMedia("(prefers-reduced-motion: reduce)"),R=(e,t)=>{const s=n.createShader(e);return n.shaderSource(s,t),n.compileShader(s),n.getShaderParameter(s,n.COMPILE_STATUS)?s:(n.deleteShader(s),null)},E=()=>{n.deleteBuffer(r),n.deleteProgram(s),n.deleteShader(i),n.deleteShader(o),n.deleteTexture(a),r=null,s=null,i=null,o=null,a=null},M=()=>{i=R(n.VERTEX_SHADER,"\nattribute vec2 a_position;\nvarying vec2 v_uv;\nvoid main() {\n v_uv = a_position * .5 + .5;\n gl_Position = vec4(a_position, 0., 1.);\n}");const t=!!n.getExtension("OES_standard_derivatives");k=t&&!!n.getExtension("EXT_shader_texture_lod");const d=(t?"#define USE_CHROMATIC_DERIVATIVES\n":"")+(k?"#define USE_CHROMATIC_TEXTURE_LOD\n":"");if(o=R(n.FRAGMENT_SHADER,d+"\n#ifdef USE_CHROMATIC_DERIVATIVES\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\nvarying vec2 v_uv;\nuniform vec2 u_size;\nuniform vec2 u_resolution;\nuniform vec2 u_grid;\nuniform float u_gap;\nuniform float u_time;\nuniform float u_phase;\nuniform float u_feather;\nuniform float u_projectionScale;\nuniform float u_centerProjectionScale;\nuniform float u_borderRadius;\nuniform float u_intensity;\nuniform float u_grain;\nuniform float u_spread;\nuniform float u_seed;\nuniform vec3 u_color;\nuniform float u_colorMode;\nuniform vec3 u_color2;\nuniform vec3 u_color3;\nuniform sampler2D u_field;\nuniform float u_hover;\nuniform float u_hoverEffect;\nuniform vec2 u_hoverPosition;\n\nfloat hash(vec3 p) {\n p = fract(p * .1031);\n p += dot(p, p.yzx + 33.33);\n return fract((p.x + p.y) * p.z);\n}\nvec3 hsv(vec3 c) {\n vec3 p = abs(fract(c.xxx + vec3(0., 2./3., 1./3.)) * 6. - 3.);\n return c.z * mix(vec3(1.), clamp(p - 1., 0., 1.), c.y);\n}\nvec3 rgbToHsv(vec3 c) {\n vec4 k = vec4(0., -1./3., 2./3., -1.);\n vec4 p = mix(vec4(c.bg, k.wz), vec4(c.gb, k.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n float d = q.x - min(q.w, q.y);\n return vec3(abs(q.z + (q.w - q.y) / (6. * d + 1.e-8)), d / (q.x + 1.e-8), q.x);\n}\nmat2 rotate(float a) { return mat2(cos(a), -sin(a), sin(a), cos(a)); }\n\nvec3 rotatedField(vec2 source, float t, float tile) {\n vec2 uv = source * vec2(3.14159265, 1.57079633);\n vec3 sphere = vec3(cos(uv.y) * sin(uv.x), sin(uv.y), cos(uv.y) * cos(uv.x));\n sphere.xy = rotate(sin(t * .22 + tile * 3.1) * .55) * sphere.xy;\n sphere.yz = rotate(sin(t * .18 + tile * 2.4) * .55) * sphere.yz;\n sphere.xz = rotate(t * .16 + tile * 6.28) * sphere.xz;\n vec2 fieldUv = vec2(atan(sphere.x, sphere.z) / 6.283185 + .5, asin(clamp(sphere.y, -1., 1.)) / 3.141593 + .5);\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n // Longitude wraps from 1 to 0 on the back meridian. Implicit derivatives see\n // that as a full-texture jump and pick the smallest mip, drawing dotted seams,\n // so select the mip from the wrapped (true) longitude change instead.\n vec2 dx = dFdx(fieldUv);\n vec2 dy = dFdy(fieldUv);\n dx.x -= floor(dx.x + .5);\n dy.x -= floor(dy.x + .5);\n return texture2DGradEXT(u_field, fieldUv, dx, dy).rgb;\n#else\n return texture2D(u_field, fieldUv).rgb;\n#endif\n}\nvec3 blurredField(vec2 source, float t, float tile) {\n // Blur the rotated field in the unprojected plane so compressed edges\n // remain soft after projection.\n float b = .045;\n vec3 c = rotatedField(source, t, tile) * .28;\n c += (rotatedField(source + vec2(b,0), t, tile) + rotatedField(source - vec2(b,0), t, tile)\n + rotatedField(source + vec2(0,b), t, tile) + rotatedField(source - vec2(0,b), t, tile)) * .12;\n c += (rotatedField(source + vec2(b,b), t, tile) + rotatedField(source - vec2(b,b), t, tile)\n + rotatedField(source + vec2(b,-b), t, tile) + rotatedField(source + vec2(-b,b), t, tile)) * .06;\n return c;\n}\nvec2 projectedSource(vec2 p, float fov) {\n vec2 angle = p * fov;\n float longitude = clamp(angle.x, -1.565, 1.565);\n float latitude = clamp(angle.y, -1.565, 1.565);\n return vec2(tan(longitude), tan(latitude) / max(.005, cos(longitude))) / tan(fov);\n}\nvec2 contourExtent() {\n vec2 halfSize = max(vec2(2.), (u_size / u_grid - u_gap) * .5);\n return halfSize / min(halfSize.x, halfSize.y);\n}\nfloat contourRadius(vec2 p) {\n // Intersect a ray with circular corners in physical coordinates. A wide\n // button retains straight sides and round end caps instead of becoming an ellipse.\n vec2 direction = abs(p) / max(length(p), .000001);\n vec2 extent = contourExtent();\n vec2 center = extent - u_borderRadius;\n if (direction.y * extent.x <= direction.x * center.y)\n return extent.x / max(direction.x, .000001);\n if (direction.x * extent.y <= direction.y * center.x)\n return extent.y / max(direction.y, .000001);\n float cross = direction.x * center.y - direction.y * center.x;\n return dot(direction, center)\n + sqrt(max(u_borderRadius * u_borderRadius - cross * cross, 0.));\n}\nfloat contourBoundary(vec2 p) {\n if (u_borderRadius < 0.) return max(abs(p.x), abs(p.y));\n vec2 physical = p * contourExtent();\n return length(physical) / max(contourRadius(physical), .000001);\n}\nvec2 materialSource(vec2 p, float fov, float centerFov) {\n if (u_borderRadius >= 0.) {\n // Project from the actual contour instead of clipping a square field.\n // Every point on the rounded/circular edge reaches the same source rim.\n float radius = contourBoundary(p);\n float angle = mix(centerFov, fov, smoothstep(.8, .95, radius));\n float projected = tan(min(radius * angle, 1.565)) / tan(angle);\n return p / max(length(p), .000001) * projected;\n }\n // The face can keep its own projection, which sets how the central gradient\n // moves, while the rim reflections keep the outer projection.\n float rim = smoothstep(.8, .95, max(abs(p.x), abs(p.y)));\n return mix(projectedSource(p, centerFov), projectedSource(p, fov), rim);\n}\nfloat projectedBoundary(vec2 p, float fov, float centerFov) {\n vec2 source = materialSource(p, fov, centerFov);\n return u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n}\nvoid main() {\n vec2 cellSize = u_size / u_grid;\n vec2 pixel = vec2(v_uv.x, 1. - v_uv.y) * u_size;\n vec2 id = floor(pixel / cellSize);\n vec2 halfSize = max(vec2(2.), (cellSize - u_gap) * .5);\n vec2 p = (mod(pixel, cellSize) - cellSize * .5) / halfSize;\n float tile = fract(dot(id, vec2(.754877666, .569840296)) + u_seed * .1031);\n float t = u_time + u_phase * 6.283185;\n if (u_hoverEffect > 1.5 && u_hoverEffect < 2.5) t += u_hover * 1.25;\n\n // Inverse of AE's Plane to Sphere: a 174 degree flat plane is mapped into\n // an equirectangular 360 x 180 degree frame. Most source pixels compress\n // into the perimeter; the colored rim is the projected field itself.\n float fov = radians(u_projectionScale * .5);\n float centerFov = radians(u_centerProjectionScale * .5);\n vec2 source = materialSource(p, fov, centerFov);\n float boundary = u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n float boxBoundary = contourBoundary(p);\n float edgeWidth;\n float boxWidth;\n#ifdef USE_CHROMATIC_DERIVATIVES\n edgeWidth = fwidth(boundary);\n boxWidth = fwidth(boxBoundary);\n#else\n // Match one framebuffer pixel even on devices without shader derivatives.\n vec2 dp = u_size / u_resolution / halfSize;\n vec2 dx = vec2(dp.x * .5, 0.);\n vec2 dy = vec2(0., dp.y * .5);\n edgeWidth = abs(projectedBoundary(p + dx, fov, centerFov) - projectedBoundary(p - dx, fov, centerFov))\n + abs(projectedBoundary(p + dy, fov, centerFov) - projectedBoundary(p - dy, fov, centerFov));\n boxWidth = abs(contourBoundary(p + dx) - contourBoundary(p - dx))\n + abs(contourBoundary(p + dy) - contourBoundary(p - dy));\n#endif\n edgeWidth = max(edgeWidth, .0001);\n boxWidth = max(boxWidth, .0001);\n float feather = clamp(u_feather / 360., .001, 1.);\n // Integrate coverage across the pixel footprint instead of cutting a\n // subpixel contour. Feather still controls the material's inner softness.\n float opacity = 1. - smoothstep(1. - feather - edgeWidth * .5, 1. + edgeWidth * .5, boundary);\n opacity *= 1. - smoothstep(1. - boxWidth * .5, 1. + boxWidth * .5, boxBoundary);\n\n // Rotate the already colored, softened source as a panoramic field, just\n // as VR Rotate Sphere precedes the Plane to Sphere adjustment layer.\n vec2 sampleSource = source;\n if (u_hoverEffect > 2.5) sampleSource -= u_hoverPosition * u_hover * .18;\n vec3 sourceColor = blurredField(sampleSource, t, tile);\n float intensity = u_intensity;\n if (u_hoverEffect > .5 && u_hoverEffect < 1.5) intensity *= 1. + u_hover * .3;\n if (u_hoverEffect > 2.5) {\n vec2 light = p - u_hoverPosition;\n intensity *= 1. + u_hover * .4 * exp(-dot(light, light) * 3.);\n }\n vec3 sourceHsv = rgbToHsv(sourceColor);\n vec3 base = rgbToHsv(u_color);\n float hue = sourceHsv.x + base.x - .81 + tile * u_spread + t * .075;\n vec3 color = hsv(vec3(hue, sourceHsv.y * base.y, min(1., sourceHsv.z * 1.75 * intensity * base.z)));\n if (u_colorMode < 2.5) {\n vec3 palette = u_color;\n if (u_colorMode > .5) {\n // Change the whole material's tint over time. Spatial coordinates\n // affect the reflections, never the selected palette's color.\n float flow = .5 - .5 * cos((tile * u_spread + t * .075) * 6.283185);\n palette = mix(u_color, u_color2, flow);\n if (u_colorMode > 1.5) {\n palette = flow < .5\n ? mix(u_color, u_color2, flow * 2.)\n : mix(u_color2, u_color3, flow * 2. - 1.);\n }\n }\n vec3 paletteHsv = rgbToHsv(palette);\n color = hsv(vec3(paletteHsv.xy, min(1., sourceHsv.z * 1.75 * intensity * paletteHsv.z)));\n }\n color += (hash(vec3(floor(pixel * 1.5), u_seed)) - .5) * u_grain * (.1 + length(color) * .15);\n gl_FragColor = vec4(max(color, 0.) * opacity, opacity);\n}"),!i||!o)return void E();if(s=n.createProgram(),n.attachShader(s,i),n.attachShader(s,o),n.linkProgram(s),!n.getProgramParameter(s,n.LINK_STATUS))return void E();n.useProgram(s),r=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),n.STATIC_DRAW);const u=n.getAttribLocation(s,"a_position");n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),a=n.createTexture(),n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([20,0,35,255])),l=Object.fromEntries(["size","resolution","grid","gap","time","phase","feather","projectionScale","centerProjectionScale","borderRadius","intensity","grain","spread","seed","color","colorMode","color2","color3","field","hover","hoverEffect","hoverPosition"].map(e=>[e,n.getUniformLocation(s,`u_${e}`)])),!c&&!S&&s&&a&&(n.bindTexture(n.TEXTURE_2D,a),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,128,128,0,n.RGBA,n.UNSIGNED_BYTE,function(){if(vl)return vl;const e=function(e,t){const n=Array.from(e.keys()).sort((t,n)=>e[t]-e[n]),s=new Float32Array(e.length);return n.forEach((n,r)=>{const i=r/(e.length-1);let o=1;for(;o<t.length-1&&t[o][0]<i;)o++;const[a,c]=t[o-1],[l,d]=t[o];s[n]=c+(i-a)/Math.max(1e-6,l-a)*(d-c)}),s}(pl(128,4,4,11),ul),t=ml(pl(128,3,3,29),.83,.05),n=ml(pl(128,5,2,53),.988,.03),s=new Uint8Array(65536);for(let r=0;r<16384;r++){const[i,o,a]=gl((t[r]%1+1)%1,Math.min(1,Math.max(.8,n[r])),e[r]);s[4*r]=Math.round(255*i),s[4*r+1]=Math.round(255*o),s[4*r+2]=Math.round(255*a),s[4*r+3]=255}return vl=s,s}()),k&&(n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR)),e.dataset.renderer="webgl",$())},T=()=>!!s&&!S&&x&&!document.hidden&&!j.matches&&(!f.current.paused&&0!==f.current.speed||Math.abs(v-g)>.001),A=()=>{if(!s||S)return;const r=f.current,i=Math.round(xl(r.columns,1,1,24)),o=Math.round(xl(r.rows,1,1,24));n.viewport(0,0,e.width,e.height),n.uniform2f(l.size,I,C),n.uniform2f(l.resolution,e.width,e.height),n.uniform2f(l.grid,i,o),n.uniform1f(l.gap,xl(r.gap,0,0,Math.max(0,Math.min(I/i,C/o)-4))),n.uniform1f(l.time,m),n.uniform1f(l.hover,t?.disabled||"none"===r.hoverEffect?0:g),n.uniform1f(l.hoverEffect,Math.max(0,bl.indexOf(r.hoverEffect))),n.uniform2f(l.hoverPosition,...w),n.uniform1f(l.phase,xl(r.phase,0,-1e3,1e3)),n.uniform1f(l.feather,xl(r.feather,95,0,100));const c=xl(r.projectionScale,174,90,179.5);n.uniform1f(l.projectionScale,c),n.uniform1f(l.centerProjectionScale,xl(r.centerProjectionScale??c,c,90,179.5)),n.uniform1f(l.borderRadius,void 0===r.borderRadius?-1:xl(r.borderRadius,50,0,50)/50),n.uniform1f(l.intensity,xl(r.intensity,1.15,0,3)),n.uniform1f(l.grain,xl(r.grain,.035,0,.5)),n.uniform1f(l.spread,xl(r.colorSpread,0,0,2)),n.uniform1f(l.seed,xl(r.seed,7,0,65535)),n.uniform3fv(l.color,Sl(r.color)),n.uniform1f(l.colorMode,yl.indexOf(r.colorMode)),n.uniform3fv(l.color2,Sl(r.color2)),n.uniform3fv(l.color3,Sl(r.color3)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,a),n.uniform1i(l.field,0),n.drawArrays(n.TRIANGLES,0,6)},N=e=>{if(h=0,T()){if(p){const t=Math.min((e-p)/1e3,.1);f.current.paused||(m+=t*xl(f.current.speed,.7,0,4)),g+=(v-g)*(1-Math.exp(14*-t)),Math.abs(v-g)<=.001&&(g=v)}p=e,A(),T()&&(h=requestAnimationFrame(N))}else p=0},D=()=>{v=t&&!t.disabled&&"none"!==f.current.hoverEffect&&(y||b)?1:0,(j.matches||"none"===f.current.hoverEffect||t?.disabled)&&(g=v)},P=()=>{D(),h||(p=0,A(),T()&&(h=requestAnimationFrame(N)))},L=e=>{"touch"!==e.pointerType&&(y=!0,P())},F=()=>{y=!1,P()},q=()=>{b=!!t?.matches(":focus-visible"),b&&(w=[0,0]),P()},O=()=>{b=!1,P()},_=e=>{if(!t||t.disabled||"touch"===e.pointerType||"spotlight"!==f.current.hoverEffect)return;const n=t.getBoundingClientRect();w=[Math.max(-1,Math.min(1,(e.clientX-n.left)/Math.max(1,n.width)*2-1)),Math.max(-1,Math.min(1,(e.clientY-n.top)/Math.max(1,n.height)*2-1))],h||A()},$=()=>{cancelAnimationFrame(h),h=0,p=0,D(),A(),T()&&(h=requestAnimationFrame(N))},z=()=>{I=Math.max(1,e.clientWidth),C=Math.max(1,e.clientHeight);const t=Math.min(devicePixelRatio||1,2,Math.sqrt(15e5/(I*C)));e.width=Math.max(1,Math.round(I*t)),e.height=Math.max(1,Math.round(C*t)),$()},H=t=>{t.preventDefault(),S=!0,cancelAnimationFrame(h),delete e.dataset.renderer},B=()=>{S=!1,E(),M(),z()};M(),t?.addEventListener("pointerenter",L),t?.addEventListener("pointerleave",F),t?.addEventListener("pointercancel",F),t?.addEventListener("pointermove",_),t?.addEventListener("focus",q),t?.addEventListener("blur",O);const U=new ResizeObserver(z);U.observe(e);const W=new IntersectionObserver(([e])=>{x=e.isIntersecting,$()});return W.observe(e),document.addEventListener("visibilitychange",$),j.addEventListener("change",$),e.addEventListener("webglcontextlost",H),e.addEventListener("webglcontextrestored",B),u.current=$,z(),()=>{c=!0,u.current=null,cancelAnimationFrame(h),U.disconnect(),W.disconnect(),document.removeEventListener("visibilitychange",$),j.removeEventListener("change",$),e.removeEventListener("webglcontextlost",H),e.removeEventListener("webglcontextrestored",B),delete e.dataset.renderer,E(),t?.removeEventListener("pointerenter",L),t?.removeEventListener("pointerleave",F),t?.removeEventListener("pointercancel",F),t?.removeEventListener("pointermove",_),t?.removeEventListener("focus",q),t?.removeEventListener("blur",O)}},[]),n.jsx("canvas",{ref:d,className:"chromatic-surface","aria-hidden":"true",tabIndex:-1})}const Il={...wl,feather:100,projectionScale:174.7,intensity:1.4,grain:.105,borderRadius:50,hoverEffect:"brighten",entrance:"blur-up",entranceSpeed:1,entranceBlur:10,entranceDistance:20,entranceScale:.65},Cl=t.forwardRef(function({children:e="Get started",className:s="",type:r="button",color:i=Il.color,colorMode:o,color2:a=Il.color2,color3:c=Il.color3,fixedColor:l,speed:d,paused:u,phase:h,feather:f=Il.feather,projectionScale:p=Il.projectionScale,intensity:m=Il.intensity,grain:g=Il.grain,borderRadius:v=Il.borderRadius,hoverEffect:y=Il.hoverEffect,entrance:b=Il.entrance,entranceSpeed:w=Il.entranceSpeed,entranceBlur:x=Il.entranceBlur,entranceDistance:S=Il.entranceDistance,entranceScale:k=Il.entranceScale,seed:I,style:C,...j},R){const E=t.useRef(null);t.useImperativeHandle(R,()=>E.current,[]),t.useEffect(()=>{const e=E.current,t=()=>{e.style.setProperty("--chromatic-button-short-side",`${Math.min(e.clientWidth,e.clientHeight)}px`)};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),t.useEffect(()=>{if("spotlight"!==y||j.disabled)return;const e=E.current,t=matchMedia("(prefers-reduced-motion: reduce)"),n=[0,0],s=[0,0],r=[0,0];let i=0,o=0,a=!1;const c=()=>Math.min(10,.18*Math.min(e.clientWidth,e.clientHeight)),l=()=>{cancelAnimationFrame(i),i=o=0,n.fill(0),s.fill(0),r.fill(0),e.style.removeProperty("--chromatic-pointer-transform")},d=a=>{if(i=0,t.matches||e.disabled||document.hidden)return void l();const u=o?Math.min((a-o)/1e3,1/30):1/60;o=a;const h=Math.max(1,Math.ceil(120*u)),f=u/h;for(let e=0;e<h;e++)for(let t=0;t<2;t++)s[t]+=(220*(r[t]-n[t])-16*s[t])*f,n[t]+=s[t]*f;const p=n.every((e,t)=>Math.abs(e-r[t])<.01&&Math.abs(s[t])<.05);if(p&&(n.splice(0,2,...r),s.fill(0),r.every(e=>0===e)))return void l();const m=Math.max(-1,Math.min(1,(Math.abs(n[0])-Math.abs(n[1]))/Math.max(1,c())));e.style.setProperty("--chromatic-pointer-transform",`translate(${n[0]}px, ${n[1]}px) scale(${1+.025*m}, ${1-.025*m})`),p?o=0:i=requestAnimationFrame(d)},u=()=>{i||(i=requestAnimationFrame(d))},h=e=>{"touch"===e.pointerType||t.matches||(a=!0)},f=s=>{if(!a||"touch"===s.pointerType||t.matches||e.disabled)return;const i=e.getBoundingClientRect(),o=[i.left+i.width/2-n[0],i.top+i.height/2-n[1]];r[0]=Math.max(-1,Math.min(1,(s.clientX-o[0])/Math.max(1,e.clientWidth/2)))*c(),r[1]=Math.max(-1,Math.min(1,(s.clientY-o[1])/Math.max(1,e.clientHeight/2)))*c(),u()},p=()=>{a=!1,r.fill(0),u()},m=()=>{a=!1,l()},g=()=>{document.hidden&&m()};return e.addEventListener("pointerenter",h),e.addEventListener("pointermove",f),e.addEventListener("pointerleave",p),e.addEventListener("pointercancel",p),t.addEventListener("change",m),document.addEventListener("visibilitychange",g),()=>{l(),e.removeEventListener("pointerenter",h),e.removeEventListener("pointermove",f),e.removeEventListener("pointerleave",p),e.removeEventListener("pointercancel",p),t.removeEventListener("change",m),document.removeEventListener("visibilitychange",g)}},[y,j.disabled]);const M=Math.min(50,Math.max(0,Number.isFinite(v)?v:Il.borderRadius)),T=function(e,t,n=!1){const s=e=>Math.SQRT2*(1-e/50)+e/50,r=s(Math.min(50,Math.max(0,Number.isFinite(t)?t:Il.borderRadius)))/s(Il.borderRadius),i=Math.min(179.5,Math.max(90,Number.isFinite(e)?e:174.7))*Math.PI/360;return Math.min(179.5,Math.max(90,360*Math.atan(Math.tan(i)*(n?1/r:r))/Math.PI))}(p,M),A=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t));return n.jsxs("button",{...j,ref:E,type:r,"data-hover-effect":y,"data-entrance":b,className:`chromatic-button ${s}`.trim(),style:{"--chromatic-button-color":i,"--chromatic-button-radius":M/100,"--chromatic-entrance-speed":A(w,1,.1,4),"--chromatic-entrance-blur":`${A(x,10,0,40)}px`,"--chromatic-entrance-distance":`${A(S,20,0,120)}px`,"--chromatic-entrance-scale":A(k,.65,.05,1),...C},children:[n.jsx(kl,{color:i,colorMode:o,color2:a,color3:c,fixedColor:l,speed:d,paused:u,phase:h,feather:f,projectionScale:T,borderRadius:M,hoverEffect:y,centerProjectionScale:T-(Il.projectionScale-wl.projectionScale),intensity:m,grain:g,seed:I}),n.jsx("span",{className:"chromatic-button-content",children:e})]})}),jl=t.forwardRef(function({className:e="",style:s,...r},i){const[o,a]=t.useState(["#a87bb2","#c27ba0"]),[c,l]=t.useState(!1),[d,u]=t.useState(!1),h=t.useRef(null),f=e=>{h.current=e,"function"==typeof i?i(e):i&&(i.current=e)};return t.useEffect(()=>{u("undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver&&"undefined"!=typeof WebGL2RenderingContext);const e=()=>{if(!h.current)return;const e=getComputedStyle(h.current);a([e.getPropertyValue("--accent").trim()||"#a87bb2",e.getPropertyValue("--accent-secondary").trim()||"#c27ba0"])};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class","style"]}),()=>t.disconnect()},[]),d?n.jsx(Cl,{...r,ref:f,className:`product-chromatic-action ${e}`,style:s,color:o[0],color2:o[1],colorMode:"gradient-2",intensity:1.2,borderRadius:25,grain:.04,entrance:"none",hoverEffect:"brighten",paused:!c||r.disabled,speed:.25,onPointerEnter:e=>{l(!0),r.onPointerEnter?.(e)},onPointerLeave:e=>{l(!1),r.onPointerLeave?.(e)},onFocus:e=>{l(!0),r.onFocus?.(e)},onBlur:e=>{l(!1),r.onBlur?.(e)}}):n.jsx("button",{...r,ref:f,className:`product-chromatic-action chromatic-button ${e}`,style:s,children:n.jsx("span",{className:"chromatic-button-content",children:r.children})})}),Rl={en:{label:"Pairing link",hint:"Paste a Web link from the CLI or the connected mobile app.",connect:"Connect",invalid:"Enter a valid Web pairing link.",expired:"This link has expired. Generate a new link."},zh:{label:"配对链接",hint:"粘贴 CLI 或已连接手机分享的 Web 链接。",connect:"连接",invalid:"请输入有效的 Web 配对链接。",expired:"链接已过期,请重新生成。"},"zh-TW":{label:"配對連結",hint:"貼上 CLI 或已連線手機分享的 Web 連結。",connect:"連線",invalid:"請輸入有效的 Web 配對連結。",expired:"連結已過期,請重新產生。"}};function El(){const e=Rl[a(c().language)],[s,r]=t.useState(""),[i,o]=t.useState("");return n.jsxs("form",{className:"web-pairing-form",onSubmit:t=>{t.preventDefault();try{const e=new URL(function(e){const t=function(e){if(e.length>16384)throw new Error("Pairing link is too long");const t=new URL(e),n="vibelet:"===t.protocol&&"pair"===t.hostname?t.searchParams.get("link"):null,s=n?new URL(n):t,r=s.searchParams.get("data");return r&&!s.hash&&"vibelet:"===s.protocol&&"pair"===s.hostname&&(s.hash=new URLSearchParams({pair:r}).toString(),s.searchParams.delete("data")),s}(e.trim()),n=en(t.hash);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||!n)throw new Error("invalid");if(n.expiresAt&&(!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now()))throw new Error("expired");return t.pathname="/web/",t.search="",t.href}(s)),t=e.origin===window.location.origin&&e.pathname===window.location.pathname&&e.search===window.location.search;window.location.assign(e.href),t&&window.location.reload()}catch(n){o(n instanceof Error&&"expired"===n.message?e.expired:e.invalid)}},children:[n.jsx("label",{htmlFor:"web-pairing-link",children:e.label}),n.jsx("p",{children:e.hint}),n.jsx("input",{id:"web-pairing-link",value:s,onChange:e=>{r(e.target.value),o("")},autoComplete:"off",spellCheck:!1,required:!0}),n.jsx(jl,{className:"primary-button",type:"submit",children:e.connect}),i&&n.jsx("p",{role:"alert",className:"connection-guide-error",children:i})]})}const Ml="vibelet --access=quick";function Tl({errorText:e,t:s}){const[r,i]=t.useState("idle"),[o,a]=t.useState(!1),l=c().language,d=al(l);return n.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:n.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[n.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:n.jsx(qe,{})}),n.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet"}),n.jsx("h1",{id:"connection-guide-title",children:s.openDaemonWebLink}),n.jsx("p",{children:s.openDaemonWebLinkHint}),n.jsx(El,{}),n.jsxs("div",{className:"connection-command",children:[n.jsx("code",{children:Ml}),n.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await _n(Ml),i("success")}catch{i("error")}window.setTimeout(()=>i("idle"),1800)})()},type:"button",children:["success"===r?n.jsx(O,{"aria-hidden":"true"}):n.jsx(V,{"aria-hidden":"true"}),n.jsx("span",{children:"success"===r?s.commandCopied:"error"===r?s.copyFailed:s.copyStartCommand})]})]}),n.jsx("p",{className:"connection-guide-footnote",children:s.connectionGuideFootnote}),e?n.jsx("p",{className:"connection-guide-error",children:e}):null,n.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":o,onClick:()=>a(e=>!e),children:[n.jsx(ge,{"aria-hidden":"true"}),d.title]}),o?n.jsx("div",{className:"connection-feedback-panel",children:n.jsx(dl,{language:l,entry:"connection-guide"})}):null]})})}const Al=t.lazy(()=>R(()=>import("./ImageViewer-CK5ZHIVv.js"),__vite__mapDeps([8,1,2,9,10])));function Nl(){const[e,s]=t.useState(null);return t.useEffect(()=>{const e=e=>s(e.detail);return window.addEventListener(Ur,e),()=>window.removeEventListener(Ur,e)},[]),e?n.jsx(t.Suspense,{fallback:null,children:n.jsx(Al,{request:e,onClose:()=>s(null)},e.images[e.index].src)}):null}const Dl=t.createContext(null),Pl={browser:ae,terminal:qe,diff:oe};function Ll(e){return"浏览器"===e.browser?{center:"移到中间区域",right:"移到右侧栏",create:"新建标签页",drop:"拖到这里以移动标签页"}:"瀏覽器"===e.browser?{center:"移到中間區域",right:"移到右側欄",create:"新增標籤頁",drop:"拖到這裡以移動標籤頁"}:{center:"Move to workspace",right:"Move to sidebar",create:"New tab",drop:"Drop here to move tab"}}function Fl({location:e,kind:s,t:r,cwd:i}){const o=st(),a=Ll(r),c=t.useRef(null),l=t.useRef(null),d=o.items.filter(t=>t.location===e&&(!s||t.kind===s)),u=function(e,n,s,r=""){const i=t.useContext(Dl),o=i?.element;n=n&&i?.kind===s;const[a,c]=t.useState(!1);return t.useLayoutEffect(()=>{const t=e.current,s=o?.querySelector(".control-tabs");if(!(n&&o&&t&&s))return;const r=()=>{const n=(e.current??t).cloneNode(!0);n.setAttribute("aria-hidden","true"),n.inert=!0,Object.assign(n.style,{position:"fixed",visibility:"hidden",width:"max-content",maxWidth:"none",left:"-10000px",font:getComputedStyle(t).font}),document.body.append(n);const r=n.getBoundingClientRect().width;n.remove();const i=o.clientWidth-s.getBoundingClientRect().width-8;c(e=>r>0?r<=i:e)},i=new ResizeObserver(r);return i.observe(o),i.observe(s),r(),()=>i.disconnect()},[n,o,e,r]),n&&a?o:null}(l,"right"===e&&d.length>1,s,d.map(e=>`${e.id}:${e.title}`).join("|"));if(t.useEffect(()=>{"right"===e&&s&&!o.items.some(e=>e.kind===s)&&o.add(s,r["browser"===s?"browser":"terminal"],i)},[e,s,o.epoch,o.scopeKey]),t.useEffect(()=>{if("right"!==e||!c.current)return;const t=c.current.querySelector('.dock-tab[data-active="true"]');t&&(c.current.scrollLeft=Math.max(0,t.offsetLeft-c.current.offsetLeft))},[e,s,o.right,d.map(e=>e.title).join("|")]),"right"===e&&s&&1===d.length)return null;const h=n.jsxs("div",{className:"dock-tabs",ref:l,role:"right"===e?"tablist":"group","aria-label":s?r["browser"===s?"browser":"terminal"]:void 0,children:["right"===e&&s&&o.right[s]&&n.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":a.center,title:a.center,onClick:()=>o.move(o.right[s],"center"),children:n.jsx(P,{})}),n.jsx("div",{className:"dock-tab-items",ref:c,children:d.map(t=>{const s="center"===e?o.center===t.id:o.right[t.kind]===t.id,i=Pl[t.kind];return n.jsxs("div",{className:"document-tab dock-tab","data-active":s,"data-dock-id":t.id,draggable:!0,onDragStart:e=>{e.dataTransfer.setData(it,t.id),e.dataTransfer.effectAllowed="move"},children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":s,title:t.title,onClick:()=>"center"===e?o.setCenter(t.id):o.setRight(e=>({...e,[t.kind]:t.id})),children:[n.jsx(i,{}),n.jsx("span",{children:t.title})]}),s&&"center"===e&&n.jsx("button",{type:"button",className:"dock-move","aria-label":a.right,title:a.right,onClick:()=>o.move(t.id,"right"),children:n.jsx(L,{})}),n.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${r.close} ${t.title}`,title:r.close,onClick:()=>o.close(t.id),children:n.jsx(Be,{})})]},t.id)})}),"right"===e&&s&&n.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:wr(a.create,"newTab"),onClick:()=>o.add(s,r["browser"===s?"browser":"terminal"],i),children:n.jsx(je,{})})]});return u?k.createPortal(h,u):h}function ql({item:e,t}){const s=st(),r=Ll(t);return n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button","aria-label":r.center,title:r.center,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(it,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>s.move(e.id,"center"),children:n.jsx(P,{})}),n.jsx("button",{type:"button","aria-label":r.create,title:wr(r.create,"newTab"),onClick:()=>s.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:n.jsx(je,{})})]})}function Ol({location:e,kind:s}){const r=st(),i="center"===e?"center":`right-${s}`,o=t.useCallback(e=>r.register(i,e),[r.register,i]);return n.jsx("div",{ref:o,className:"dock-slot","data-dock-location":e,"data-dock-kind":s})}function _l(e,t){const n=rt();return n?{onDragOver:e=>{e.dataTransfer.types.includes(it)&&(e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("dock-drop-target"))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||e.currentTarget.classList.remove("dock-drop-target")},onDrop:s=>{s.currentTarget.classList.remove("dock-drop-target");const r=s.dataTransfer.getData(it),i=n.items.find(e=>e.id===r);i&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(r,e),t?.(i.kind))}}:{}}const $l=t.lazy(()=>R(()=>import("./BrowserControlPanel-CkKIuEsj.js"),__vite__mapDeps([11,1,2,9]))),zl=t.lazy(()=>R(()=>import("./SessionTerminalPanel-D_XqGjcx.js"),__vite__mapDeps([12,1,2]))),Hl=t.lazy(()=>R(()=>Promise.resolve().then(()=>Yl),void 0).then(e=>({default:e.DiffDrawer})));function Bl({item:e,...s}){const r=st(),[i]=t.useState(()=>({pairing:s.pairing,deviceName:s.deviceName})),o=t.useRef(s.client);s.daemonId===i.pairing?.daemonId&&(o.current=s.client);const a=_l(e.location),[c]=t.useState(()=>document.createElement("div")),l="right"===e.location,d=l&&1===r.items.filter(t=>"right"===t.location&&t.kind===e.kind).length,u=d?n.jsx(ql,{item:e,t:s.t}):void 0,h=(e.scopeKey??"default")===r.scopeKey&&(l?"diff"===e.kind?r.right.diff===e.id:s.rightVisible&&s.controlTab===e.kind&&r.right[e.kind]===e.id:r.center===e.id),f=r.hosts[l?`right-${e.kind}`:"center"]??r.hosts.parking,p=r.hosts.parking;t.useLayoutEffect(()=>{p&&c.parentElement!==p&&p.appendChild(c)},[c,p]),t.useLayoutEffect(()=>{c.className="dock-surface",c.dataset.dockId=e.id,c.dataset.location=e.location,c.dataset.kind=e.kind,c.hidden=!h;const t=l&&"diff"===e.kind,n=()=>{const e=f?.getBoundingClientRect();Object.assign(c.style,t?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${e?.left??0}px`,top:`${e?.top??0}px`,width:`${e?.width??0}px`,height:`${e?.height??0}px`})};n();const s=new ResizeObserver(n);return f&&s.observe(f),window.addEventListener("resize",n),document.addEventListener("transitionend",n,!0),window.addEventListener("scroll",n,!0),()=>{s.disconnect(),window.removeEventListener("resize",n),document.removeEventListener("transitionend",n,!0),window.removeEventListener("scroll",n,!0)}},[c,f,h,e.id,e.location,e.kind,l]),t.useLayoutEffect(()=>()=>c.remove(),[c]);const m=t.useCallback(t=>r.updateBrowserUrl(e.id,t),[r.updateBrowserUrl,e.id]);return k.createPortal(n.jsx("div",{className:"dock-surface-content",...a,children:n.jsx(t.Suspense,{fallback:n.jsx("p",{className:"control-panel-loading",children:s.t.loading}),children:"browser"===e.kind?n.jsx($l,{initialUrl:e.url,visible:h,onUrlChange:m,t:s.t,dockActions:u,onClose:d?()=>r.close(e.id):void 0,onTitleChange:t=>r.rename(e.id,t)}):"terminal"===e.kind?n.jsx(zl,{pairing:i.pairing,cwd:e.cwd??"",deviceName:i.deviceName,visible:h,autoOpen:!1!==e.autoOpenTerminal,onOpen:()=>r.activate(e.id),onCloseTab:()=>r.close(e.id),t:s.t,dockActions:u}):e.session&&o.current?n.jsx(Hl,{client:o.current,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:s.t,onClose:()=>r.close(e.id),onDock:()=>r.move(e.id,l?"center":"right"),dockLabel:Ll(s.t).center,presentation:l?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),c)}function Ul(e){const s=st();s.openRight.current=(t,n)=>{"browser"===t&&n&&e.onOpenBrowserLink?.(),"browser"!==t&&"terminal"!==t||e.onOpenRight?.(t)},s.closeRight.current=t=>{e.controlTab===t&&e.onCloseRight?.()},t.useEffect(()=>r().subscribeCommand?.(t=>{if(!t.startsWith("open-link:"))return;const n=t.slice(10);/^https?:\/\//i.test(n)&&s.openBrowser(n,e.t.browser)}),[s.openBrowser,e.t.browser]);const i=t.useCallback(e=>s.register("parking",e),[s.register]);return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"dock-parking",ref:i}),n.jsx("div",{className:"dock-overlay-slot",children:n.jsx(Ol,{location:"right",kind:"diff"})}),s.allItems.map(t=>n.jsx(Bl,{item:t,...e},t.id))]})}function Wl({patch:e,truncated:s,truncatedLabel:r,loadingLabel:i}){const o=t.useMemo(()=>function(e){let t=0,n=0;return e.split("\n").map(e=>{const s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return s?(t=Number(s[1]),n=Number(s[2]),{text:e,kind:"hunk",oldLine:"",newLine:"",sign:""}):e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("---")||e.startsWith("+++")||!t&&!n?{text:e,kind:"header",oldLine:"",newLine:"",sign:""}:e.startsWith("+")?{text:e.slice(1),kind:"add",oldLine:"",newLine:String(n++),sign:"+"}:e.startsWith("-")?{text:e.slice(1),kind:"del",oldLine:String(t++),newLine:"",sign:"−"}:e.startsWith(" ")?{text:e.slice(1),kind:"ctx",oldLine:String(t++),newLine:String(n++),sign:""}:{text:e,kind:"header",oldLine:"",newLine:"",sign:""}})}(e),[e]),[a,c]=t.useState(400),l=t.useRef(null);return t.useEffect(()=>{c(400)},[e]),t.useEffect(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&c(e=>e+400)},{root:e.closest(".diff-patch"),rootMargin:"200px"});return t.observe(e),()=>t.disconnect()},[a,o.length]),n.jsxs("div",{className:"diff-patch-view",children:[o.slice(0,a).map((e,t)=>n.jsxs("div",{className:`diff-line ${e.kind}`,children:[n.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.oldLine}),n.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.newLine}),n.jsx("span",{className:"diff-line-sign","aria-hidden":"true",children:e.sign}),n.jsx("span",{className:"diff-line-text",children:e.text||" "})]},t)),a<o.length&&n.jsx("div",{ref:l,className:"diff-more",role:"status",children:i}),s&&n.jsx("p",{className:"diff-empty",children:r})]})}const Kl=new WeakMap;function Vl(e,t,n){let s=Kl.get(e);s||Kl.set(e,s=new Map);const r=JSON.stringify([t.sessionId,t.cwd,n]);let i=s.get(r);return i||(s.size>=12&&s.delete(s.keys().next().value),s.set(r,i={updated:0,patches:new Map})),i}function Ql(e,t,n){return Vl(e,t,n)}function Gl(e,t,n){const s=Vl(e,t,n);return s.pending?s.pending:s.data&&Date.now()-s.updated<5e3?Promise.resolve(s.data):(s.pending=e.request({action:"session.gitDiff.list",id:e.makeId("gitDiffList"),...t,scope:n}).then(e=>(s.data=e,s.updated=Date.now(),s.patches.clear(),e)).finally(()=>{s.pending=void 0}),s.pending)}function Jl(e,t,n,s){const r=Vl(e,t,n),i=r.patches.get(s);if(i?.pending)return i.pending;if(i?.data&&Date.now()-r.updated<5e3)return Promise.resolve(i.data);r.patches.size>=12&&r.patches.delete(r.patches.keys().next().value);const o={};return r.patches.set(s,o),o.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:s}).then(e=>(o.data=e,e)).finally(()=>{o.pending=void 0}),o.pending}const Zl={loading:!1,files:null,error:null};function Xl({client:e,sessionId:s,cwd:r,sessionTitle:i,t:o,onClose:a,onDock:c,dockLabel:l,presentation:d="drawer",initialScope:u="unstaged",initialPath:h}){const f=t.useId(),p=t.useRef(null),[m,g]=t.useState(!1),v=t.useRef(void 0),y=t.useCallback(()=>{void 0===v.current&&("workspace"===d||window.matchMedia("(prefers-reduced-motion: reduce)").matches?a():(g(!0),v.current=window.setTimeout(a,180)))},[a,d]);t.useEffect(()=>()=>window.clearTimeout(v.current),[]);const b=j(y,p,"drawer"===d),w=Ql(e,{sessionId:s,cwd:r},u),[x,S]=t.useState(u),[k,I]=t.useState({unstaged:Zl,staged:Zl,[u]:{...Zl,files:w.data?.files??null}}),[C,R]=t.useState(h??w.data?.files[0]?.path??null),[E,M]=t.useState(w.patches.get(h??w.data?.files[0]?.path??"")?.data??null),[T,A]=t.useState(!1),[N,D]=t.useState(null),L=function(e){const n=t.useRef(void 0);return t.useEffect(()=>()=>n.current?.(),[]),{"data-dock-draggable":!!e,onPointerDown:t=>{if(!e||0!==t.button||t.target.closest("button"))return;n.current?.();const s=t.currentTarget,r=t.clientX,i=t.clientY,o=document.querySelector(".workspace-documents");if(!o)return;let a=!1;const c=(e,t)=>{const n=o.getBoundingClientRect();return e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom},l=e=>{Math.hypot(e.clientX-r,e.clientY-i)<6&&!a||(a=!0,document.body.classList.add("dock-dragging"),o.classList.toggle("dock-drop-target",c(e.clientX,e.clientY)))},d=()=>{document.body.classList.remove("dock-dragging"),o.classList.remove("dock-drop-target"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",d),s.hasPointerCapture(t.pointerId)&&s.releasePointerCapture(t.pointerId),n.current=void 0},u=t=>{const n=a&&c(t.clientX,t.clientY);d(),n&&e()};n.current=d,s.setPointerCapture(t.pointerId),window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",d),t.preventDefault()}}}("drawer"===d&&c?()=>c({scope:x,path:C}):void 0),F=k[x],q=t.useCallback(async t=>{I(e=>({...e,[t]:{loading:!0,files:e[t].files,error:null}}));try{const n=await Gl(e,{sessionId:s,cwd:r},t);I(e=>({...e,[t]:{loading:!1,files:n.files,error:null}}))}catch(n){I(e=>({...e,[t]:{loading:!1,files:null,error:n instanceof Error?n.message:String(n)}}))}},[e,s,r]);t.useEffect(()=>{q(x)},[x,q]),t.useEffect(()=>{const e=F.files;e&&(e.length?R(t=>e.some(e=>e.path===t)?t:e[0].path):R(null))},[F.files]),t.useEffect(()=>{if(!C)return M(null),void D(null);let t=!1;const n=Ql(e,{sessionId:s,cwd:r},x).patches.get(C)?.data;return M(e=>n??(e?.path===C?e:null)),A(!n&&E?.path!==C),D(null),Jl(e,{sessionId:s,cwd:r},x,C).then(e=>{t||(M(e),A(!1))}).catch(e=>{t||(D(e instanceof Error?e.message:String(e)),A(!1))}),()=>{t=!0}},[e,s,r,x,C,F.files]);const O=t.useMemo(()=>{const e=e=>e?e.reduce((e,t)=>({adds:e.adds+t.additions,dels:e.dels+t.deletions,count:e.count+1}),{adds:0,dels:0,count:0}):{adds:0,dels:0,count:0};return{unstaged:e(k.unstaged.files),staged:e(k.staged.files)}},[k]);return n.jsxs("div",{"aria-labelledby":f,"aria-modal":"drawer"===d||void 0,className:`diff-drawer ${"workspace"===d?"diff-workspace":""} ${m?"closing":""}`,ref:b,role:"drawer"===d?"dialog":"region",tabIndex:-1,children:["drawer"===d&&n.jsx("div",{className:"diff-drawer-backdrop",onClick:y,"aria-hidden":"true"}),n.jsxs("div",{className:"diff-drawer-panel",children:[n.jsxs("header",{className:"diff-drawer-header",...L,children:[c&&"drawer"===d&&n.jsx("button",{type:"button",className:"icon-button","aria-label":l,title:l,onClick:()=>c({scope:x,path:C}),children:n.jsx(P,{})}),n.jsxs("div",{children:[n.jsx("strong",{id:f,children:o.changes}),n.jsx("span",{children:i})]}),n.jsx("button",{"aria-label":o.closeChanges,className:"icon-button",onClick:y,ref:p,type:"button",title:o.closeChanges,children:n.jsx(Be,{"aria-hidden":"true"})})]}),n.jsx("div",{className:"diff-tabs",role:"tablist",children:["unstaged","staged"].map(e=>{const t=O[e],s=x===e;return n.jsxs("button",{type:"button",role:"tab","aria-selected":s,className:"diff-tab "+(s?"active":""),onClick:()=>{e!==x&&(R(null),M(null),D(null),S(e))},children:[n.jsx("span",{className:"diff-tab-label",children:"unstaged"===e?o.workingChanges:o.stagedChanges}),t.count>0?n.jsxs("span",{className:"diff-tab-meta",children:[n.jsxs("span",{className:"diff-add",children:["+",t.adds]}),n.jsxs("span",{className:"diff-del",children:["-",t.dels]})]}):null]},e)})}),n.jsxs("div",{className:"diff-body",children:[n.jsxs("aside",{className:"diff-files","aria-label":o.changedFiles,children:[F.loading&&!F.files?n.jsx("p",{className:"diff-empty",children:o.loading}):null,F.error?n.jsx("p",{className:"diff-empty diff-error",children:F.error}):null,F.files&&0===F.files.length?n.jsx("p",{className:"diff-empty",children:o.noChanges}):null,F.files?.map(e=>n.jsxs("button",{type:"button",className:`diff-file diff-file-${e.status} ${C===e.path?"active":""}`,onClick:()=>R(e.path),children:[n.jsx("span",{className:`diff-status diff-status-${e.status}`,children:e.status}),n.jsx("span",{className:"diff-file-path",title:e.path,children:e.path}),n.jsxs("span",{className:"diff-file-stats",children:[e.binary?n.jsx("span",{className:"diff-binary",children:"bin"}):null,!e.binary&&e.additions>0?n.jsxs("span",{className:"diff-add",children:["+",e.additions]}):null,!e.binary&&e.deletions>0?n.jsxs("span",{className:"diff-del",children:["-",e.deletions]}):null]})]},e.path))]}),n.jsx("section",{className:"diff-patch","aria-label":o.fileDiff,children:C?T?n.jsx("p",{className:"diff-empty",children:o.loadingPatch}):N?n.jsx("p",{className:"diff-empty diff-error",children:N}):E?.binary?n.jsx("p",{className:"diff-empty",children:o.binaryDiffUnavailable}):E?n.jsx(Wl,{patch:E.patch,truncated:E.truncated,truncatedLabel:o.patchTruncated,loadingLabel:o.loadingPatch},`${x}:${C}`):null:n.jsxs("div",{className:"diff-empty",children:[n.jsx(ee,{"aria-hidden":"true"}),n.jsx("p",{children:o.selectFileForDiff})]})})]})]})]})}const Yl=Object.freeze(Object.defineProperty({__proto__:null,DiffDrawer:Xl},Symbol.toStringTag,{value:"Module"})),ed=t.lazy(async()=>R(()=>import("./RemoteWorkspaceSettings-B9yBCaSU.js"),__vite__mapDeps([13,1,2,14,15])).then(e=>({default:e.RemoteWorkspaceSettings}))),td=t.lazy(async()=>R(()=>import("./FilesControlPanel-CwbB5lm2.js"),__vite__mapDeps([16,1,2,17,18])).then(e=>({default:e.FilesControlPanel}))),nd=t.lazy(async()=>R(()=>import("./LanguageSettingsPanel-BXx4BvyU.js"),__vite__mapDeps([19,1,2,20])).then(e=>({default:e.LanguageSettingsPanel}))),sd=t.lazy(async()=>R(()=>import("./ThemeSettingsPanel-BAHOGS0L.js"),__vite__mapDeps([21,1,2,20])).then(e=>({default:e.ThemeSettingsPanel}))),rd=t.lazy(async()=>R(()=>import("./NotificationSettingsPanel-D78c9Tv6.js"),__vite__mapDeps([22,1,2])).then(e=>({default:e.NotificationSettingsPanel})));function id({t:e}){return n.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[n.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),n.jsx("span",{children:e.loadingControls})]})}function od({client:e,id:s,activeSession:r,sessions:i,t:a,close:c}){const l=rt(),d=r?.sessionId,u=r?.cwd,h=r?.runtime.isResponding;t.useEffect(()=>{if(!e||!d)return;const t=window.setTimeout(()=>{"hidden"!==document.visibilityState&&async function(e,t){const n=await Gl(e,t,"unstaged");n.files[0]&&await Jl(e,t,"unstaged",n.files[0].path)}(e,{sessionId:d,cwd:u}).catch(()=>{})},350);return()=>window.clearTimeout(t)},[e,d,u,h]);const f=i.find(e=>e.sessionId===s);return f&&e?n.jsx(Xl,{client:e,sessionId:f.sessionId,cwd:f.cwd,sessionTitle:o(f),t:a,onClose:c,dockLabel:Ll(a).center,onDock:l?({scope:e,path:t})=>{l.add("diff",o(f),f.cwd,f,e,t),c()}:void 0},f.sessionId):null}let ad;const cd=R(()=>import("./NewSessionDialog-CuL1-FFv.js"),__vite__mapDeps([23,1,2,17,24])).then(e=>(ad=e.default,e));cd.catch(()=>{});const ld=t.lazy(()=>cd);function dd(e){const t=ad??ld;return n.jsx(t,{...e})}const ud="vibelet.web.hideDeviceAddresses";function hd({activeDaemonId:e,busy:i,fallbackName:o,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:f}){const{hidden:p,toggle:m}=function(){const[e,n]=t.useState(()=>{try{return"true"===s().getItem(ud)}catch{return!1}});return{hidden:e,toggle:()=>{const t=!e;n(t);try{s().setItem(ud,String(t))}catch{}}}}(),g=e=>p?function(e){return e.replace(/([^\s]+):(\d+)(?=\s|$)/g,(e,t,n)=>{const s=t.split(".");if(4===s.length&&s.every(e=>/^\d{1,3}$/.test(e)))return`${s[0]}.***.${s[3]}:${n}`;const r=Math.min(3,Math.floor((t.length-1)/2));return`${r>0?`${t.slice(0,r)}***${t.slice(-r)}`:"***"}:${n}`})}(e):e,v=p?l.showDeviceAddresses:l.hideDeviceAddresses,[y,b]=t.useState(!1),[w,x]=t.useState(null),[S,k]=t.useState(""),I=t.useRef(null),C=t.useRef(null),j=r().isLocalDaemon??(()=>!1),R=function(e,t,n){const s=e.find(e=>e.daemonId===t&&n(e.daemonId))??e.find(e=>n(e.daemonId));return e.filter(e=>!n(e.daemonId)||e===s)}(d,e,j),E=d.find(t=>t.daemonId===e),M=g(E?.label||o||e?.slice(0,10)||"Vibelet");return t.useEffect(()=>{y||x(null),w&&C.current?.select()},[y,w]),t.useEffect(()=>{if(!y)return;const e=e=>{e.target instanceof Node&&!I.current?.contains(e.target)&&b(!1)},t=e=>{"Escape"===e.key&&b(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[y]),n.jsxs("div",{className:"device-switcher",ref:I,children:[n.jsxs("button",{"aria-expanded":y,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:M,type:"button",children:[n.jsx("strong",{children:M}),n.jsx(_,{"aria-hidden":"true"})]}),n.jsxs("span",{className:`brand-connection ${a}`,children:[n.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),y?n.jsxs("div",{"aria-label":l.savedDevices,className:"device-switcher-menu",role:"menu",children:[n.jsxs("div",{className:"device-switcher-menu-header",children:[n.jsx("span",{children:l.savedDevices}),n.jsx("button",{type:"button",className:"device-rename-button","aria-label":v,title:v,onClick:m,children:p?n.jsx(Z,{"aria-hidden":"true"}):n.jsx(X,{"aria-hidden":"true"})})]}),R.map(t=>{const s=t.daemonId===e,o=(e=>{const t=r();if(!j(e.daemonId))return"desktop"===t.kind?t.connectionEndpoint?.(e.daemonId):e.webSocketUrl?function(e){try{const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return;const n=t.port||(["https:","wss:"].includes(t.protocol)?"443":"80");return`${t.hostname}:${n}`}catch{return}}(e.webSocketUrl):void 0})(t),a=g(t.label);return n.jsx("div",{className:"device-switcher-row"+(s?" is-active":""),children:w===t.daemonId?n.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),w&&S.trim()&&(h(w,S),x(null))},children:[n.jsx("input",{ref:C,"aria-label":l.rename,autoFocus:!0,onChange:e=>k(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),x(null))},value:S}),n.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!S.trim(),type:"submit",children:n.jsx(O,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>x(null),children:n.jsx(Be,{"aria-hidden":"true"})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"device-connect-button",disabled:i||s,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":s?"true":void 0,type:"button",children:[s?n.jsx(O,{"aria-hidden":"true"}):n.jsx(Ce,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsxs("strong",{className:"device-target-heading",children:[n.jsx("span",{children:a}),s?n.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?n.jsx("small",{children:g(t.displayName)}):null,j(t.daemonId)||!t.displayName?n.jsx("small",{children:j(t.daemonId)?l.currentDevice:g(t.daemonId)}):null,o?n.jsx("small",{className:"device-connection-endpoint",children:g(o)}):null]})]}),n.jsx("button",{"aria-label":`${l.rename} ${a}`,title:`${l.rename} ${a}`,className:"device-rename-button",onClick:()=>(e=>{x(e.daemonId),k(e.label)})(t),type:"button",children:n.jsx(ke,{"aria-hidden":"true"})}),f&&r().canEditConnection?.(t.daemonId)&&n.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{f(t),b(!1)},type:"button",children:n.jsx(Ne,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?n.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function fd({label:e,value:s,options:r,onChange:i}){const o=t.useId();return n.jsxs("div",{className:"filter-section",children:[n.jsx("span",{className:"filter-section-label",id:o,children:e}),n.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":o,children:r.map(e=>n.jsxs("label",{className:"filter-menu-row",children:[n.jsx("input",{type:"radio",name:o,value:e.value,checked:s===e.value,onChange:()=>i(e.value)}),n.jsx("span",{children:e.label}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":s===e.value})]},e.value))})]})}function pd({folder:e,initialValue:s,t:r,onClose:i,onSave:o}){const[a,c]=t.useState(s),l=t.useRef(null),d=j(i,l);return k.createPortal(n.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:d,role:"dialog",tabIndex:-1,children:[n.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:i}),n.jsxs("form",{className:"folder-tag-dialog",onSubmit:e=>{e.preventDefault(),o(a)},children:[n.jsxs("header",{children:[n.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:n.jsx(_e,{})}),n.jsxs("div",{children:[n.jsx("strong",{id:"folder-tag-dialog-title",children:r.editDirectoryTags}),n.jsx("span",{title:e,children:e})]}),n.jsx("button",{"aria-label":r.cancel,title:r.cancel,className:"mini-button",onClick:i,type:"button",children:n.jsx(Be,{"aria-hidden":"true"})})]}),n.jsxs("label",{className:"folder-tag-dialog-field",children:[n.jsx("span",{children:r.directoryTags}),n.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:r.directoryTagsPlaceholder,ref:l,rows:3,value:a,onChange:e=>c(e.target.value)})]}),n.jsx("p",{id:"folder-tag-dialog-help",children:r.directoryTagsDescription}),n.jsxs("footer",{children:[n.jsx("button",{className:"icon-text-button",onClick:i,type:"button",children:r.cancel}),n.jsx("button",{className:"primary-button",type:"submit",children:r.saveDirectoryTags})]})]})]}),document.body)}function md({folderToggle:e,search:s,connected:r,filtersOpen:i,filtersActive:o,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,f]=t.useState(Boolean(s)),p=h||s.length>0,m=t.useRef(null),g=t.useRef(null),v=t.useRef(!1),y=()=>{v.current=!0,l(),c(""),f(!1),g.current?.focus(),v.current=!1};return t.useEffect(()=>{const e=()=>{f(!0),requestAnimationFrame(()=>m.current?.focus())};return window.addEventListener("vibelet.session-search",e),()=>window.removeEventListener("vibelet.session-search",e)},[]),n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rail-list-heading",children:[n.jsx("div",{className:"rail-heading-folders",children:e}),n.jsxs("div",{className:"rail-heading-actions",children:[n.jsx("button",{ref:g,"aria-label":a.searchSessions,"aria-expanded":p,className:"rail-create-button",title:wr(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{f(!0),requestAnimationFrame(()=>m.current?.focus())},children:n.jsx(Te,{"aria-hidden":"true"})}),n.jsx(jl,{"aria-label":a.newSession,className:"rail-create-button",disabled:!r,onClick:u,title:a.newSession,type:"button",children:n.jsx(je,{"aria-hidden":"true"})}),n.jsx("button",{"aria-expanded":i,"aria-label":a.sessionFilters,className:"filter-toggle "+(i||o?"selected":""),onClick:d,title:a.sessionFilters,type:"button",children:n.jsx(re,{"aria-hidden":"true"})})]})]}),p&&n.jsxs("div",{className:"search-box rail-search-overlay",onBlur:e=>{v.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),f(Boolean(s)))},children:[n.jsx(Te,{"aria-hidden":"true"}),n.jsx("input",{ref:m,"aria-label":a.searchSessions,value:s,onChange:e=>c(e.target.value),placeholder:a.searchSessions,onKeyDown:e=>{"Enter"===e.key&&l(),"Escape"===e.key&&y()}}),n.jsx("button",{className:"search-close","aria-label":a.cancel,title:a.cancel,type:"button",onClick:y,children:n.jsx(Be,{"aria-hidden":"true"})})]})]})}function gd({menu:e,pending:t,t:s,onOpen:r,onDetails:i,onRename:o,onCopyResumeCommand:a,onResumeInTerminal:c,terminalBusy:l,onTogglePinned:d,onToggleArchived:u,onDelete:h}){return n.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:[n.jsxs("button",{type:"button",role:"menuitem",onClick:r,children:[n.jsx(M,{"aria-hidden":"true"}),s.open]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:o,children:[n.jsx(ke,{"aria-hidden":"true"}),s.rename]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[n.jsx(de,{"aria-hidden":"true"}),s.details]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[n.jsx(V,{"aria-hidden":"true"}),s.copyResumeCommand]}),c&&n.jsxs("button",{type:"button",role:"menuitem",disabled:t||l,title:l?s.resumeTerminalBusy:s.resumeInTerminal,onClick:c,children:[n.jsx($e,{"aria-hidden":"true"}),s.resumeInTerminal]}),n.jsx("span",{className:"context-menu-separator"}),n.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:d,children:[n.jsx(Ie,{"aria-hidden":"true"}),e.session.pinned?s.unpin:s.pin]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:u,children:[n.jsx(N,{"aria-hidden":"true"}),e.session.archived?s.unarchive:s.archive]}),n.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:h,children:[n.jsx(ze,{"aria-hidden":"true"}),s.delete]})]})}function vd({title:e,t:s,onClose:r,onSave:i}){const[o,a]=t.useState(e),[c,l]=t.useState(!1),[d,u]=t.useState(!1),h=t.useRef(null),f=t.useRef(!1),p=t.useRef(!1),m=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");r(),p.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};t.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(f.current)return;const t=o.trim();if(t&&t!==e){f.current=!0,u(!0),l(!1);try{if(await i(t))return void m()}catch{}f.current=!1,u(!1),l(!0),h.current?.focus()}else m()};return n.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},children:[n.jsx("input",{ref:h,"aria-label":s.rename,value:o,readOnly:d,onChange:e=>a(e.target.value),onBlur:()=>{g()},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||("Enter"===e.key&&(p.current=!0),"Escape"!==e.key||d||(e.preventDefault(),f.current=!0,p.current=!0,m()))}}),c&&n.jsx("small",{role:"alert",children:s.renameFailed})]})}function yd({session:e,renamingRowId:s,onRename:r,onCloseRename:i,active:a,selected:c=!1,responding:l,pending:d=!1,attentionReason:u,tagLabels:h,showFolder:f=!0,t:p,onSelect:m,onContextMenu:g,onToggleArchived:v,onTogglePinned:y}){const b=e.creationError,w=t.useId(),x=s===w,S=o(e),I=Dt(e.lastActivityAt,Date.now(),p),C=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",j=e.branchUrl||(e.branch&&e.pullRequest?.url.match(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/)?e.pullRequest.url.replace(/\/pull\/\d+$/,`/tree/${encodeURIComponent(e.branch)}`):void 0),[R,E]=t.useState(!1),M=t.useRef(null),T=t.useRef(null),A=t.useRef({x:0,y:0}),D=t.useRef(null),P=()=>{const e=T.current;if(!e)return;const{x:t,y:n}=A.current,s=e.getBoundingClientRect(),r=n+18+s.height<=window.innerHeight-8?n+18:n-s.height-12;e.style.left=`${Math.max(8,Math.min(t+14,window.innerWidth-s.width-8))}px`,e.style.top=`${Math.max(8,Math.min(r,window.innerHeight-s.height-8))}px`,e.style.visibility="visible"};t.useLayoutEffect(()=>{R&&P()},[R,S]);const L=()=>{null!==M.current&&window.clearTimeout(M.current),M.current=null,null!==D.current&&window.cancelAnimationFrame(D.current),D.current=null,E(!1)};return t.useEffect(()=>()=>{null!==M.current&&window.clearTimeout(M.current),null!==D.current&&window.cancelAnimationFrame(D.current)},[e.sessionId]),t.useEffect(()=>{if(!R)return;const e=()=>E(!1);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[R]),n.jsxs("div",{className:"session-item","data-row-id":w,onContextMenu:e=>{L(),g?.(e)},"data-renaming":x||void 0,"data-active":a||void 0,"data-multi-selected":c||void 0,"data-statuses":Number(Boolean(e.pinned))+Number(Boolean(e.archived)),onMouseEnter:e=>{A.current={x:e.clientX,y:e.clientY},x||(e=>{null!==M.current&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null,e.isConnected&&e.matches(":hover")&&E(!0)},2e3)})(e.currentTarget)},onMouseMove:e=>{A.current={x:e.clientX,y:e.clientY},R&&null===D.current&&(D.current=window.requestAnimationFrame(()=>{D.current=null,P()}))},onMouseLeave:L,onFocusCapture:e=>{if(!x&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==M.current&&window.clearTimeout(M.current),M.current=null;const t=e.currentTarget.getBoundingClientRect();A.current={x:t.left+t.width/2,y:t.bottom},E(!0)}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||L()},children:[n.jsxs("button",{className:`session-row ${a?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":w,disabled:x,"aria-current":a?"true":void 0,"aria-pressed":c,onClick:m,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[n.jsxs("span",{className:"session-row-head",children:[n.jsx("strong",{children:S}),n.jsx("span",{className:"session-row-metadata",children:n.jsx("span",{className:"session-row-time",title:I,children:I})}),l?n.jsx("span",{className:"session-running-indicator",role:"img","aria-label":p.agentResponding,title:p.agentResponding}):n.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),b&&n.jsxs("span",{className:"session-attention-reason",title:b,children:[p.sessionCreateFailed,": ",b]}),u&&n.jsx("span",{className:"session-attention-reason",children:u}),h?.length?n.jsx("span",{className:"directory-tag-row",title:p.directoryTags,children:h.map(e=>n.jsx("em",{children:e},e))}):null,n.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),x&&r&&i&&n.jsx(vd,{title:S,t:p,onClose:i,onSave:t=>r(e,t)}),n.jsxs("div",{className:"session-quick-actions",children:[n.jsx("button",{"aria-label":e.pinned?p.unpin:p.pin,className:e.pinned?"is-pinned":void 0,disabled:d,onClick:y,title:e.pinned?p.unpin:p.pin,type:"button",children:n.jsx(Ie,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":e.archived?p.unarchive:p.archive,className:e.archived?"is-archived":void 0,disabled:d,onClick:v,title:e.archived?p.unarchive:p.archive,type:"button",children:n.jsx(N,{"aria-hidden":"true"})})]}),n.jsxs("div",{className:"session-git-links",children:[f&&n.jsx("span",{className:"session-git-folder",title:e.cwd,children:C}),e.branch&&(j&&a?n.jsx("a",{className:"session-branch-link",href:j,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):n.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&(a?n.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]}):n.jsxs("span",{className:"session-pr-link",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})),e.pinned?n.jsx("span",{className:"session-row-status",children:p.pinned}):null,e.archived?n.jsx("span",{className:"session-row-status",children:p.archived}):null,n.jsx("span",{className:"session-row-agent",children:"codex"===e.agent?"Codex":"Claude"})]}),R&&k.createPortal(n.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:T,style:{left:0,top:0,visibility:"hidden"},children:S}),document.body)]})}function bd(e){const s=t.useRef(e);t.useLayoutEffect(()=>{s.current=e});const r=t.useMemo(()=>({onRenameSession:(e,t)=>s.current.onRenameSession?.(e,t)??Promise.resolve(!1),onCloseRename:()=>s.current.onCloseRename?.(),onEditFolderTags:e=>s.current.onEditFolderTags(e),onOpenCreateMenu:(e,t)=>s.current.onOpenCreateMenu(e,t),onOpenSessionMenu:(e,t)=>s.current.onOpenSessionMenu(e,t),onSelectSession:e=>s.current.onSelectSession(e),onToggleSessionArchived:e=>s.current.onToggleSessionArchived(e),onToggleSessionPinned:e=>s.current.onToggleSessionPinned(e),onToggleFolder:e=>s.current.onToggleFolder(e)}),[]);return n.jsx(wd,{...e,...r})}const wd=t.memo(function({activeSessionId:e,renamingRowId:s,onRenameSession:r,onCloseRename:i,collapsedFolders:o,folderCounts:a,getFolderTags:c,groupFolders:l,groupedSessions:d,phase:u,attentionReasons:h,pendingSessionIds:f,respondingSessionIds:p,t:m,visibleSessions:g,onEditFolderTags:v,onOpenCreateMenu:y,onOpenSessionMenu:b,onSelectSession:w,onToggleSessionArchived:x,onToggleSessionPinned:S,onToggleFolder:k}){const I=t.useId(),[C,j]=t.useState(()=>new Set),R=t.useRef(null),E=t.useMemo(()=>{const e=l?d.flatMap(e=>o[e.folder]?[]:e.sessions):g;return[...new Set(e.map(e=>e.sessionId))]},[o,l,d,g]);t.useEffect(()=>{const e=new Set(E);j(t=>[...t].every(t=>e.has(t))?t:new Set([...t].filter(t=>e.has(t)))),R.current&&!e.has(R.current)&&(R.current=null)},[E]),t.useEffect(()=>{0===C.size&&(R.current=e)},[e,C]);const M=(t,n)=>{if(n.shiftKey){const s=R.current??e??t,r=E.indexOf(s),i=E.indexOf(t),o=E.slice(Math.min(r<0?i:r,i),Math.max(r,i)+1);return j(e=>{const t=n.metaKey||n.ctrlKey?new Set(e):new Set;for(const n of o)t.add(n);return t}),void(R.current=s)}R.current=t,n.metaKey||n.ctrlKey?j(n=>{const s=n.size?new Set(n):new Set(e?[e]:[]);return s.has(t)?s.delete(t):s.add(t),s}):(j(new Set),w(t))};return l?n.jsxs(n.Fragment,{children:[d.map(t=>{const l=!!o[t.folder],d=`${I}-${encodeURIComponent(t.folder)}`,g="folder"===t.kind?a[t.folder]??t.sessions.length:t.sessions.length,w="attention"===t.kind?m.needsAttentionSessionsGroup:"running"===t.kind?m.runningSessionsGroup:"pinned"===t.kind?m.pinnedSessionsGroup:t.folder;return n.jsxs("div",{className:"folder-group "+("folder"!==t.kind?"virtual-session-group":""),"data-group-kind":t.kind,"data-contains-active":t.sessions.some(t=>t.sessionId===e)||void 0,children:[n.jsxs("div",{className:"folder-heading",children:[n.jsxs("div",{className:"folder-header",children:[n.jsxs("button",{"aria-expanded":!l,"aria-controls":d,title:w,onClick:()=>k(t.folder),type:"button",children:[n.jsx($,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===t.kind?n.jsx(de,{"aria-hidden":"true"}):"running"===t.kind?n.jsx(A,{"aria-hidden":"true"}):"pinned"===t.kind?n.jsx(Ie,{"aria-hidden":"true"}):l?n.jsx(se,{"aria-hidden":"true"}):n.jsx(te,{"aria-hidden":"true"}),n.jsx("span",{children:"folder"===t.kind?t.folder.split(/[\\/]/).filter(Boolean).at(-1)||t.folder:w})]}),"folder"===t.kind?n.jsxs(n.Fragment,{children:[n.jsx("button",{"aria-label":c(t.folder).length?m.editDirectoryTags:m.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>v(t.folder),title:c(t.folder).length?m.editDirectoryTags:m.addDirectoryTags,type:"button",children:n.jsx(_e,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":m.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>y(e,t.folder),title:m.newSession,type:"button",children:n.jsx(je,{"aria-hidden":"true"})})]}):null,n.jsx("small",{className:"folder-session-count",title:`${g} ${m.sessions}`,children:g})]}),"folder"===t.kind&&c(t.folder).length?n.jsx("div",{className:"folder-tag-row",children:c(t.folder).map(e=>n.jsx("span",{children:e},e))}):null]}),n.jsx("div",{className:"folder-session-list",id:d,hidden:l,children:l?null:t.sessions.map(o=>n.jsx(yd,{renamingRowId:s,onRename:r,onCloseRename:i,active:o.sessionId===e,selected:C.has(o.sessionId),responding:p.has(o.sessionId),attentionReason:h?.[o.sessionId],pending:f?.has(o.sessionId),session:o,showFolder:"folder"!==t.kind,tagLabels:c(o.cwd),t:m,onContextMenu:e=>b(e,o),onSelect:e=>M(o.sessionId,e),onToggleArchived:()=>x(o),onTogglePinned:()=>S(o)},o.sessionId))})]},t.folder)}),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:m.noSessionsMatch})}):null]}):n.jsxs(n.Fragment,{children:[g.map(t=>n.jsx(yd,{renamingRowId:s,onRename:r,onCloseRename:i,active:t.sessionId===e,selected:C.has(t.sessionId),responding:p.has(t.sessionId),attentionReason:h?.[t.sessionId],pending:f?.has(t.sessionId),session:t,tagLabels:c(t.cwd),t:m,onContextMenu:e=>b(e,t),onSelect:e=>M(t.sessionId,e),onToggleArchived:()=>x(t),onTogglePinned:()=>S(t)},t.sessionId)),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:m.noSessionsMatch})}):null]})});function xd({agentFilter:e,t,onAgentFilterChange:s}){return n.jsx(fd,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:s})}function Sd({groupFolders:e,hideArchived:t,separatePinnedGroup:s,showNeedsAttentionGroup:r,showRunningGroup:i,t:o,onToggleGroupFolders:a,onToggleHideArchived:c,onToggleNeedsAttentionGroup:l,onToggleRunningGroup:d,onToggleSeparatePinnedGroup:u}){const h=[[o.showNeedsAttentionGroup,r,l],[o.showRunningGroup,i,d],[o.separatePinnedGroup,s,u]];return n.jsxs("div",{className:"filter-section",children:[n.jsx("span",{className:"filter-section-label",children:o.filterViewOptions}),n.jsxs("div",{className:"filter-view-list",children:[n.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:a,type:"button",children:[n.jsx("span",{children:o.groupByFolder}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),h.map(([t,s,r])=>n.jsxs("button",{"aria-pressed":e&&s,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:r,type:"button",children:[n.jsx("span",{children:t}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&s})]},t)),n.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:c,type:"button",children:[n.jsx("span",{children:o.hideArchived}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function kd({connectionIndicators:e,hasDaemonUpdate:s=!1,activeSessionId:i,busy:o,collapsedFolders:a,allFoldersCollapsed:c,currentCwd:l,activeDaemonId:d,displayName:u,savedTargets:h,directoryTags:f,folderCounts:p,groupFolders:m,sessionSort:g,onSessionSortChange:v,groupedSessions:y,hideArchived:b,separatePinnedGroup:w,showNeedsAttentionGroup:x,showRunningGroup:S,inventoryVersion:I,nextCursor:C,phase:j,attentionReasons:R,pendingSessionIds:E,respondingSessionIds:M,search:T,sessionAgentFilter:A,sessionsCount:N,sinceFilter:D,statusText:P,t:L,visibleSessions:F,onLoadMore:q,onCopyResumeCommand:O,onResumeInTerminal:_,onConnectTarget:$,onRequestNewSession:z,onDeleteSession:H,onRenameSession:B,onEditFolderTags:U,onOpenSessionDetails:W,onResetFilters:K,onRenameTarget:V,onEditConnection:Q,onSearchChange:G,onSearchCommit:J,onSelectSession:Z,onToggleSessionArchived:X,onToggleSessionPinned:Y,onSessionAgentFilterChange:ee,onSinceFilterChange:te,onToggleFolder:ne,onToggleAllFolders:se,onToggleGroupFolders:re,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:oe,onToggleRunningGroup:ae,onToggleSeparatePinnedGroup:ce}){const le=function({activeSessionId:e,activeDaemonId:n,groupFolders:s,groupedSessions:i,collapsedFolders:o,onToggleFolder:a}){const c=t.useRef(null),l=t.useRef({key:"",revealed:!1});return t.useLayoutEffect(()=>{if("desktop"!==r().kind)return;const t=JSON.stringify([n,e]);if(l.current.key!==t&&(l.current={key:t,revealed:!1}),!e||l.current.revealed)return;if(s){const t=i.filter(t=>t.sessions.some(t=>t.sessionId===e)),n=t.find(e=>!o[e.folder])??t[0];if(n&&o[n.folder])return void(l.current.opening!==n.folder&&(l.current.opening=n.folder,a(n.folder)))}const d=c.current?.querySelector('.session-row[aria-current="true"]');if(!d)return;const u=requestAnimationFrame(()=>{d.isConnected&&l.current.key===t&&(d.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"}),l.current.revealed=!0)});return()=>cancelAnimationFrame(u)},[n,e,o,s,i,a]),c}({activeSessionId:i,activeDaemonId:d,groupFolders:m,groupedSessions:y,collapsedFolders:a,onToggleFolder:ne}),[de,ue]=t.useState(null),[he,fe]=t.useState(!1),[ge,ve]=t.useState(null);t.useEffect(()=>{if(!ge)return;const e=window.setTimeout(()=>ve(null),2400);return()=>window.clearTimeout(e)},[ge]);const[ye,we]=t.useState(null),[xe,Se]=t.useState(null),ke=t.useRef(null),Ie=t.useRef(null),[Ce,je]=t.useState(null),Re="updated"!==g||"all"!==A||"30d"!==D||!m||m&&(x||S||w)||b,Ee=function(e,n,s=!1){const r=t.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),i=t.useRef(null),o=t.useRef(null),a=t.useRef(n),[c,l]=t.useState(null),d=Boolean(e?.lastActivityAt&&e.sessionId),u=d?`${e?.lastActivityAt}:${e?.sessionId}`:null;return t.useEffect(()=>{a.current=n},[n]),t.useEffect(()=>{const e=i.current;if(!e||!r||!u)return o.current=null,void l(null);const t=e.closest(".session-list");if(!(t instanceof HTMLElement))return;let n,c=!0;l(null);const d=()=>{o.current!==u&&(o.current=u,l(u),a.current(r).catch(()=>{c&&(n=window.setTimeout(()=>{c&&(o.current=null,s?d():(h?.unobserve(e),h?.observe(e)))},1500))}).finally(()=>{c&&l(e=>e===u?null:e)}))},h=s?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&d()},{root:t,rootMargin:"0px 0px 240px 0px",threshold:.01});return s?d():h?.observe(e),()=>{c=!1,o.current=null,void 0!==n&&window.clearTimeout(n),h?.disconnect()}},[u,r,s]),{canLoadMore:d,loading:d&&c===u,sentinelRef:i}}(C,q,"updated"!==g||!b),Me=!!xe&&Boolean(E?.has(xe.session.sessionId)),Te=t.useCallback(e=>f[function(e){return"string"==typeof e&&e.trim().length>0?e:void 0}(e)??"/"]??[],[f]),Ae=`${P} · ${"connected"===j?`${F.length}/${N} sessions · v${I??"-"}`:L.sameOriginAccess}`,Ne=r().toolbarTarget?.("left");t.useLayoutEffect(()=>{if(!he)return;const e=()=>{const e=ke.current?.getBoundingClientRect();if(!e)return;const t=Math.min(820,window.innerWidth-24);je({top:e.bottom+8,left:Math.max(12,Math.min(e.left,window.innerWidth-t-12))})};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[he]),t.useEffect(()=>{if(!he&&!xe)return;const e=e=>{const t=e.target;t instanceof Node&&(ke.current?.contains(t)||Ie.current?.contains(t))||(fe(!1),Se(null))},t=e=>{"Escape"===e.key&&(fe(!1),Se(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[xe,he]);const Pe=(e,t)=>{Se(null),fe(!1),z(t)},Le=()=>Se(null),Fe=e=>{if(!xe)return;const{session:t}=xe;Le(),e(t)},qe=n.jsxs("div",{className:"brand-block",title:Ae,children:[n.jsx("div",{className:"brand-mark","aria-hidden":"true",children:n.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-CVsV06Wq.webp",width:"40"})}),n.jsx(hd,{activeDaemonId:d,busy:o,fallbackName:u,phase:j,statusText:P,t:L,targets:h,onConnect:$,onRename:V,onEditConnection:Q})]});return n.jsxs("aside",{className:"session-rail","aria-label":L.sessions,children:[Ne?k.createPortal(qe,Ne):qe,n.jsxs("div",{className:"search-filter-wrap",ref:ke,children:[n.jsx(md,{folderToggle:m&&y.length>0&&n.jsx("button",{"aria-label":c?L.expandAllSessions:L.collapseAllSessions,"aria-pressed":c,className:"session-folders-toggle",onClick:se,title:c?L.expandAllSessions:L.collapseAllSessions,type:"button",children:c?n.jsx(me,{"aria-hidden":"true"}):n.jsx(be,{"aria-hidden":"true"})}),search:T,connected:"connected"===j,filtersOpen:he,filtersActive:Re,t:L,onSearchChange:G,onSearchCommit:J,onToggleFilters:()=>fe(e=>!e),onCreate:Pe}),he&&Ce?k.createPortal(n.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":L.sessionFilters,ref:Ie,style:{top:Ce.top,left:Ce.left},children:[n.jsx(fd,{label:L.sessionSortLabel,value:g,options:[{value:"updated",label:L.sessionSortUpdated},{value:"created",label:L.sessionSortCreated},{value:"title",label:L.sessionSortTitle},{value:"folder",label:L.sessionSortFolder}],onChange:v}),n.jsx(xd,{agentFilter:A,t:L,onAgentFilterChange:ee}),n.jsx(fd,{label:L.searchTimeRangeLabel,value:D,options:[{value:"all",label:L.searchTimeRangeAllTime},{value:"7d",label:L.searchTimeRangeLast7Days},{value:"30d",label:L.searchTimeRangeLast30Days},{value:"90d",label:L.searchTimeRangeLast90Days}],onChange:te}),n.jsx(Sd,{groupFolders:m,hideArchived:b,separatePinnedGroup:w,showNeedsAttentionGroup:x,showRunningGroup:S,t:L,onToggleGroupFolders:re,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:oe,onToggleRunningGroup:ae,onToggleSeparatePinnedGroup:ce}),Re?n.jsx("button",{className:"filter-reset-button",onClick:K,type:"button",children:L.resetFilters}):null]}),document.body):null]}),n.jsxs("div",{className:"session-list",ref:le,children:[n.jsx(bd,{activeSessionId:i,renamingRowId:de,onRenameSession:B,onCloseRename:()=>ue(null),collapsedFolders:a,folderCounts:p,getFolderTags:Te,groupFolders:m,groupedSessions:y,phase:j,attentionReasons:R,pendingSessionIds:E,respondingSessionIds:M,t:L,visibleSessions:F,onEditFolderTags:e=>{fe(!1),Se(null),we({folder:e,value:Te(e).join(", ")})},onOpenCreateMenu:Pe,onOpenSessionMenu:(e,t)=>{e.preventDefault(),Se({session:t,rowId:e.currentTarget.dataset.rowId??"",x:Math.min(e.clientX,window.innerWidth-224-10),y:Math.min(e.clientY,window.innerHeight-342-10)})},onSelectSession:Z,onToggleSessionArchived:X,onToggleSessionPinned:Y,onToggleFolder:ne},d??"unconnected"),Ee.canLoadMore?n.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(Ee.loading?"loading":""),ref:Ee.sentinelRef,role:"status",children:Ee.loading?n.jsxs(n.Fragment,{children:[n.jsx(pe,{className:"spin","aria-hidden":"true"}),n.jsx("span",{children:L.loadingMore})]}):null}):null]}),n.jsxs("div",{className:"session-rail-footer",children:[n.jsx("div",{className:"rail-footer-indicators",children:e}),r().openSettings&&n.jsxs("button",{"aria-label":L.settings,className:"icon-button rail-settings-button",onClick:()=>r().openSettings?.(s?"daemon":void 0),title:L.settings,type:"button",children:[n.jsx(De,{"aria-hidden":"true"}),r().settingsBadge?.(s)]})]}),ye?n.jsx(pd,{folder:ye.folder,initialValue:ye.value,t:L,onClose:()=>we(null),onSave:e=>{ye&&(U(ye.folder,e),we(null))}}):null,xe?n.jsx(gd,{menu:xe,pending:Me,t:L,onOpen:()=>Fe(e=>Z(e.sessionId)),onRename:()=>{ue(xe.rowId),Le()},onDetails:()=>Fe(W),onCopyResumeCommand:()=>Fe(e=>{Promise.resolve(O(e)).then(()=>ve({message:L.commandCopied,tone:"success"})).catch(()=>ve({message:L.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:_&&d&&r().resumeInTerminal&&r().isLocalDaemon?.(d)?()=>Fe(_):void 0,terminalBusy:M.has(xe.session.sessionId),onTogglePinned:()=>Fe(Y),onToggleArchived:()=>Fe(X),onDelete:()=>Fe(H)}):null,n.jsx(Oi,{feedback:ge})]})}function Id({collapsed:e,children:t,onExpand:s,onResize:i,t:o}){const a=r().toolbarTarget?.("left"),c=n.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:s,title:wr(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:n.jsx(we,{"aria-hidden":"true"})});return n.jsxs(n.Fragment,{children:[a?k.createPortal(c,a):c,n.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),n.jsx("button",{"aria-label":o.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:i,title:o.resizeSessionSidebar,type:"button",children:n.jsx("span",{})})]})}function Cd(e){const n=st(),s=n.items.find(e=>e.id===n.right.browser&&"right"===e.location),i=s?.currentUrl??s?.url,o=t.useRef(null);return t.useEffect(()=>{o.current!==n.scopeKey&&(o.current=n.scopeKey,"desktop"!==r().kind||"browser"!==e.controlTab||i&&"about:blank"!==i||e.setRightSidebarCollapsed(!0))},[n.scopeKey,i,e.controlTab,e.setRightSidebarCollapsed]),()=>{e.rightSidebarCollapsed&&("session"===e.controlTab&&0===e.pendingActionsCount||"desktop"===r().kind&&"browser"===e.controlTab&&(!i||"about:blank"===i))&&e.setControlTab("files"),e.setRightSidebarCollapsed(e=>!e)}}const jd={en:{reset:"Reset all session models to CLI defaults",resetHint:"Current connection · Claude and Codex · Keep fast mode unchanged",settings:"Open settings",left:"Toggle left sidebar",right:"Toggle right sidebar",files:"Open file tree",terminal:"Open terminal",browser:"Open browser",diff:"View current session Git changes",working:"Resetting models…",done:"Updated {ok} · Failed {failed}",error:"Reset interrupted. Some sessions may have been updated. Check the connection and retry.",offline:"Connect to a device first",commandHint:"↑ ↓ Select · Enter Run · Esc Close"},"zh-CN":{reset:"将所有会话模型重置为 CLI 默认模型",resetHint:"当前连接 · Claude 和 Codex · 保留快速模式设置",settings:"打开设置",left:"显示 / 隐藏左侧栏",right:"显示 / 隐藏右侧栏",files:"打开文件树",terminal:"打开终端",browser:"打开浏览器",diff:"查看当前会话 Git 变更",working:"正在重置模型…",done:"已更新 {ok} 个 · 失败 {failed} 个",error:"重置中断,部分会话可能已更新。请检查连接后重试。",offline:"请先连接设备",commandHint:"↑ ↓ 选择 · Enter 执行 · Esc 关闭"},"zh-TW":{reset:"將所有會話模型重置為 CLI 預設模型",resetHint:"目前連線 · Claude 和 Codex · 保留快速模式設定",settings:"開啟設定",left:"顯示 / 隱藏左側欄",right:"顯示 / 隱藏右側欄",files:"開啟檔案樹",terminal:"開啟終端機",browser:"開啟瀏覽器",diff:"檢視目前會話 Git 變更",working:"正在重置模型…",done:"已更新 {ok} 個 · 失敗 {failed} 個",error:"重置中斷,部分會話可能已更新。請檢查連線後重試。",offline:"請先連線裝置",commandHint:"↑ ↓ 選擇 · Enter 執行 · Esc 關閉"}};function Rd({workspace:e,onSelect:s}){const[i,o]=t.useState(!1),l=function(e,n){const s=jd["zh"===n?"zh-CN":n]??jd.en,i=Cd(e),o=t.useRef(!1),[a,c]=t.useState(!1),[l,d]=t.useState(null),u="connected"===e.phase;return{commands:[{id:"resetModels",title:s.reset,meta:u?s.resetHint:s.offline,keywords:"reset models cli default auto 重置 模型 默认 預設",disabled:!u||a,keepOpen:!0,select:()=>{(async()=>{if(o.current||!u)return;o.current=!0,c(!0);const t=e.pairing?.daemonId,n=e=>d({scope:t,text:e}),r=e=>s.done.replace("{ok}",String(e.updated)).replace("{failed}",String(e.failed));n(s.working);try{const t=await e.applyToAllSessions({models:{claude:"",codex:""}},e=>n(`${s.working} ${r(e)}`));n(r(t))}catch{n(s.error)}finally{o.current=!1,c(!1)}})()}},{id:"settings",title:s.settings,meta:"",keywords:"settings preferences 设置 設定",select:()=>r().openSettings?.()},{id:"left",title:s.left,meta:"",keywords:"left sidebar 左侧栏 左側欄",select:()=>e.setLeftSidebarCollapsed(e=>!e)},{id:"right",title:s.right,meta:"",keywords:"right sidebar 右侧栏 右側欄",select:i},...["files","terminal","browser"].map(t=>({id:t,title:s[t],meta:"",keywords:t,select:()=>e.setControlTabAndOpen(t)})),{id:"diff",title:s.diff,meta:"",keywords:"git diff changes 差异 差異",disabled:!e.activeSession,select:()=>{e.activeSession&&e.setDiffSessionId(e.activeSession.sessionId)}}].map(e=>({...e,disabled:e.disabled||a})),busy:a,status:l?.scope===e.pairing?.daemonId?l?.text:void 0,hint:s.commandHint}}(e,a(c().language));return t.useEffect(()=>{const e=()=>o(!0);return window.addEventListener("vibelet.quick-search",e),()=>window.removeEventListener("vibelet.quick-search",e)},[]),t.useEffect(()=>o(!1),[e.pairing?.daemonId]),i?n.jsx(Ed,{workspace:e,onSelect:s,onClose:()=>o(!1),commandState:l}):null}function Ed({workspace:e,onSelect:s,onClose:r,commandState:i}){const l=st(),[d,u]=t.useState(""),[h,f]=t.useState(0),p=d.startsWith(">"),[m,g]=t.useState([]),[v,y]=t.useState(!0),[b,w]=t.useState(!1),x=t.useRef(null),S=j(r,x),I=a(c().language),C="en"===I?{title:"Quick switch",placeholder:"Search tab name, branch, PR title or #number, or > commands…",empty:"No matches",loading:"Loading sessions…",error:"Could not load all sessions. Close and reopen to retry.",hint:"↑ ↓ Select · Enter Open · Esc Close"}:"zh-TW"===I?{title:"快速定位",placeholder:"搜尋標籤名稱、分支、PR 標題或 #編號,或輸入 > 執行命令…",empty:"沒有符合的結果",loading:"正在載入會話…",error:"部分會話載入失敗,請關閉後重新開啟重試。",hint:"↑ ↓ 選擇 · Enter 開啟 · Esc 關閉"}:{title:"快速定位",placeholder:"搜索标签名称、分支、PR 标题或 #编号,或输入 > 执行命令…",empty:"没有匹配的结果",loading:"正在加载会话…",error:"部分会话加载失败,请关闭后重新打开重试。",hint:"↑ ↓ 选择 · Enter 打开 · Esc 关闭"};t.useEffect(()=>{let t=!1;const n=e.clientRef.current;return(async()=>{if(!n?.isConnected)return y(!1),void w(!0);let s;do{const r=await n.request({action:"sessions.list",id:n.makeId("quick_search"),limit:100,cursor:s,hideArchived:!0});if(t||e.clientRef.current!==n)return;g(e=>[...e,...r.sessions]),s=r.nextCursor}while(s);y(!1)})().catch(()=>{t||(w(!0),y(!1))}),()=>{t=!0}},[e.clientRef]);const R=new Map(m.map(e=>[e.sessionId,e]));for(const t of e.displaySessions)R.set(t.sessionId,{...R.get(t.sessionId),...t});const E=p?function(e,t){const n=t.trim().toLocaleLowerCase().split(/\s+/),s=e=>n.filter(t=>e.title.toLocaleLowerCase().includes(t)).length;return e.filter(e=>n.every(t=>`${e.title} ${e.meta} ${e.keywords}`.toLocaleLowerCase().includes(t))).sort((e,t)=>s(t)-s(e))}(i.commands,d.slice(1)):[...l.items.filter(e=>!e.emptyPlaceholder&&e.title.toLocaleLowerCase().includes(d.trim().toLocaleLowerCase())).map(t=>({id:`tab-${t.id}`,title:t.title,meta:t.currentUrl||t.cwd||t.kind,select:()=>{"center"===t.location||"diff"===t.kind?l.setCenter(t.id):(l.setRight(e=>({...e,[t.kind]:t.id})),e.setControlTabAndOpen(t.kind))}})),...[...R.values()].filter(e=>!e.archived&&function(e,t){const n=e.pullRequest,s=[o(e),e.title,...e.titleAliases??[],e.branch,e.cwd,e.agent,n?.title,n?.url,n&&`#${n.number}`].filter(Boolean).join(" ").toLocaleLowerCase();return t.trim().toLocaleLowerCase().split(/\s+/).every(e=>s.includes(e))}(e,d)).map(t=>({id:t.sessionId,title:o(t),meta:[t.branch,t.pullRequest&&`#${t.pullRequest.number} ${t.pullRequest.title}`,t.cwd].filter(Boolean).join(" · "),select:()=>{e.setSessions(e=>e.some(e=>e.sessionId===t.sessionId)?e:[...e,t]),s(t.sessionId)}}))],M=Math.min(h,Math.max(0,E.length-1));t.useEffect(()=>{S.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:"nearest"})},[M,d]);const T=e=>{const t=E[e];t&&!t.disabled&&(t.keepOpen||r(),t.select())};return k.createPortal(n.jsx("div",{className:"quick-session-backdrop",onMouseDown:e=>{e.target===e.currentTarget&&r()},children:n.jsxs("div",{className:"quick-session-dialog",ref:S,role:"dialog","aria-modal":"true","aria-label":C.title,onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),T(M)),"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),f((M+("ArrowDown"===e.key?1:-1)+E.length)%Math.max(1,E.length))))},children:[n.jsx("input",{ref:x,role:"combobox","aria-label":C.title,"aria-expanded":"true","aria-controls":"quick-session-results","aria-activedescendant":E[M]?`quick-result-${M}`:void 0,placeholder:C.placeholder,value:d,onChange:e=>{u(e.target.value),f(0)}}),n.jsxs("div",{className:"quick-session-results",id:"quick-session-results",role:"listbox","aria-label":C.title,children:[E.map((e,t)=>n.jsxs("button",{id:`quick-result-${t}`,type:"button",role:"option",tabIndex:-1,"aria-selected":t===M,"aria-disabled":e.disabled||void 0,onClick:()=>T(t),children:[n.jsx("strong",{children:e.title}),e.meta&&n.jsx("small",{children:e.meta})]},e.id)),!E.length&&(p||!v)&&n.jsx("p",{children:C.empty})]}),n.jsx("footer",{"aria-live":"polite",children:p?i.status||i.hint:b?C.error:v?C.loading:C.hint})]})}),document.body)}function Md({workspace:e,onSelect:s}){const i=t.useRef([]),o=t.useRef(new Map),[l,d]=t.useState(null),u=t.useRef({w:e,onSelect:s});u.current={w:e,onSelect:s};const h=t.useRef(null),f=t.useRef(null),p=a(c().language),m="en"===p?{title:"Recent conversations",hint:"Tab / Shift+Tab to preview · Release Ctrl to switch · Esc to cancel",empty:"No messages yet"}:"zh-TW"===p?{title:"最近會話",hint:"Tab / Shift+Tab 預覽 · 鬆開 Ctrl 切換 · Esc 取消",empty:"暫無訊息"}:{title:"最近会话",hint:"Tab / Shift+Tab 预览 · 松开 Ctrl 切换 · Esc 取消",empty:"暂无消息"};return t.useEffect(()=>{i.current=[],o.current.clear(),h.current=null,d(null)},[e.pairing?.daemonId]),t.useEffect(()=>{e.activeSessionId&&(i.current=[e.activeSessionId,...i.current.filter(t=>t!==e.activeSessionId)].slice(0,30))},[e.activeSessionId,e.pairing?.daemonId]),t.useEffect(()=>{const t=e.messagesSessionIdRef.current;if(t&&t===e.activeSessionId){o.current.set(t,e.messages.filter(e=>"user"===e.role||"assistant"===e.role).slice(-3).map(e=>({role:e.role,content:e.content.slice(0,360)})));for(const e of o.current.keys())i.current.includes(e)||o.current.delete(e)}},[e.messages,e.activeSessionId]),t.useEffect(()=>{f.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:"nearest",inline:"nearest"})},[l]),t.useEffect(()=>{if("desktop"!==r().kind)return;const e=e=>{h.current=e,d(e)},t=()=>e(null),n=()=>{const e=h.current?.sessions[h.current.index]?.sessionId;t(),e&&u.current.w.displaySessions.some(t=>t.sessionId===e&&!t.archived)&&u.current.onSelect(e)},s=s=>{if(s.isComposing||s.altKey||s.metaKey)return;if(h.current&&("Escape"===s.key||"Enter"===s.key))return s.preventDefault(),s.stopImmediatePropagation(),void("Escape"===s.key?t():n());if("Tab"!==s.key||!s.ctrlKey)return;if(document.querySelector('[data-shortcut-recording="true"], [role="dialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;s.preventDefault(),s.stopImmediatePropagation();const{w:r}=u.current;let o=h.current;if(!o){const e=r.displaySessions.filter(e=>!e.archived),t=[...new Set([r.activeSessionId,...i.current,...e.map(e=>e.sessionId)])].flatMap(t=>e.find(e=>e.sessionId===t)??[]);if(t.length<2)return;o={sessions:t,index:0}}e({...o,index:(o.index+(s.shiftKey?-1:1)+o.sessions.length)%o.sessions.length})},o=e=>{"Control"===e.key&&h.current&&n()},a=()=>{document.hidden&&t()};return window.addEventListener("keydown",s,!0),window.addEventListener("keyup",o,!0),window.addEventListener("blur",t),document.addEventListener("visibilitychange",a),()=>{window.removeEventListener("keydown",s,!0),window.removeEventListener("keyup",o,!0),window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",a)}},[]),l?n.jsx("div",{className:"recent-session-backdrop",onPointerDown:()=>{h.current=null,d(null)},children:n.jsxs("section",{className:"recent-session-switcher","aria-label":m.title,onPointerDown:e=>e.stopPropagation(),children:[n.jsxs("div",{className:"recent-session-heading",children:[n.jsx("strong",{children:m.title}),n.jsxs("span",{children:[l.index+1," / ",l.sessions.length]})]}),n.jsx("div",{className:"recent-session-cards",role:"listbox","aria-label":m.title,ref:f,children:l.sessions.map((t,r)=>n.jsxs("button",{type:"button",role:"option","aria-selected":r===l.index,"data-session-id":t.sessionId,className:"recent-session-card",title:`${t.customTitle||t.title||e.t.chat} · ${t.cwd}`,onClick:()=>{h.current=null,d(null),s(t.sessionId)},children:[n.jsx("div",{className:"recent-session-preview","aria-hidden":"true",children:(o.current.get(t.sessionId)?.length?o.current.get(t.sessionId):[{role:"assistant",content:t.customTitle||t.title||m.empty}]).map((e,t)=>n.jsx("p",{className:e.role,children:e.content},t))}),n.jsxs("div",{className:"recent-session-title",children:[n.jsx(ve,{size:17}),n.jsx("strong",{children:t.customTitle||t.title||e.t.chat})]}),n.jsxs("div",{className:"recent-session-meta",children:[t.agent," · ",t.cwd.split("/").filter(Boolean).at(-1)||t.cwd]})]},t.sessionId))}),n.jsxs("div",{className:"recent-session-hint","aria-live":"polite",children:[n.jsxs("span",{className:"recent-session-announcement",children:[l.sessions[l.index]?.customTitle||l.sessions[l.index]?.title||e.t.chat,"."," "]}),m.hint]})]})}):null}function Td(){const e=r().polishSettings,s="en"!==a(c().language),[i,o]=t.useState(),[l,d]=t.useState({...T}),[u,h]=t.useState(""),[f,p]=t.useState(!1),[m,g]=t.useState(""),[v,y]=t.useState(!1);if(t.useEffect(()=>{let t=!0;return e?.status().then(e=>{t&&(o(e),d(e.settings))}).catch(()=>{t&&(y(!0),g(s?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{t=!1}},[e]),!e)return null;const b=async t=>{p(!0),g(""),y(!1);try{const n=await e.save(l,t);o(n),d(n.settings),h(""),g(s?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{y(!0),g(s?"保存失败,请检查 HTTPS API 地址、模型和提示词。":"Save failed. Check the HTTPS API URL, model and prompts.")}finally{p(!1)}};return n.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[n.jsx("h2",{children:s?"语音润色":"Voice polishing"}),n.jsxs("label",{className:"speech-enabled",children:[n.jsx("input",{type:"checkbox",role:"switch","aria-checked":l.enabled,className:"settings-switch",checked:l.enabled,disabled:!i||f,onChange:async t=>{const n={...l,enabled:t.target.checked};d(n),p(!0),g(""),y(!1);try{const t=await e.save({...i.settings,enabled:n.enabled});o(t),d(n),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{d(l),y(!0),g(s?"无法保存开关设置":"Could not save setting")}finally{p(!1)}}}),s?"启用语音润色":"Enable voice polishing"]}),l.enabled&&n.jsxs("fieldset",{disabled:!i||f,className:"speech-polish-fields",children:[n.jsx("p",{className:"empty-copy",children:s?"识别后轻度整理口误、重复和标点,保留原意。转写文字会发送到你配置的模型;失败时保留原始文字,仅填入草稿。":"Lightly correct slips, repetition and punctuation while preserving meaning. Transcripts are sent to your configured model. Failures keep the original text; nothing is sent from your draft."}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:s?"API 地址":"API URL"}),n.jsx("input",{type:"url",value:l.baseUrl,onChange:e=>d({...l,baseUrl:e.target.value}),autoComplete:"off"})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:s?"模型":"Model"}),n.jsx("input",{value:l.model,onChange:e=>d({...l,model:e.target.value}),autoComplete:"off"})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:s?"润色 API Key":"Polishing API Key"}),n.jsx("input",{type:"password",autoComplete:"off",value:u,onChange:e=>h(e.target.value),placeholder:i?.configured?s?"已保存 · 留空保留":"Saved · leave blank to keep":"API Key"})]}),n.jsx("p",{className:"empty-copy",children:"encrypted"===i?.persistence?s?"密钥加密保存在这台 Mac。支持 OpenAI 兼容接口。":"Key encrypted on this Mac. Supports OpenAI-compatible APIs.":s?"密钥仅保留在当前页面,刷新后需重新填写。Web API 需允许跨域访问。":"Key kept only in this page; enter it again after reload. The API must allow cross-origin requests."}),l.enabled&&!i?.configured&&!u.trim()&&n.jsx("p",{className:"empty-copy",children:s?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),n.jsxs("details",{className:"speech-polish-advanced",children:[n.jsx("summary",{children:s?"自定义提示词":"Custom prompts"}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:s?"中文提示词":"Chinese prompt"}),n.jsx("textarea",{rows:5,value:l.promptZh,onChange:e=>d({...l,promptZh:e.target.value})})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:s?"英文提示词":"English prompt"}),n.jsx("textarea",{rows:5,value:l.promptEn,onChange:e=>d({...l,promptEn:e.target.value})})]}),n.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>d({...l,promptZh:T.promptZh,promptEn:T.promptEn}),children:s?"恢复默认提示词":"Reset prompts"})]}),n.jsxs("div",{className:"attention-actions",children:[n.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{b(u.trim()||void 0)},children:s?"保存润色设置":"Save polishing settings"}),i?.configured&&n.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{b("")},children:s?"移除润色密钥":"Remove polishing key"})]})]}),m&&n.jsx("p",{role:v?"alert":"status",className:v?"error-copy":"empty-copy",children:m})]})}const Ad={en:{title:"Voice input",disclosure:"Recording adds text to your draft without sending it. Audio is uploaded to Deepgram Nova-3 and billed to your Deepgram account.",saved:"Saved; your key is never displayed",session:"The key is kept only in this page’s memory. Enter it again after reloading or closing the page.",secure:"The key is encrypted on this Mac.",save:"Save API key",remove:"Remove API key",enabled:"Enable voice input",unsupported:"Recording requires a secure connection and a browser that supports WebM audio recording."},zh:{title:"语音输入",disclosure:"录音后将文字填入草稿,不会自动发送。音频会上传到 Deepgram Nova-3,并按你的 Deepgram 账户计费。",saved:"已保存,密钥不会回显",session:"密钥只保留在当前页面内存中,刷新或关闭页面后需要重新填写。",secure:"密钥会在此 Mac 上加密保存。",save:"保存密钥",remove:"移除密钥",enabled:"启用语音输入",unsupported:"录音需要安全连接,以及支持 WebM 音频录制的浏览器。"},"zh-TW":{title:"語音輸入",disclosure:"錄音後將文字填入草稿,不會自動傳送。音訊會上傳到 Deepgram Nova-3,並按你的 Deepgram 帳戶計費。",saved:"已儲存,金鑰不會回顯",session:"金鑰只保留在目前頁面記憶體中,重新整理或關閉頁面後需要重新填寫。",secure:"金鑰會在此 Mac 上加密儲存。",save:"儲存金鑰",remove:"移除金鑰",enabled:"啟用語音輸入",unsupported:"錄音需要安全連線,以及支援 WebM 音訊錄製的瀏覽器。"}};function Nd(){const e=r().speechSettings,i=Ad[a(c().language)],[o,l]=t.useState(),[d,u]=t.useState(""),[h,f]=t.useState(!1),[p,m]=t.useState(""),[g,v]=t.useState("true"===s().getItem("vibelet.web.voice.enabled")),y=Boolean(globalThis.isSecureContext&&"function"==typeof globalThis.navigator?.mediaDevices?.getUserMedia&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));t.useEffect(()=>{let t=!0;return e?.status().then(e=>{t&&l(e)}).catch(()=>{t&&m("Unable to load speech settings.")}),()=>{t=!1}},[e]);const b=e=>{v(e),s().setItem("vibelet.web.voice.enabled",String(e)),window.dispatchEvent(new Event("vibelet.speech.changed"))},w=async t=>{if(e&&!h){f(!0),m("");try{l(await e.saveKey(t)),u(""),t||b(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){m(n instanceof Error?n.message:String(n))}finally{f(!1)}}};if(!e)return null;const x="volcengine"===o?.engine,S=[...o?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:"en"===a(c().language)?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return n.jsxs(n.Fragment,{children:[n.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[n.jsx("h2",{children:i.title}),n.jsxs("label",{className:"speech-enabled",children:[n.jsx("input",{type:"checkbox",role:"switch","aria-checked":g,className:"settings-switch",checked:g,disabled:!y,onChange:e=>b(e.target.checked)}),i.enabled]}),g&&n.jsxs(n.Fragment,{children:[e.setEngine&&n.jsxs("div",{className:"field speech-engine-field",children:[n.jsx("span",{children:"en"===a(c().language)?"Recognition engine":"识别引擎"}),n.jsx(mi,{icon:ye,menuLabel:"Speech engine",label:S.find(e=>e.value===o?.engine)?.label??"Deepgram · Nova-3",options:S,value:o?.engine??"deepgram",disabled:h,onSelect:async t=>{f(!0),m(""),u("");try{l(await e.setEngine(t)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){m(n instanceof Error?n.message:String(n))}finally{f(!1)}}})]}),n.jsx("p",{className:"empty-copy",children:"system"===o?.engine?"en"===a(c().language)?"No API key needed. macOS 26+ uses on-device recognition and may download a language model on first use. Earlier versions may send audio to Apple. Text is added to your draft without sending.":"无需 API Key。macOS 26 及以上在本机识别,首次可能下载语言模型;较旧系统可能将音频发送给 Apple。文字只填入草稿,不会自动发送。":x?"en"===a(c().language)?"Audio is sent to Volcengine ASR Flash (volc.bigasr.auc_turbo), billed to your account. Enable this voice resource and use its API Key. Text only enters your draft.":"音频会上传至火山引擎录音识别极速版(volc.bigasr.auc_turbo),按你的账户计费。请开通此语音资源并填写语音 API Key,文字只追加到草稿。":i.disclosure}),"system"!==o?.engine&&n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"empty-copy",children:"encrypted"===o?.persistence?i.secure:i.session}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:x?"火山引擎 API Key":"Deepgram API Key"}),n.jsx("input",{type:"password",autoComplete:"off",value:d,onChange:e=>u(e.target.value),placeholder:o?.configured?i.saved:"API Key"})]}),n.jsxs("div",{className:"attention-actions",children:[n.jsx("button",{type:"button",className:"icon-text-button",disabled:h||!d.trim(),onClick:()=>{w(d)},children:i.save}),o?.configured&&n.jsx("button",{type:"button",className:"icon-text-button",disabled:h,onClick:()=>{w("")},children:i.remove})]})]})]}),!y&&n.jsx("p",{className:"empty-copy",children:i.unsupported}),p&&n.jsx("p",{role:"alert",className:"error-copy",children:p})]}),g&&n.jsx(Td,{})]})}function Dd(e){const t=e?.fiveHour??e?.weekly,n=Number(t?.usedPercent);return Number.isFinite(n)?{availablePercent:Math.round(Math.max(0,Math.min(100,100-n))),resetsAt:t?.resetsAt??""}:null}function Pd(e){return e?"success":"warning"}function Ld(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function Fd({connected:e,latencyMs:s,limits:r,t:i,failed:o={},loading:a=!1,onRetry:c}){const l=function(e){const t=[],n=Dd(e.codex),s=Dd(e.claude);return null!==n&&t.push({agent:"codex",label:"Codex",...n}),null!==s&&t.push({agent:"claude",label:"Claude",...s}),t}({codex:r.codex?.limits,claude:r.claude?.limits}),[d,u]=t.useState(0);t.useEffect(()=>{if(u(0),l.length<2)return;const e=setInterval(()=>u(e=>(e+1)%l.length),4e3);return()=>clearInterval(e)},[l.length]);const h=l[d%l.length],f=h?function(e,t=Date.now()){const n=new Date(e);if(!Number.isFinite(n.getTime())||n.getTime()<=t)return null;const s=e=>String(e).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}`}(h.resetsAt):null,p=h?`${h.label} ${h.availablePercent}%`:"",m=!!h&&o[h.agent],g=m?i.quotaUpdateFailed:h?"":a?i.loading:i.quotaUnavailable,v=`${i.remainingQuota}: ${p||g}${m?` · ${g}`:""} · ${f?i.quotaResetsAt.replace("{time}",f):i.quotaResetUnavailable}${e?"":` · ${i.latencyDisconnected}`}`,y=e?null===s?i.latencyMeasuring:`${s} ms`:i.latencyDisconnected;return n.jsxs("div",{className:"connection-indicators",children:[(h||c)&&n.jsxs("button",{type:"button",className:"connection-quota",disabled:!e||a||!c,onClick:c,title:`${v}${c?` · ${i.retry}`:""}`,"aria-label":`${v}${c?` · ${i.retry}`:""}`,"aria-busy":a,children:[n.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${m||!h?"warning":Pd(e)})`}}),n.jsxs("span",{className:"connection-quota-text",children:[p||g,m?" ↻":""]})]}),n.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${Ld(e,s)})`},"aria-label":`${i.connectionLatency}: ${y}`,children:[n.jsx(A,{size:11,"aria-hidden":"true"}),n.jsx("span",{className:"connection-latency-text",children:y})]})]})}function qd({workspace:e}){const{phase:s,clientRef:r,pairing:i,t:o}=e,[a,c]=t.useState(null),[l,d]=t.useState({}),[u,h]=t.useState({}),[f,p]=t.useState(!1),m=t.useRef(()=>{});return t.useEffect(()=>{h({}),d({})},[i?.daemonId]),t.useEffect(()=>{const e=r.current;if(c(null),p(!1),"connected"!==s||!e)return;let t=!0;const n=e.onLatency(c),i=new Set,o=new Map,a={codex:0,claude:0},l=()=>t&&r.current===e&&e.isConnected,u=(n,s=!1)=>{l()&&!i.has(n)&&(clearTimeout(o.get(n)),i.add(n),p(!0),Bs(e,()=>({action:"usage.limits.fetch",id:e.makeId("header-usage"),agent:n,force:s}),l).then(e=>{if(!l())return;const t=Boolean(e?.limits);a[n]=t?0:a[n]+1,h(e=>({...e,[n]:!t})),e?.limits&&d(t=>({...t,[n]:e}));const s=t?6e4:Math.min(6e4,15e3*2**Math.min(a[n]-1,2));o.set(n,setTimeout(()=>u(n),s))}).finally(()=>{i.delete(n),t&&p(i.size>0)}))},f=()=>{u("codex"),u("claude")};return m.current=()=>{u("codex",!0),u("claude",!0)},f(),window.addEventListener("online",f),window.addEventListener("focus",f),()=>{t=!1,m.current=()=>{},n();for(const e of o.values())clearTimeout(e);window.removeEventListener("online",f),window.removeEventListener("focus",f)}},[s,r,i?.daemonId]),n.jsx(Fd,{connected:"connected"===s,latencyMs:a,limits:l,failed:u,loading:f,onRetry:()=>m.current(),t:o})}function Od({value:e,t,showSession:s=!0,onChange:r}){const i=[...s?[{tab:"session",label:t.session,Icon:Le}]:[],{tab:"files",label:t.files,Icon:te},{tab:"terminal",label:t.terminal,Icon:qe},{tab:"browser",label:t.browser,Icon:ae}];return n.jsx("div",{className:"control-tabs",children:i.map(({tab:t,label:s,Icon:i})=>n.jsxs("button",{"aria-label":s,"aria-pressed":e===t,className:e===t?"selected":"",onClick:()=>r(t),title:s,type:"button",children:[n.jsx(i,{"aria-hidden":"true"}),n.jsx("span",{children:s})]},t))})}function _d(){const[e,s]=t.useState(null);return t.useEffect(()=>{let e=null,t=null;const n=()=>{e&&null!==t&&e.setAttribute("title",t),e=null,t=null,s(null)},r=e=>{if(!(e instanceof Element))return null;const t=e.closest("button, a");return t?.closest(".control-pane, .control-tabs, .header-actions, .right-resize-handle")?t.textContent?.trim()?null:t:null},i=r=>{if(r===e)return;if(n(),!r)return;const i=r.getAttribute("title")||r.getAttribute("aria-label");if(!i)return;e=r,t=r.getAttribute("title"),null!==t&&r.removeAttribute("title");const o=r.getBoundingClientRect(),a=o.bottom+42>window.innerHeight,c=o.right>window.innerWidth-140?"end":o.left<140?"start":"center";s({label:i,left:"end"===c?o.right:"start"===c?o.left:o.left+o.width/2,top:a?o.top-7:o.bottom+7,above:a,align:c})},o=e=>i(r(e.target)),a=t=>{e&&t.relatedTarget instanceof Node&&e.contains(t.relatedTarget)||r(t.target)===e&&n()},c=e=>i(r(e.target)),l=t=>{r(t.target)===e&&n()};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",a),document.addEventListener("focusin",c),document.addEventListener("focusout",l),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",a),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),n()}},[]),e?k.createPortal(n.jsx("div",{className:"right-sidebar-icon-hint",role:"tooltip",style:{left:e.left,top:e.top,transform:`translate(${"end"===e.align?"-100%":"start"===e.align?"0":"-50%"}, ${e.above?"-100%":"0"})`},children:e.label}),document.body):null}function $d({chinese:e}){const[i,o]=t.useState(yr),[a,c]=t.useState(null),[l,d]=t.useState(""),u=e=>{!function(e){s().setItem(vr,JSON.stringify(e)),window.dispatchEvent(new Event(lr))}(e),o(e),d("")};return n.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[n.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),n.jsx("p",{className:"empty-copy",children:e?"点击组合键后直接按键录制。Esc 取消,退格键清除。新建标签会沿用当前终端或浏览器;右侧栏隐藏时不新建标签。":"Click a shortcut to record it. Escape cancels; Backspace clears. New tab follows the current terminal or browser; it does nothing while the right sidebar is hidden."}),ur.map(t=>n.jsxs("div",{className:"workspace-shortcut-row",children:[n.jsx("span",{children:e?t.zh:t.en}),n.jsx("button",{type:"button","data-shortcut-recording":a===t.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?t.zh:t.en}`,onClick:()=>{c(t.id),d("")},onBlur:()=>c(null),onKeyDown:n=>{if(a!==t.id)return;if(n.preventDefault(),n.stopPropagation(),"Escape"===n.key)return c(null),void d("");if("Backspace"===n.key||"Delete"===n.key)return u({...i,[t.id]:""}),void c(null);const s=pr(n.nativeEvent);if(!s)return;const o=function(e,t,n){return"browser"===r().kind?"mod+w"===t?"reserved":gr(e,t,{closeTab:"mod+alt+w",...n}):gr(e,t,n)}(t.id,s,i);if(o){const t=ur.find(e=>e.id===o);return void d("reserved"===o?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?t?.zh:t?.en}`)}u({...i,[t.id]:s}),c(null)},children:a===t.id?e?"按下快捷键…":"Press shortcut…":mr(br(t.id,i))||(e?"未设置":"Not set")})]},t.id)),l&&n.jsx("p",{role:"alert",children:l}),n.jsx("div",{className:"attention-actions",children:n.jsx("button",{type:"button",onClick:()=>{u({}),c(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),n.jsx("p",{className:"empty-copy",children:e?"⌘N 新建会话,⌘, 打开设置;⌘W 保留为关闭窗口。关闭标签默认使用 ⌘⌥W。":"⌘N creates a session; ⌘, opens settings; ⌘W closes the window. Close tab defaults to ⌘⌥W."})]})}function zd({children:e,t:s,onClose:r}){const i=t.useRef(null);return t.useEffect(()=>{const e=document.getElementById("vibelet-workspace");return e&&(e.inert=!0),i.current?.focus(),()=>{e&&(e.inert=!1)}},[]),k.createPortal(n.jsxs("section",{className:"browser-settings-page","aria-label":s.settings,onKeyDown:e=>{if("Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),r()),"Tab"!==e.key)return;const t=[...e.currentTarget.querySelectorAll("button:not(:disabled),input:not(:disabled),a[href]")].filter(e=>e.getBoundingClientRect().width>0),n=t[0],s=t.at(-1);e.shiftKey&&document.activeElement===n&&(e.preventDefault(),s?.focus()),e.shiftKey||document.activeElement!==s||(e.preventDefault(),n?.focus())},children:[n.jsxs("button",{ref:i,type:"button",className:"icon-text-button",onClick:r,children:["← ",s.chat]}),n.jsx("h1",{children:s.settings}),n.jsxs("div",{className:"browser-settings-body",children:[n.jsx(Ir,{}),e,n.jsx($d,{chinese:"Browser"!==s.browser})]})]}),document.body)}function Hd({children:e,collapsed:s,t:i,value:o,showSession:a,onChange:c,onResize:l}){const d=_l("right",e=>{"terminal"!==e&&"browser"!==e||c(e)}),u=r().toolbarTarget?.("controls"),[h,f]=t.useState(null),p=n.jsx("div",{className:"right-dock-toolbar",ref:f,children:n.jsx(Od,{value:o,t:i,showSession:a,onChange:c})});return"admin"===o&&"browser"===r().kind?n.jsx(zd,{t:i,onClose:()=>c("files"),children:e}):n.jsxs(Dl.Provider,{value:{element:h,kind:o},children:[n.jsx(_d,{}),u&&!s?k.createPortal(p,u):null,n.jsx("button",{"aria-label":i.resizeControlsSidebar,"aria-hidden":s,className:"resize-handle right-resize-handle",disabled:s,onPointerDown:l,title:i.resizeControlsSidebar,type:"button",children:n.jsx("span",{})}),n.jsx("div",{className:"workspace-control-sidebar-motion",inert:s,"aria-hidden":s,children:n.jsxs("aside",{tabIndex:-1,"aria-label":i.controls,className:"control-pane",...d,children:[!u&&n.jsx("div",{className:"control-pane-toolbar",children:p}),e]})})]})}function Bd({path:e,label:t,zh:s}){const{copyText:r,feedback:i}=qi(s?"已复制路径":"Path copied",s?"复制失败,请重试":"Copy failed. Please try again."),o=i?.message??t;return n.jsx("button",{type:"button",title:o,"aria-label":o,onClick:()=>{r(e)},children:i?"success"===i.tone?n.jsx(O,{}):n.jsx(Be,{}):n.jsx(V,{})})}function Ud(){const e=a(c().language);return"en"===e?{read:"Read",live:"Edit",edit:"Visual",source:"Source",properties:"Properties",loading:"Loading…",unavailable:"Reference unavailable",editorError:"Unable to load the editor. Switch to source mode."}:"zh-TW"===e?{read:"瀏覽",live:"編輯",edit:"視覺化",source:"原始碼",properties:"屬性",loading:"正在載入…",unavailable:"無法讀取引用",editorError:"無法載入編輯器,請切換到原始碼模式。"}:{read:"浏览",live:"编辑",edit:"可视化",source:"源码",properties:"属性",loading:"正在加载…",unavailable:"无法读取引用",editorError:"无法加载编辑器,请切换到源码模式。"}}function Wd({file:e}){const[s,i]=t.useState(!1),o=j(()=>i(!1),void 0,s),l=$s(),d=a(c().language),u="en"===d?"Close":"zh-TW"===d?"關閉":"关闭",h=r().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>i(!0),children:[n.jsx(ee,{"aria-hidden":"true"}),l.pdfPreview]}),s&&k.createPortal(n.jsx("div",{className:"remote-document-layer",onPointerDown:e=>{e.target===e.currentTarget&&i(!1)},children:n.jsxs("div",{ref:o,className:"remote-document-dialog","aria-label":l.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[n.jsxs("header",{children:[n.jsx("span",{children:e.path.split("/").pop()}),n.jsx("button",{className:"icon-button",type:"button","aria-label":u,title:u,onClick:()=>i(!1),children:n.jsx(Be,{"aria-hidden":"true"})})]}),n.jsx("iframe",{title:l.pdfPreview,src:`${h}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function Kd({file:e}){const[s,i]=t.useState(),o=e.objectUrl??e.path,a=()=>i(o),c=$s(),l=Zs(e.path,e.contentType,"text"===e.kind);if(s===o)return n.jsx("p",{className:"empty-copy",role:"status",children:c.mediaError});if("html"===l){const t=e.dirty?void 0:r().htmlPreviewUrl?.(e.path,e.cwd);return n.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:c.htmlPreview,src:t,srcDoc:t?void 0:Xs(e.text)})}return e.objectUrl?"image"===l?n.jsx("div",{className:"remote-media-viewer remote-image-viewer",children:n.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:a})}):"audio"===l?n.jsx("audio",{"aria-label":c.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:a}):"video"===l?n.jsx("div",{className:"remote-media-viewer remote-video-viewer",children:n.jsx("video",{"aria-label":c.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:a},e.objectUrl)}):"pdf"===l?n.jsx(Wd,{file:e}):n.jsx("p",{className:"empty-copy",children:c.mediaError}):null}function Vd(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function Qd(e,t){return An(ct(e,t))??t??"."}function Gd(e,t,n){if(!e)return{path:ct(t,n),cwd:n??Qd(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??Qd(t,n):Qd(t,n);return{path:Vd(e||t),cwd:s}}function Jd(e,t){if(!t)return;let n=t.replace(/^#/,"");try{n=decodeURIComponent(n)}catch{}const s=n.startsWith("^"),r=e.querySelectorAll(s?".block-id-superscript":"h1,h2,h3,h4,h5,h6"),i=Array.from(r).find(e=>e.textContent?.trim()===n||!s&&e.id===n),o=s?i?.closest(".milkdown-list-item-block, li, p, blockquote")??i:i;o?.scrollIntoView({block:"start"})}const Zd=new Map;function Xd(e,t,n){for(const[s,r]of Zd)Date.now()-r.time>1e4&&Zd.delete(s);n&&Zd.set(ct(e,t),{hash:n,time:Date.now()})}function Yd(e,t){const n=ct(e,t),s=Zd.get(n);return Zd.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const eu=t.lazy(()=>R(()=>import("./MarkdownModePanel-VRQHdCgq.js"),__vite__mapDeps([25,1,2,26])).then(e=>({default:e.MarkdownModePanel}))),tu=t.lazy(()=>R(()=>import("./file-editor-FileCodeEditor-Cc7o0SoW.js"),__vite__mapDeps([27,1,2,28,29])).then(e=>({default:e.FileCodeEditor}))),nu=t.lazy(()=>R(()=>import("./file-editor-ObsidianCodeEditor-DKHh91wx.js"),__vite__mapDeps([30,1,2,27,28,29,31,32,33,34,35,36,37,3,38,6,39,40,41])).then(e=>({default:e.ObsidianCodeEditor}))),su=t.lazy(()=>R(()=>import("./file-editor-ObsidianFileEditor-D4DiY_3P.js"),__vite__mapDeps([42,1,2,37,3,28,38,43,32,5,44,45,46,47])).then(e=>({default:e.ObsidianFileEditor})));function ru({file:e,client:s,onOpenRemoteFile:r,onTextChange:i}){const o=function(e,n){return t.useMemo(()=>{let t;return async(s,r)=>{const i=Gd(s,r,n),o={path:ct(i.path,i.cwd),cwd:n??i.cwd};if(!e?.isConnected||!n||!s||/^([/.]|[a-z]:)/i.test(s))return o;t??=e.request({action:"vault.listMarkdown",id:`editor-vault-${crypto.randomUUID()}`,cwd:n});try{const{entries:e}=await t,r=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===r||e.basename.toLowerCase()===r||e.aliases?.includes(r)),c=ct(Vd(s),i.cwd),l=a.find(e=>ct(e.relPath,n)===c)??a.find(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===r)??a.sort((e,t)=>e.relPath.localeCompare(t.relPath))[0];return l?{path:ct(l.relPath,n),cwd:n}:o}catch{return t=void 0,o}}},[e,n])}(s,e.cwd),l=function(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}(e.path),[d,u]=t.useState("preview"),h="html"===Zs(e.path,e.contentType,!0),f="en"!==a(c().language);return n.jsxs(n.Fragment,{children:[h&&n.jsxs("div",{className:"segmented editor-mode-tabs",children:[n.jsx("button",{type:"button",className:"edit"===d?"selected":"",onClick:()=>u("edit"),children:f?"编辑":"Edit"}),n.jsx("button",{type:"button",className:"preview"===d?"selected":"",onClick:()=>u("preview"),children:f?"预览":"Preview"})]}),l?n.jsx(t.Suspense,{fallback:n.jsx("pre",{className:"remote-editor",children:e.text}),children:n.jsx(eu,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:Ud(),renderVisual:t=>n.jsx(su,{client:s,resolveFile:o,path:e.path,cwd:e.cwd,text:e.text,readOnly:t,onChange:i,onOpenFile:r}),renderCode:t=>n.jsx(nu,{client:s,cwd:e.cwd,path:e.path,resolveFile:o,onOpenFile:r,text:e.text,onChange:i,preview:t})})}):h&&"preview"===d?n.jsx(Kd,{file:e}):n.jsx(t.Suspense,{fallback:n.jsx("pre",{className:"remote-editor",children:e.text}),children:n.jsx(tu,{path:e.path,text:e.text,onChange:i})})]})}function iu({file:e,daemonId:s}){const[i,o]=t.useState(!1),[l,d]=t.useState(!1),u=r().openFile;if(!u||!s)return null;const h=a(c().language),f="en"===h?["Open in another app","Save changes before opening","Unable to open. Try again."]:"zh-TW"===h?["使用其他軟體開啟","請先儲存變更再開啟","無法開啟,請重試"]:["使用其他软件打开","请先保存更改再打开","无法打开,请重试"],p=e.dirty?f[1]:l?f[2]:f[0];return n.jsx("button",{type:"button",title:p,"aria-label":p,disabled:i||e.dirty,onClick:async()=>{o(!0),d(!1);try{await u({path:e.path,cwd:e.cwd,daemonId:s})}catch{d(!0)}finally{o(!1)}},children:n.jsx(M,{})})}function ou({workspace:e,children:s}){const i=st(),o=Ye(e.pairing?.daemonId,e.activeSessionId),l=function(e){const{value:n,setForScope:s}=Xe(e,!1);return t.useEffect(()=>{const e=e=>{const t=e.detail;s(Ye(t.daemonId,t.sessionId),t.removing)};return window.addEventListener(Ve,e),()=>window.removeEventListener(Ve,e)},[s]),n}(o),d=_l("center"),{openFiles:h,setOpenFiles:f}=e,[m,g]=Ze(o,null),[v,y]=t.useState(null),b=t.useRef({files:h,remoteFile:e.remoteFile,scopeKey:o});b.current={files:h,remoteFile:e.remoteFile,scopeKey:o};const w=t.useRef(new Map);t.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of[...w.current]){const e=Je(n,t);e!==n&&(w.current.delete(n),null!==e&&w.current.set(e,s))}};return window.addEventListener(We,e),()=>window.removeEventListener(We,e)},[]);const x="en"!==a(c().language);t.useEffect(()=>{if(!e.remoteFile)return w.current.set(o,null),void g(null);const t=e.remoteFile,n=Ys(t);w.current.get(o)!==n&&(g(n),i.setCenter(null)),w.current.set(o,n)},[e.remoteFile,o]);const S=t=>{i.setCenter(null),e.setRemoteFile(h[t]),g(t),Os({file:h[t].path,cwd:h[t].cwd},{replace:!0})},k=()=>{g(null),e.setRemoteFile(null),i.setCenter(null),w.current.set(o,null),Os({file:void 0},{replace:!0})},I=async t=>{const n=h[t];if(!n)return;const s=u();n.dirty&&!(await p({title:s.discard,message:t,confirmLabel:s.discardAction,danger:!0}))||b.current.scopeKey===o&&b.current.files[t]?.text===n.text&&(f(e=>{const n={...e};return delete n[t],n}),t===m&&(g(null),w.current.set(o,null),e.setRemoteFile(null),Os({file:void 0},{replace:!0})))};t.useEffect(()=>{const e=e=>{const t=e.detail;if("closeTab"===t)return void(i.center?i.close(i.center):m&&I(m));const n=[null,...Object.keys(h),...i.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(i.center||m),r=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];r?h[r]?S(r):i.setCenter(r):k()};return window.addEventListener(dr,e),()=>window.removeEventListener(dr,e)},[h,m,i]);const C=m?h[m]:null;!function(e,n,s){const r=t.useRef({enabled:e,busy:n,save:s});r.current={enabled:e,busy:n,save:s},t.useEffect(()=>{const e=e=>{if(!r.current.enabled||e.defaultPrevented||e.isComposing||229===e.keyCode||"mod+s"!==pr(e)||document.querySelector('[role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden]'))return;const t=e.target instanceof Element?e.target:document.activeElement;t?.closest(".document-file, .document-file-header")&&(e.preventDefault(),e.stopPropagation(),e.repeat||r.current.busy||r.current.save())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[])}(!!C&&"text"===C.kind&&!i.center&&!l,e.busy,e.saveRemoteFile);const j=r().toolbarTarget?.("conversation"),R=C&&!i.center&&n.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":x?"文件操作":"File actions",children:[n.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:n.jsx(E,{})}),n.jsx(iu,{file:C,daemonId:e.pairing?.daemonId},`open:${C.path}`),n.jsx(Bd,{path:C.path,label:e.t.copyPath,zh:x},C.path),"text"===C.kind&&n.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!C.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:n.jsx(Me,{})})]});return n.jsx(Ro.Provider,{value:v,children:n.jsxs("div",{className:"workspace-documents",...d,children:[!j&&n.jsx("div",{className:"chat-header document-conversation-header",ref:y}),(Object.keys(h).length>0||i.items.some(e=>"center"===e.location))&&n.jsxs("div",{className:"document-tabs",children:[n.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":x?"工作区标签页":"Workspace tabs",children:[n.jsx("button",{role:"tab","aria-selected":!m&&!i.center,onClick:k,type:"button",children:e.t.chat}),Object.entries(h).map(([t,s])=>n.jsxs("div",{className:"document-tab","data-active":!i.center&&m===t,children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":!i.center&&m===t,title:Ys(s),onClick:()=>S(t),children:[n.jsx(ee,{}),n.jsxs("span",{className:"document-tab-label",children:[wn(s.path),s.dirty?" ·":""]})]}),n.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${wn(s.path)}`,onClick:()=>I(t),children:n.jsx(Be,{})})]},t)),n.jsx(Fl,{location:"center",t:e.t})]}),R]}),n.jsx("div",{hidden:!!m||!!i.center,className:"document-chat",children:s}),n.jsx("div",{hidden:!i.center,className:"dock-center-content",children:n.jsx(Ol,{location:"center"})}),C&&!i.center&&n.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":wn(C.path),inert:l,"aria-busy":l,children:[e.errorText&&!e.remoteFileConflict&&n.jsx("div",{role:"alert",className:"inline-notice warning",children:n.jsx("span",{children:e.errorText})}),"text"===C.kind?n.jsx(ru,{client:e.clientRef?.current,file:C,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},C.path):n.jsx(Kd,{file:C},C.path),e.remoteFileConflict&&n.jsxs("div",{role:"alert",className:"inline-notice warning",children:[n.jsx("span",{children:e.t.remoteFileConflict(C.path)}),n.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await p({message:e.t.confirmOverwrite(wn(t.path)),danger:!0})&&b.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}const au=t.lazy(()=>R(()=>import("./GlobalPendingDialog-DqEBvP53.js"),__vite__mapDeps([48,1,2,14])));function cu({workspace:e}){const s=function(e){const[n,s]=t.useState(0),[r,i]=t.useState(0);return t.useLayoutEffect(()=>{if(!r)return;const e=requestAnimationFrame(()=>{document.querySelector('[role="dialog"]')||document.querySelector(".document-chat:not([hidden]) .composer textarea")?.focus({preventScroll:!0})});return()=>cancelAnimationFrame(e)},[r]),{selectSession:t=>{i(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t),e.completionAttention?.acknowledgeOpened(t);const n=e.displaySessions.find(e=>e.sessionId===t);if(!e.pendingApprovals[t]&&!e.pendingQuestions[t]&&!n?.runtime.needsAttention)return;s(e=>e+1);const r=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===r&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:n}}(e),[i,o]=t.useState(!0),[a,c]=t.useState(!1),[l,d]=t.useState(!1);!function(e){const n=st(),s=Cd(e),[i,o]=t.useState(yr),a=t.useRef({workspace:e,dock:n,shortcuts:i,toggleRightSidebar:s});a.current={workspace:e,dock:n,shortcuts:i,toggleRightSidebar:s},t.useEffect(()=>{const e=()=>o(yr()),t=e=>e instanceof Element&&!!e.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"], #desktop-toolbar-controls');let n=!1;const s=e=>{n=t(e.target)},i=(e,s,r=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const i=pr(e);if(!i&&!s)return;const{workspace:o,dock:c,shortcuts:l}=a.current,d=s??ur.find(e=>br(e.id,l)===i)?.id;if(!d)return;if("searchMessages"===d&&(t(r)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;const u="terminal"===o.controlTab?"terminal":"browser",h=c.items.find(e=>e.id===c.center),f=!o.rightSidebarCollapsed&&(t(r)||r===document.body&&n),p=!f&&h?h:c.items.find(e=>e.id===c.right[u]);if("browserAddress"===d||"browserCopyUrl"===d){if("browser"!==p?.kind)return;const t=Array.from(document.querySelectorAll(".dock-surface")).find(e=>e.dataset.dockId===p.id&&!e.hidden)?.querySelector(".embedded-browser-panel");if(!t)return;return e.preventDefault(),e.stopPropagation(),void t.dispatchEvent(new CustomEvent("vibelet.browser.command",{detail:d}))}switch(e.preventDefault(),e.stopPropagation(),d){case"quickSearch":window.dispatchEvent(new Event("vibelet.quick-search"));break;case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":o.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.current.toggleRightSidebar();break;case"files":case"terminal":case"browser":o.setControlTabAndOpen(d);break;case"searchSessions":o.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{if(o.rightSidebarCollapsed)break;const e="terminal"===p?.kind||"browser"===p?.kind?p.kind:u;c.add(e,o.t[e],o.cwd),o.setControlTabAndOpen(e);break}case"moveTab":p&&c.move(p.id,"center"===p.location?"right":"center");break;case"diff":o.activeSession&&o.setDiffSessionId(o.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(f)if("closeTab"===d)"files"===o.controlTab||!p||p.emptyPlaceholder?o.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),c.close(p.id));else{const e=c.items.filter(e=>"right"===e.location&&e.kind===u);e.length&&c.setRight(t=>({...t,[u]:e[(Math.max(0,e.findIndex(e=>e.id===p?.id))+("nextTab"===d?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(dr,{detail:d}))}},c=e=>i(e),l=r().subscribeCommand?.(e=>{"close-tab"===e&&i(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(lr,e),window.addEventListener("focusin",s,!0),window.addEventListener("pointerdown",s,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(lr,e),window.removeEventListener("focusin",s,!0),window.removeEventListener("pointerdown",s,!0),window.removeEventListener("keydown",c,!0)}},[])}(e);const u=Cd(e),[h,f]=function(e){const[n,s]=t.useState(null);return t.useEffect(()=>{const t=()=>s(t=>t??{cwd:e}),n=r().subscribeCommand?.(e=>{"new-session"===e&&t()}),i=e=>{"browser"!==r().kind||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",i),()=>{n?.(),window.removeEventListener("keydown",i)}},[e]),[n,s]}(e.cwd);t.useEffect(()=>{"browser"===e.controlTab&&o(!0)},[e.controlTab]),t.useEffect(()=>{"terminal"===e.controlTab&&c(!0)},[e.controlTab]),t.useEffect(()=>{("session"===e.controlTab||"desktop"===r().kind&&"admin"===e.controlTab)&&e.setControlTab("files");const t=()=>e.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",t),()=>window.removeEventListener("vibelet.browser.settings",t)},[e.controlTab,e.setControlTab,e.setControlTabAndOpen]),t.useEffect(()=>{e.activeQuestion&&e.setQuestionAnswers(Sn(e.activeQuestion))},[e.activeQuestion,e.setQuestionAnswers]);const{clientRef:p,phase:m,statusText:g,errorText:v,pairing:y,sessions:b,nextCursor:w,folderCounts:x,inventoryVersion:S,activeSessionId:k,diffSessionId:I,setDiffSessionId:C,respondingSessions:j,questionAnswers:R,agent:E,cwd:M,approvalMode:T,model:A,setModel:N,effort:D,setEffort:P,fastMode:L,setFastMode:F,renameTitle:q,setRenameTitle:O,draft:_,webPreferences:$,sessionSort:z,setSessionSort:H,search:B,setSearch:U,sinceFilter:W,setSinceFilter:K,hideArchived:V,setHideArchived:Q,groupFolders:G,setGroupFolders:J,showNeedsAttentionGroup:Z,setShowNeedsAttentionGroup:X,showRunningGroup:Y,setShowRunningGroup:ee,separatePinnedGroup:te,setSeparatePinnedGroup:ne,collapsedFolders:se,setCollapsedFolders:re,sessionAgentFilter:ie,setSessionAgentFilter:oe,directoryTags:ae,composerPreferences:ce,savedTargets:le,leftSidebarCollapsed:de,setLeftSidebarCollapsed:ue,rightSidebarCollapsed:he,setRightSidebarCollapsed:fe,workspaceClassName:pe,wideMainClassName:me,workspaceStyle:ge,beginPaneResize:ve,commitSearch:ye,saveTargets:be,setLanguagePreference:we,setThemePreference:xe,updateComposerPreferences:Se,t:ke,busy:Ie,rewindMessage:Ce,rewinding:je,controlTab:Re,setControlTab:Ee,detailsOpen:Me,setDetailsOpen:Te,setControlTabAndOpen:Ae,skills:Ne,admin:De,daemonMetadata:Pe,notificationSettings:Le,notificationPermission:Fe,archiveSyncBusy:qe,archiveSyncStatus:Oe,attachments:_e,setAttachments:$e,uploadBusy:ze,directory:He,newDirName:Be,setNewDirName:Ue,remoteFile:We,uploadFiles:Ke,openRemoteFile:Ve,listDirectory:Qe,listSessionDirectories:Ge,listFileTreeDirectory:Je,createDirectory:Ze,createSessionDirectory:Xe,pendingActionsCount:Ye,activeQueue:et,activeModelOptions:tt,activeUsage:nt,activeApproval:rt,activeQuestion:it,activeSession:ot,displaySessions:at,groupedSessions:ct,pendingSessionIds:lt,visibleSessions:dt,historyLoading:ut,hasOlderHistory:ht,olderHistoryLoading:ft,requestHistory:pt,messages:mt,messagesSessionIdRef:gt,updateDraft:vt,requestReconnectSnapshot:yt,requestSessions:bt,fetchAgentResources:wt,failedSend:xt,dismissFailedSend:St,retryFailedSend:kt,stagePendingSession:It,listSessionModels:Ct,loadDirectoryGitMetadata:jt,sendDraft:Rt,sendQuickReply:Et,respondApproval:Mt,respondQuestion:Tt,cancelQuestion:At,setQuestionChoice:Nt,requestActiveAction:Dt,interruptActiveSession:Pt,retrySessions:Lt,updateApprovalMode:Ft,cancelQueuedTurn:qt,setSessionPinned:Ot,setSessionArchived:_t,deleteSession:$t,updatePinned:zt,updateArchived:Ht,renameSession:Bt,runArchiveSync:Ut,skipArchiveSync:Wt,runAdminAction:Kt,exportActiveSession:Vt,clearPairing:Qt,setNotificationsEnabled:Gt,connectSavedTarget:Jt,forgetSavedTarget:Zt,openSessionDetails:Xt,editFolderTags:Yt,copyResumeCommand:en,resumeInTerminal:tn,notificationsBlocked:nn,hasDaemonUpdate:sn,archiveSynced:rn,archiveSyncDismissed:on}=e,an=t.useMemo(()=>function(e,t,n){const s={};for(const r of Object.values(e))s[r.sessionId]=`${n.interactionWaitingApproval} · ${r.description||r.toolName}`;for(const r of Object.values(t))s[r.sessionId]=`${n.interactionWaitingAnswer} · ${r.questions[0]?.question??""}`;return s}(e.pendingApprovals,e.pendingQuestions,ke),[e.pendingApprovals,e.pendingQuestions,ke]),cn=t.useMemo(()=>l?Object.fromEntries(ct.map(e=>[e.folder,!1!==se[e.folder]])):se,[l,se,ct]),ln=ct.length>0&&ct.every(e=>cn[e.folder]);return"missing-pair"===m?n.jsxs(n.Fragment,{children:[n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ke.skipToConversation}),n.jsx(Tl,{errorText:v,t:ke})]}):n.jsxs("main",{className:pe,id:"vibelet-workspace",style:ge,children:[n.jsx(Md,{workspace:e,onSelect:s.selectSession}),n.jsx(Rd,{workspace:e,onSelect:s.selectSession}),h&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(dd,{client:"connected"===m?p.current:null,onOpenRemoteFile:Ve,pairing:y,onLoadGitMetadata:jt,cwd:h.cwd,agent:E,device:y?.daemonId??"disconnected",connected:"connected"===m,approvalMode:T,model:A,effort:D,fastMode:L,t:ke,onClose:()=>f(null),onCreate:It,onListModels:Ct,onListDirectories:Ge,onCreateDirectory:Xe},y?.daemonId??"disconnected")}),n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ke.skipToConversation}),n.jsx(Id,{collapsed:de,onExpand:()=>ue(e=>!e),onResize:ve("left"),t:ke,children:n.jsx(kd,{connectionIndicators:n.jsx(qd,{workspace:e}),activeDaemonId:y?.daemonId,activeSessionId:k,busy:Ie,collapsedFolders:cn,allFoldersCollapsed:ln,currentCwd:M,directoryTags:ae,displayName:y?.displayName,savedTargets:le,folderCounts:x,groupFolders:G,sessionSort:z,onSessionSortChange:H,groupedSessions:ct,hideArchived:V,separatePinnedGroup:te,showNeedsAttentionGroup:Z,showRunningGroup:Y,inventoryVersion:S,nextCursor:w,phase:m,respondingSessionIds:j,search:B,sessionAgentFilter:ie,sessionsCount:at.length,sinceFilter:W,statusText:g,t:ke,hasDaemonUpdate:sn,visibleSessions:dt,onLoadMore:e=>bt({append:!0,cursor:e}),onCopyResumeCommand:en,onResumeInTerminal:tn,onConnectTarget:Jt,attentionReasons:an,pendingSessionIds:lt,onRequestNewSession:e=>f({cwd:e??M}),onRenameSession:Bt,onDeleteSession:e=>{$t(e)},onEditFolderTags:Yt,onOpenSessionDetails:Xt,onResetFilters:()=>{H("updated"),oe("all"),K("30d"),Q(!1),J(!0),X(!1),ee(!1),ne(!1)},onRenameTarget:(e,t)=>be(function(e,t,n){const s=n.trim();return s?e.map(e=>e.daemonId===t?{...e,label:s}:e):e}(le,e,t)),onEditConnection:r().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:U,onSearchCommit:ye,onSelectSession:s.selectSession,onToggleSessionArchived:e=>{_t(e,!e.archived)},onToggleSessionPinned:e=>{Ot(e,!e.pinned)},onSessionAgentFilterChange:oe,onSinceFilterChange:K,onToggleFolder:e=>re(t=>({...t,[e]:l?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{d(!ln),re({})},onToggleGroupFolders:()=>J(e=>!e),onToggleHideArchived:()=>Q(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>ue(!0)})}),n.jsxs("section",{className:me,"aria-label":ke.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[n.jsx(ou,{workspace:e,children:n.jsx(Oc,{client:"connected"===m?p.current:null,activeSession:ot,activeSessionId:k,activeModelOptions:tt,activeQueue:et,activeUsage:nt,agent:E,approvalMode:T,attachments:_e,busy:Ie,cwd:M,draft:_,effort:D,errorText:v,failedSend:xt,onDismissFailedSend:St,fastMode:L,historyLoading:ut,hasOlderHistory:ht,olderHistoryLoading:ft,onLoadOlderHistory:()=>ot?pt(ot,{older:!0}):Promise.resolve(),messages:mt,messagesSessionId:gt.current,model:A,phase:m,quickReplies:ce.quickReplies,onQuickRepliesChange:e=>Se(t=>({...t,quickReplies:e})),quickRepliesOpen:ce.quickRepliesOpen,onQuickRepliesOpenChange:e=>Se(t=>({...t,quickRepliesOpen:e})),renameTitle:q,respondingSessionIds:j,sendShortcut:ce.sendShortcut,skills:Ne,uploadBusy:ze,detailsOpen:Me,t:ke,onApprovalModeChange:e=>{Ft(e)},onBrowseFiles:()=>{const e=ot?.cwd||M||pn;Ae("files"),Qe(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{qt(e)},onClearInterrupt:()=>{Dt("session.clearInterrupt")},onDraftChange:vt,onDetailsOpenChange:Te,onEffortChange:P,onExportActiveSession:()=>{Vt()},rewinding:je,onRewindMessage:e=>{Ce(e)},onFastModeChange:F,onRetryFailedSend:kt,onModelChange:N,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})},onInterrupt:Pt,onDismissError:()=>e.setErrorText(null),onRetry:()=>{Lt(),wt(ot?.agent??E,M)},onRenameSession:e=>{Bt(void 0,e)},onRenameTitleChange:O,onRemoveAttachment:e=>$e(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{wt(ot?.agent??E,M)},onSubmit:Rt,onSendQuickReply:Et,onToggleArchived:()=>{Ht()},onTogglePinned:()=>{zt()},onUploadFiles:Ke,onViewChanges:C})}),n.jsxs(Hd,{collapsed:he,t:ke,value:Re,showSession:!1,onChange:Ee,onResize:ve("right"),children:[n.jsx("div",{hidden:"files"!==Re,style:{display:"files"===Re?"contents":"none"},children:n.jsx(t.Suspense,{fallback:n.jsx(id,{t:ke}),children:n.jsx(td,{client:"connected"===m?p.current:null,watch:!he&&"files"===Re,onRefreshDirectory:()=>Qe(He.path,{background:!0}),busy:Ie,cwd:M,directory:He,onLoadChildren:Je,newDirName:Be,remoteFile:We,t:ke,onCreateDirectory:()=>{Ze()},onListDirectory:e=>{Qe(e,{updateRoute:!0})},onNewDirNameChange:Ue,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})}},y?.daemonId)})}),a?n.jsxs("div",{hidden:"terminal"!==Re,className:"terminal-tab-content",children:[n.jsx(Fl,{location:"right",kind:"terminal",t:ke,cwd:M===pn?He.path:M}),n.jsx(Ol,{location:"right",kind:"terminal"})]}):null,i?n.jsxs("div",{hidden:"browser"!==Re,className:"browser-tab-content",children:[n.jsx(Fl,{location:"right",kind:"browser",t:ke}),n.jsx(Ol,{location:"right",kind:"browser"})]}):null,"admin"===Re?n.jsxs(t.Suspense,{fallback:n.jsx(id,{t:ke}),children:[n.jsx(nd,{language:$.language,t:ke,onLanguageChange:we}),!r().settingsTarget&&n.jsx(Nd,{}),n.jsx(sd,{t:ke,theme:$.theme,onThemeChange:xe}),n.jsx(rd,{notificationsBlocked:nn,permission:Fe,settings:Le,t:ke,onToggleEnabled:Gt}),!r().settingsTarget&&n.jsx(ed,{workspace:e})]}):null]})]}),r().settingsTarget&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(ed,{workspace:e,portalOnly:!0})}),n.jsx("div",{className:"workspace-header-actions",children:n.jsx(jr,{client:"connected"===m?p.current:null,activeSession:ot,busy:Ie,controlsOpen:!he,pendingCount:Ye,t:ke,onOpenControls:u,onRefreshSessions:()=>{bt({force:!0})},onRestoreSnapshot:()=>{yt()},onToggleArchived:()=>{Ht()},onTogglePinned:()=>{zt()},onViewChanges:C})}),n.jsx(t.Suspense,{fallback:null,children:n.jsx(au,{activeApproval:rt,activeQuestion:it,pendingCount:Ye,requestKey:vo(e.pendingApprovals,e.pendingQuestions),sessions:b,busy:Ie,errorText:v,questionAnswers:R,t:ke,onCancelQuestion:()=>{At()},onQuestionChoice:Nt,onRespondApproval:e=>{Mt(e)},onRespondQuestion:()=>{Tt()},onDismissRequest:(t,n,s)=>{"approval"===t?e.setPendingApprovals(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t}):e.setPendingQuestions(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t})},onClearRequests:()=>{e.setPendingApprovals({}),e.setPendingQuestions({})}},s.revealKey)}),n.jsx(Nl,{}),n.jsx(Ul,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:Ae,onCloseRight:()=>fe(!0),client:"connected"===m?p.current:null,daemonId:y?.daemonId,pairing:y,deviceName:y?.displayName??"",controlTab:Re,rightVisible:!he,t:ke}),n.jsx(od,{activeSession:ot,client:p.current,close:()=>C(null),id:I,sessions:b,t:ke})]})}const lu=Object.freeze(Object.defineProperty({__proto__:null,App:function(){const e=function(){const e=function(){const e=function(){const e=t.useRef(null),n=t.useRef(async()=>{}),s=t.useRef(null),[r]=t.useState(()=>({permission:vt(),notifications:gt(),preferences:c(),drafts:ns(),targets:Bn()})),i=t.useRef(r.permission),o=t.useRef(r.notifications),l=t.useRef(r.preferences),d=t.useRef(r.drafts),u=t.useRef(r.targets),h=t.useRef(i.current),f=t.useRef(o.current),p=t.useRef(d.current),m=t.useRef(null),w=t.useRef(null),x=t.useRef(new Set),S=t.useRef(null),k=t.useRef(new Set),I=t.useRef(null),C=t.useRef(0),j=t.useRef(new Set),R=t.useRef({}),E=t.useRef(!1),[M,T]=t.useState("connecting"),[A,N]=t.useState(()=>b[a(l.current.language)].preparingVibeletWeb),[D,P]=t.useState(null),[L,F]=t.useState(null),[q,O]=t.useState([]),[_,$]=t.useState({}),[z,H]=t.useState({}),[B,U]=t.useState(),[W,K]=t.useState({}),[V,Q]=t.useState(),[G,J]=t.useState(null),Z=Ye(L?.daemonId,G),[X,Y]=t.useState(null),[ee,te]=t.useState(()=>new Set),[ne,se]=t.useState({}),[re,ie]=t.useState({}),[oe,ae]=t.useState({}),{pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he}=function(e){const n=t.useRef(new cr),s=t.useRef(e);s.current!==e&&(s.current=e,n.current=new cr);const[r,i]=t.useState({});return{pendingQueues:r,setPendingQueues:t.useCallback(e=>{i(t=>n.current.snapshot("function"==typeof e?e(t):e))},[]),setLivePendingQueue:t.useCallback((e,t)=>{i(s=>n.current.live(s,e,t))},[]),remapPendingQueue:t.useCallback((e,t)=>{n.current.remap(e,t)},[]),confirmPendingQueueRemoval:t.useCallback((e,t)=>{i(s=>(n.current.confirmRemoval(e,t),n.current.snapshot(s)))},[])}}(L?.daemonId),[fe,pe]=t.useState("claude"),[me,ge]=t.useState(pn),[ve,ye]=t.useState(mn),[be]=t.useState(!1),[we,xe]=t.useState(""),[Se,ke]=t.useState(""),[Ie,Ce]=t.useState(!1),[je,Re]=t.useState(""),[Ee,Me]=t.useState(d.current),[Te,Ae]=t.useState(()=>is(d.current,null)),{webPreferences:Ne,sessionSort:De,setSessionSort:Pe,setRightSidebarCollapsed:Le,search:Fe,setSearch:qe,sinceFilter:Oe,setSinceFilter:_e,hideArchived:$e,setHideArchived:ze,groupFolders:He,setGroupFolders:Be,showNeedsAttentionGroup:Ue,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Ve,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ge,collapsedFolders:Je,setCollapsedFolders:Xe,sessionAgentFilter:et,setSessionAgentFilter:tt,directoryTags:nt,archiveSyncedDaemonIds:st,archiveSyncCardDismissedDaemonIds:rt,composerPreferences:it,savedTargets:ot,setSavedTargets:at,leftSidebarCollapsed:ct,setLeftSidebarCollapsed:lt,rightSidebarCollapsed:dt,workspaceClassName:ut,wideMainClassName:ht,workspaceStyle:ft,beginPaneResize:pt,applyBrowserDefaultWidth:mt,commitSearch:yt,saveTargets:bt,setLanguagePreference:wt,setThemePreference:xt,updateSessionListPreferences:St,updateComposerPreferences:kt}=function(e,n,s="default"){const[r,i]=t.useState(e);t.useEffect(()=>{const e=()=>{const e=c();i(t=>({...t,theme:e.theme,language:e.language,composer:e.composer}))};return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]);const[o,a]=t.useState(e.sessionList.sortOrder),[l,d]=t.useState(""),[u,h]=t.useState(e.sessionList.searchHistory),[f,p]=t.useState(e.sessionList.sinceFilter),[m,y]=t.useState(e.sessionList.hideArchived),[b,w]=t.useState(e.sessionList.groupFolders),[x,S]=t.useState(e.sessionList.showNeedsAttentionGroup),[k,I]=t.useState(e.sessionList.showRunningGroup),[C,j]=t.useState(e.sessionList.separatePinnedGroup),[R,E]=t.useState(e.sessionList.collapsedFolders),[M,T]=t.useState(e.sessionList.agentFilter),[A,N]=t.useState(n),[D,P]=t.useState(e.layout.leftSidebarCollapsed),[L,F]=t.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:q,rightPaneWidth:O,beginPaneResize:_,applyBrowserDefaultWidth:$}=function(e,n,s="default"){const[r,i]=t.useState(288),[o,a]=Ze(s,"third"),[c,l]=t.useState(()=>window.innerWidth),[d,u]=t.useState(null);t.useEffect(()=>{const e=document.querySelector(".workspace .wide-main");if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>u(e.getBoundingClientRect().width);t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s]);const h=d??c-(e?0:r+10),f="number"==typeof o?o:Math.round(h/("half"===o?2:3)),p=t.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),m=t.useRef(null);t.useEffect(()=>()=>m.current?.(),[e,n,s]),t.useEffect(()=>{const e=()=>l(window.innerWidth);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const g=function(e,t){const n=e.leftCollapsed?0:e.leftPaneWidth,s=e.rightCollapsed?0:e.rightPaneWidth,r=n+s,i=r>t?Math.max(0,t)/r:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*i),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(s*i)}}({leftCollapsed:e,rightCollapsed:n,leftPaneWidth:r,rightPaneWidth:f},c-96-64),v=t.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),m.current?.();const n=t.currentTarget,s=t.pointerId;let r=!0;const o=document.createElement("div");o.dataset.paneResizeShield="",o.setAttribute("aria-hidden","true"),Object.assign(o.style,{position:"fixed",inset:"0",zIndex:"2147483647",cursor:"col-resize",touchAction:"none"}),document.body.append(o);const c=t.clientX,l="left"===e?g.leftPaneWidth:g.rightPaneWidth,d=t.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),u=l+Math.max(0,(d?.getBoundingClientRect().width??0)-96),h=t=>{if(t.pointerId!==s)return;if(!(1&t.buttons))return void f();const n=(t.clientX-c)*("left"===e?1:-1),r=function(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}(l+n,"left"===e?252:234,u);"left"===e?i(r):a(r)},f=()=>{if(r){r=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",p,!0),window.removeEventListener("pointercancel",p,!0),window.removeEventListener("blur",f),window.removeEventListener("keydown",v,!0),document.removeEventListener("visibilitychange",y),n.removeEventListener("lostpointercapture",p);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}m.current===f&&(m.current=null)}},p=e=>{e.pointerId===s&&f()},v=e=>{"Escape"===e.key&&(e.preventDefault(),f())},y=()=>{"hidden"===document.visibilityState&&f()};m.current=f,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",p,!0),window.addEventListener("pointercancel",p,!0),window.addEventListener("blur",f),window.addEventListener("keydown",v,!0),document.addEventListener("visibilitychange",y),n.addEventListener("lostpointercapture",p);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:v,applyBrowserDefaultWidth:p}}(D,L,s),z=r.sessionList.directoryTags,H=r.sessionList.archiveSyncedDaemonIds,B=r.sessionList.archiveSyncCardDismissedDaemonIds,U=r.composer,W=function(e){return{workspaceClassName:["workspace",e.leftCollapsed&&"left-sidebar-collapsed"].filter(Boolean).join(" "),wideMainClassName:["wide-main",e.rightCollapsed&&"right-sidebar-collapsed"].filter(Boolean).join(" "),style:{"--left-pane-width":`${e.leftPaneWidth}px`,"--right-pane-width":`${e.rightPaneWidth}px`}}}({leftCollapsed:D,rightCollapsed:L,leftPaneWidth:q,rightPaneWidth:O});t.useEffect(()=>{i(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:o,sinceFilter:f,hideArchived:m,groupFolders:b,showNeedsAttentionGroup:x,showRunningGroup:k,separatePinnedGroup:C,collapsedFolders:R,agentFilter:M},layout:{...e.layout,leftSidebarCollapsed:D,rightSidebarCollapsed:L}};return g(t),t})},[R,b,m,D,L,u,C,M,x,k,f,o]);const K=t.useCallback(()=>{h(e=>v(e,l))},[l]),V=t.useCallback(e=>{N(e),Un(e)},[]),Q=t.useCallback(e=>{i(t=>{const n={...t,language:e};return g(n),n})},[]),G=t.useCallback(e=>{i(t=>{const n={...t,theme:e};return g(n),n})},[]),J=t.useCallback(e=>{i(t=>{const n={...t,sessionList:e(t.sessionList)};return g(n),n})},[]),Z=t.useCallback(e=>{i(t=>{const n={...t,composer:e(t.composer)};return g(n),n})},[]);return{webPreferences:r,sessionSort:o,setSessionSort:a,search:l,setSearch:d,sinceFilter:f,setSinceFilter:p,hideArchived:m,setHideArchived:y,groupFolders:b,setGroupFolders:w,showNeedsAttentionGroup:x,setShowNeedsAttentionGroup:S,showRunningGroup:k,setShowRunningGroup:I,separatePinnedGroup:C,setSeparatePinnedGroup:j,collapsedFolders:R,setCollapsedFolders:E,sessionAgentFilter:M,setSessionAgentFilter:T,directoryTags:z,archiveSyncedDaemonIds:H,archiveSyncCardDismissedDaemonIds:B,composerPreferences:U,savedTargets:A,setSavedTargets:N,leftSidebarCollapsed:D,setLeftSidebarCollapsed:P,rightSidebarCollapsed:L,setRightSidebarCollapsed:F,workspaceClassName:W.workspaceClassName,wideMainClassName:W.wideMainClassName,workspaceStyle:W.style,beginPaneResize:_,applyBrowserDefaultWidth:$,commitSearch:K,saveTargets:V,setLanguagePreference:Q,setThemePreference:G,updateSessionListPreferences:J,updateComposerPreferences:Z}}(l.current,u.current,Z),It=a(Ne.language),Ct=b[It],[jt,Rt]=Ze(Z,!1),[Et,Mt]=Ze(Z,!1),[Tt,At]=Ze(Z,"files"),[Nt,Dt]=t.useState(!1);!function(e){t.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>y(e,document.documentElement,t.matches);if(n(),"system"===e)return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}(Ne.theme);const Pt=t.useCallback(e=>{At(e),Le(!1)},[At,Le]),[Lt,Ft]=t.useState({}),[qt,Ot]=t.useState({}),[_t,$t]=t.useState([]),[zt,Ht]=t.useState({statusText:"",loading:!1,action:null}),[Bt,Ut]=t.useState(Wn),[Wt,Kt]=t.useState(o.current),[Vt,Qt]=t.useState(i.current),[Gt,Jt]=t.useState(null),[Zt,Xt]=t.useState(null);return{clientRef:e,connectWithPairingRef:n,activeSessionIdRef:s,initialNotificationPermissionRef:i,initialNotificationSettingsRef:o,initialPreferencesRef:l,initialComposerDraftsRef:d,initialSavedTargetsRef:u,notificationPermissionRef:h,notificationSettingsRef:f,composerDraftsRef:p,lastHistorySessionIdRef:m,historyCacheDaemonIdRef:w,historyPrefetchingSessionIdsRef:x,pairingRef:S,notifiedEventsRef:k,reconnectTimerRef:I,connectionAttemptIdRef:C,respondingSessionsRef:j,turnNotificationCountsRef:R,intentionalDisconnectRef:E,phase:M,setPhase:T,statusText:A,setStatusText:N,errorText:D?ar(D,Ct.remoteDirectConnection,Ct.localConnection):null,setErrorText:P,pairing:L,setPairing:F,sessions:q,setSessions:O,pendingSessions:_,setPendingSessions:$,optimisticSessions:z,setOptimisticSessions:H,nextCursor:B,setNextCursor:U,folderCounts:W,setFolderCounts:K,inventoryVersion:V,setInventoryVersion:Q,activeSessionId:G,setActiveSessionId:J,diffSessionId:X,setDiffSessionId:Y,respondingSessions:ee,setRespondingSessions:te,pendingApprovals:ne,setPendingApprovals:se,pendingQuestions:re,setPendingQuestions:ie,questionAnswers:oe,setQuestionAnswers:ae,pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he,agent:fe,setAgent:pe,cwd:me,setCwd:ge,approvalMode:ve,setApprovalMode:ye,continueSession:be,model:we,setModel:xe,effort:Se,setEffort:ke,fastMode:Ie,setFastMode:Ce,renameTitle:je,setRenameTitle:Re,composerDrafts:Ee,setComposerDrafts:Me,draft:Te,setDraft:Ae,webPreferences:Ne,sessionSort:De,setSessionSort:Pe,search:Fe,setSearch:qe,sinceFilter:Oe,setSinceFilter:_e,hideArchived:$e,setHideArchived:ze,groupFolders:He,setGroupFolders:Be,showNeedsAttentionGroup:Ue,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Ve,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ge,collapsedFolders:Je,setCollapsedFolders:Xe,sessionAgentFilter:et,setSessionAgentFilter:tt,directoryTags:nt,archiveSyncedDaemonIds:st,archiveSyncCardDismissedDaemonIds:rt,composerPreferences:it,savedTargets:ot,setSavedTargets:at,leftSidebarCollapsed:ct,setLeftSidebarCollapsed:lt,rightSidebarCollapsed:dt,setRightSidebarCollapsed:Le,workspaceClassName:ut,wideMainClassName:ht,workspaceStyle:ft,beginPaneResize:pt,applyBrowserDefaultWidth:mt,commitSearch:yt,saveTargets:bt,setLanguagePreference:wt,setThemePreference:xt,updateSessionListPreferences:St,updateComposerPreferences:kt,language:It,t:Ct,busy:jt,setBusy:Rt,rewinding:Et,setRewinding:Mt,controlTab:Tt,setControlTab:At,detailsOpen:Nt,setDetailsOpen:Dt,setControlTabAndOpen:Pt,modelOptions:Lt,setModelOptions:Ft,usageLimits:qt,setUsageLimits:Ot,skills:_t,setSkills:$t,admin:zt,setAdmin:Ht,daemonMetadata:Bt,setDaemonMetadata:Ut,notificationSettings:Wt,setNotificationSettings:Kt,notificationPermission:Vt,setNotificationPermission:Qt,archiveSyncBusy:Gt,setArchiveSyncBusy:Jt,archiveSyncStatus:Zt,setArchiveSyncStatus:Xt}}(),n=function(e){return{showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup,separatePinnedGroup:e.separatePinnedGroup,toggleSessionViewGroup:async t=>{("needsAttention"===t?e.setShowNeedsAttentionGroup:"running"===t?e.setShowRunningGroup:e.setSeparatePinnedGroup)(e=>!e)}}}(e),{clientRef:r,activeSessionIdRef:i,notificationPermissionRef:d,notificationSettingsRef:u,composerDraftsRef:h,lastHistorySessionIdRef:f,historyPrefetchingSessionIdsRef:p,pairingRef:k,reconnectTimerRef:I,respondingSessionsRef:C,phase:j,setStatusText:R,setErrorText:E,pairing:M,setSessions:T,setOptimisticSessions:A,setNextCursor:N,setFolderCounts:D,setInventoryVersion:P,activeSessionId:L,setActiveSessionId:F,respondingSessions:q,setRespondingSessions:O,pendingApprovals:_,setPendingApprovals:$,pendingQuestions:z,setPendingQuestions:H,setQuestionAnswers:B,pendingQueues:U,setPendingQueues:W,agent:K,setAgent:V,cwd:Q,setCwd:G,setApprovalMode:J,composerDrafts:Z,setComposerDrafts:X,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,setRightSidebarCollapsed:se,t:re,controlTab:ie,setControlTab:oe,setControlTabAndOpen:ae,modelOptions:ce,setModelOptions:le,usageLimits:de,setUsageLimits:ue,setSkills:he,setDaemonMetadata:fe,notificationSettings:pe,setNotificationSettings:me,notificationPermission:ge,setNotificationPermission:ve,sessions:ye,pendingSessions:be,optimisticSessions:we,setDraft:xe,setBusy:Se}=e,ke=function(e){const{clientRef:n,pairing:s,cwd:r,phase:i,controlTab:o,setControlTab:a,setBusy:c,setErrorText:l,t:d,scopeKey:u="default"}=e,h=t.useRef(!1),f=t.useRef(null),p=f.current&&et(f.current.key,u)?f.current:null,{value:m,set:g,setForScope:v,resolveScope:y,getAll:b}=Xe(u,()=>[]),w=t.useCallback((e,t)=>{v(Ye(s?.daemonId,e),t)},[s?.daemonId,v]);t.useEffect(()=>Qs(()=>[...b().values()].some(e=>e.length>0)),[b]);const[x,S]=t.useState(!1),k=t.useRef(new Map);t.useEffect(()=>{const e=new Set(m.map(e=>e.path));for(const[t,n]of k.current)(null===y(n.scope)||y(n.scope)===y(u)&&![...n.paths].some(t=>e.has(t)))&&(t.abort(),k.current.delete(t));S(k.current.size>0)},[m,u,y]);const[I,C]=Ze(u,()=>({path:p?.directory.path||!h.current&&(qs().folder||qs().cwd)||r||pn,entries:[],loading:!1,loaded:!1})),[j,R]=Ze(u,""),{remoteFile:E,setRemoteFile:M,openFiles:T,setOpenFiles:A,acknowledgeSave:N}=function(e,n,s){const r=t.useRef(null),i=r.current&&et(r.current.scope,e)?r.current:null,{value:o,set:a,getAll:c,updateAll:l}=Xe(e,()=>i?.value??(s?{current:Ys(s),files:{[Ys(s)]:s}}:{current:null,files:{}}));r.current={scope:e,value:o},t.useEffect(()=>{i&&l((e,t)=>t===i.scope?{current:null,files:{}}:e)},[e]),t.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of c())if(null===Je(n,{...t,action:"remove"})&&Object.values(s.files).some(e=>e.dirty))return void e.preventDefault()};return window.addEventListener(Ke,e),()=>window.removeEventListener(Ke,e)},[c]),t.useEffect(()=>Qs(()=>[...c().values()].some(e=>Object.values(e.files).some(e=>e.dirty))),[c]);const d=t.useRef(new Set);t.useEffect(()=>{const e=new Set([...c().values()].flatMap(e=>Object.values(e.files).flatMap(e=>e.objectUrl?[e.objectUrl]:[])));for(const t of d.current)e.has(t)||URL.revokeObjectURL(t);d.current=e}),t.useEffect(()=>()=>{for(const e of d.current)URL.revokeObjectURL(e)},[]);const u=t.useCallback(e=>{a(t=>{const n=t.current?t.files[t.current]??null:null,s="function"==typeof e?e(n):e;if(!s)return null===t.current?t:{...t,current:null};const r=Ys(s),i=t.files[r],o=i?.dirty&&!s.dirty?i:s;return t.current===r&&i===o?t:{current:r,files:{...t.files,[r]:o}}})},[a]),h=t.useCallback(e=>{a(t=>{const n="function"==typeof e?e(t.files):e;return n===t.files?t:{current:t.current&&n[t.current]?t.current:null,files:n}})},[a]),f=t.useCallback((e,t)=>{a(n=>{const s=Ys(e),r=n.files[s];if(!r)return n;const i=function(e,t,n){return e&&e.path===t.path&&e.cwd===t.cwd&&e.etag===t.etag?{...e,dirty:e.text!==t.text,etag:"string"==typeof n.etag?n.etag:e.etag,lastModified:"string"==typeof n.lastModified?n.lastModified:e.lastModified,size:"number"==typeof n.size?n.size:e.size}:e}(r,e,t);return i!==r&&i?{...n,files:{...n.files,[s]:i}}:n})},[a]);return t.useEffect(()=>{const t=(t,s)=>{if(t===e)return n===s;try{return JSON.parse(t)[0]===s}catch{return!1}},s=e=>"move"===e.action||"delete"===e.action,r=(e,t)=>lt(Ys(e),t.source??t.path,t.cwd),i=e=>{const{detail:n}=e;if(s(n))for(const[s,i]of c())if(t(s,n.daemonId)&&Object.values(i.files).some(e=>e.dirty&&r(e,n)))return void e.preventDefault()},o=e=>{const{detail:i}=e;if(!s(i))return;const o=ct(i.source??i.path,i.cwd),a=e=>`${ct(i.target,i.cwd)}${e.slice(o.length)}`;if(l((e,n)=>{if(!t(n,i.daemonId))return e;let s=e.current,o=!1;const c={};for(const[t,l]of Object.entries(e.files)){if(!r(l,i)){c[t]=l;continue}o=!0;const e="delete"===i.action?null:{...l,path:a(Ys(l))},n=e&&Ys(e);t===s&&(s=n),e&&n&&(c[n]=e)}return o?{current:s,files:c}:e}),n!==i.daemonId)return;const c=new URL(window.location.href),d=c.searchParams.get("file");d&&lt(d,o,c.searchParams.get("cwd")??i.cwd)&&("delete"===i.action?c.searchParams.delete("file"):c.searchParams.set("file",a(ct(d,c.searchParams.get("cwd")??i.cwd))),window.history.replaceState(null,"",c.href))};return window.addEventListener(ot,i),window.addEventListener(at,o),()=>{window.removeEventListener(ot,i),window.removeEventListener(at,o)}},[e,n,c,l]),{remoteFile:o.current?o.files[o.current]??null:null,setRemoteFile:u,openFiles:o.files,setOpenFiles:h,acknowledgeSave:f}}(u,s?.daemonId,p?.file),[D,P]=Ze(u,()=>new Set);f.current={key:u,file:E,directory:I};const L=e=>JSON.stringify([e.cwd,e.path,e.etag]),F=!!E&&D.has(L(E)),q=t.useRef(new Map),O=t.useRef(null);t.useEffect(()=>{C(e=>({...e,loaded:!1,loading:!1}))},[u]);const _=t.useRef(0),$=t.useRef(I.path);t.useEffect(()=>()=>{if(f.current&&et(u,f.current.key)&&!f.current.file&&qs().file&&(h.current=!1),_.current++,C(e=>e.loading?{...e,loading:!1}:e),y(u)!==y(f.current?.key??"")){O.current?.abort();for(const e of k.current.keys())e.abort();k.current.clear(),S(!1)}},[u]),t.useEffect(()=>{$.current!==I.path&&(_.current++,$.current=I.path)},[I.path]),t.useEffect(()=>(_.current++,C(e=>({...e,loading:!1,loaded:!1})),S(!1),()=>{_.current++;for(const e of k.current.keys())e.abort();k.current.clear(),O.current?.abort();for(const e of q.current.values())e.request.abort(),e.finish()}),[s?.pairToken]),t.useEffect(()=>{I.path!==pn||qs().folder||(_.current++,C(e=>({...e,entries:[],loaded:!1,loading:!1})))},[r]);const z=t.useCallback(async e=>{if(!e?.length||!s)return;const t=new AbortController;S(!0),l(null);const n=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));k.current.set(t,{scope:u,paths:new Set(n.map(e=>e.path))}),g(e=>[...e,...n.map(({file:e,path:t})=>({path:t,name:e.name,type:e.type,size:e.size,uploading:!0}))]);try{await async function(e,t,n,s,r){let i=0;const o=[];if(await Promise.all(Array.from({length:Math.min(2,e.length)},async function(){for(;!n.aborted&&i<e.length;){const c=e[i++];try{const e=await Js(c.file,t,n,s);n.aborted||r(c,e)}catch(a){o.push(a)}}})),!n.aborted&&o.length)throw o[0]}(n,s.pairToken,t.signal,d,({path:e},t)=>{g(n=>n.map(n=>n.path===e?t:n))})}catch(r){t.signal.aborted||l(r instanceof Error?r.message:String(r))}finally{const e=new Set(n.map(e=>e.path));g(t=>t.filter(t=>!e.has(t.path)));for(const t of e)URL.revokeObjectURL(t);k.current.delete(t)&&S(k.current.size>0)}},[s,l,d.uploadFailed,d.uploadPathMissing,u]),H=t.useCallback(async(e,t,n)=>{if(!s)return;O.current?.abort();const r=new AbortController;O.current=r,l(null);try{const i=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),o=await fetch(i?e:Dn(e,t),{headers:i?{}:{authorization:`Bearer ${s.pairToken}`},signal:r.signal});if(!o.ok)throw new Error(await o.text().catch(()=>d.fileOpenFailed)||d.fileOpenFailed);const a=o.headers.get("content-type")??"application/octet-stream";if(i&&!a.startsWith("image/"))throw new Error(d.fileOpenFailed);const c=Zs(e,a,!1),l=await o.blob(),u="html"===c||"unsupported"===c&&function(e,t){return!!t.startsWith("text/")||!!(t.includes("json")||t.includes("xml")||t.includes("javascript"))||/\.(md|txt|json|ya?ml|toml|csv|log|ts|tsx|js|jsx|css|html|xml|py|rb|go|rs|java|kt|swift|sh|zsh|bash)$/i.test(e)}(e,a)?await l.text():"unsupported"===c?function(e){const t=new Uint8Array(e);if(!t.some(e=>e<32&&![9,10,12,13].includes(e)||127===e))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}(await l.arrayBuffer()):void 0;if(r.signal.aborted)return;if(void 0!==u)M({path:e,cwd:t,kind:"text",contentType:a,text:u,etag:Pn(o.headers,"etag"),lastModified:Pn(o.headers,"last-modified"),size:Number(o.headers.get("content-length"))||void 0,dirty:!1});else{const n="pdf"===Zs(e,a,!1)?new Blob([l],{type:"application/pdf"}):l;M({path:e,cwd:t,kind:Nn(e,a)?"image":"binary",contentType:a,text:"",objectUrl:URL.createObjectURL(n),etag:Pn(o.headers,"etag"),lastModified:Pn(o.headers,"last-modified"),size:l.size,dirty:!1})}n?.updateRoute&&Os({file:e,...t?{cwd:t}:{}},{replace:n.replaceRoute})}catch(i){if(r.signal.aborted)return;l(i instanceof Error?i.message:String(i))}},[s,l,u]),B=t.useCallback(async e=>{if(!s||!E||"text"!==E.kind||q.current.has(u))return;const t=new AbortController,n={request:t,finish:()=>{q.current.get(u)===n&&(q.current.delete(u),c(!1))}};q.current.set(u,n),c(!0),l(null);try{const n=await fetch(Dn(E.path,E.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${s.pairToken}`,"content-type":"text/markdown; charset=utf-8",...E.etag&&!e?.force?{"if-match":E.etag}:{}},body:E.text});if(t.signal.aborted)return;if(!n.ok){if(409===n.status)throw P(e=>new Set(e).add(L(E))),new Error(d.remoteFileConflict(E.path));throw new Error(await n.text().catch(()=>d.fileSaveFailed)||d.fileSaveFailed)}const r=await n.json().catch(()=>null);if(t.signal.aborted)return;if(!r||"object"!=typeof r||!("etag"in r)||"string"!=typeof r.etag||!r.etag.trim())throw new Error(d.fileSaveFailed);P(e=>{const t=new Set(e);return t.delete(L(E)),t}),N(E,r)}catch(r){t.signal.aborted||f.current?.key!==u||l(r instanceof Error?r.message:String(r))}finally{n.finish()}},[s,E,c,l,u,N]),U=t.useCallback(async()=>{if(s&&E)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(E.path),t=await fetch(e?E.path:Dn(E.path,E.cwd),{headers:e?{}:{authorization:`Bearer ${s.pairToken}`}});if(!t.ok)throw new Error(d.downloadFailed);const n=URL.createObjectURL(await t.blob()),r=document.createElement("a");r.href=n,r.download=wn(E.path),r.click(),URL.revokeObjectURL(n)}catch(e){l(e instanceof Error?e.message:String(e))}},[s,E,l,u]),W=t.useCallback(async(e=I.path,t)=>{const s=n.current;if(!s?.isConnected)return;if(t?.background&&$.current!==e)return;$.current=e;const i=++_.current;t?.background||C(t=>({...t,path:e,entries:e===t.path?t.entries:[],loading:!0,loaded:!1,error:void 0}));try{const n=await s.request({action:"dirs.list",id:s.makeId("dirs"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut});if(i!==_.current)return;C({path:e,entries:n.entries??[],loading:!1,loaded:!0}),t?.updateRoute&&Os({folder:e},{replace:t.replaceRoute})}catch(o){if(i!==_.current)return;C(e=>({...e,loading:!1,loaded:!0,error:o instanceof Error?o.message:String(o)}))}},[n,r,I.path,u]),K=t.useCallback(async e=>{const t=n.current;if(!t?.isConnected)throw new Error(d.webSocketNotConnected);return(await t.request({action:"dirs.list",id:t.makeId("dirs"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut})).entries??[]},[n,r,u]),V=t.useCallback(async e=>(await K(e)).filter(e=>e.isDirectory),[K]);t.useEffect(()=>{!h.current||"files"!==o||"connected"!==i||I.loading||I.loaded||W(I.path||r||pn)},[o,r,I.loaded,I.loading,I.path,W,i]),t.useEffect(()=>{if("connected"!==i||h.current)return;const e=qs();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void W(e.folder,{updateRoute:!1});e.file&&(e.cwd&&C(t=>({...t,path:e.cwd,loaded:!1})),H(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[W,H,i,a]);const Q=t.useCallback(async()=>{const e=n.current;if(e?.isConnected&&0!==j.trim().length){c(!0),l(null);try{await e.request({action:"dirs.create",id:e.makeId("mkdir"),path:Tn(I.path,j),cwd:r||void 0}),R(""),await W(I.path)}catch(t){l(t instanceof Error?t.message:String(t))}finally{c(!1)}}},[n,r,I.path,W,j,c,l,u]),G=t.useCallback(async e=>{const t=n.current;if(!t?.isConnected)throw new Error(d.webSocketNotConnected);await t.request({action:"dirs.create",id:t.makeId("mkdir"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryCreationTimedOut})},[n,r,u]);return{attachments:m,setAttachments:g,setSessionAttachments:w,uploadBusy:x,directory:I,setDirectory:C,newDirName:j,setNewDirName:R,remoteFile:E,setRemoteFile:M,openFiles:T,setOpenFiles:A,remoteFileConflict:F,uploadFiles:z,openRemoteFile:H,saveRemoteFile:B,downloadRemoteFile:U,listDirectory:W,listSessionDirectories:V,listFileTreeDirectory:K,createDirectory:Q,createSessionDirectory:G}}({scopeKey:Ye(M?.daemonId,L),clientRef:r,pairing:M,cwd:Q,phase:j,controlTab:ie,setControlTab:ae,setBusy:Se,setErrorText:E,t:re}),Ie=Object.keys(_).length+Object.keys(z).length,Ce=function(e,t,n){return"codex"===n&&/^pending_(?:local_)?\d+(?:_\d+)?$/.test(t??"")?e.map(e=>void 0===e.waitingForStartup?{...e,waitingForStartup:!0}:e):e}(L?U[L]??[]:[],L,K),je=ce[K]??[],Re=de[K],{completionAttention:Ee,reviewSessionIds:Me}=function(e,n,s){const r=t.useMemo(()=>{let t;try{t=window.localStorage}catch{}return new Ws(t,`vibelet:completion-attention:${e??"disconnected"}`,Ks)},[e]),i=t.useSyncExternalStore(r.subscribe,r.getSnapshot),o=t.useRef(new Set);return t.useEffect(()=>{o.current=new Set},[r]),t.useEffect(()=>{for(const e of n)r.reconcile(e.sessionId,Boolean(e.runtime.isResponding))},[r,n]),t.useEffect(()=>{for(const e of s)o.current.has(e)||r.observe(e);o.current=s},[r,s]),t.useEffect(()=>{if(!i.size)return;const e=window.setInterval(r.acknowledgeVisible,250);return window.addEventListener("focus",r.acknowledgeVisible),document.addEventListener("visibilitychange",r.acknowledgeVisible),()=>{window.clearInterval(e),window.removeEventListener("focus",r.acknowledgeVisible),document.removeEventListener("visibilitychange",r.acknowledgeVisible)}},[r,i]),{completionAttention:r,reviewSessionIds:i}}(M?.daemonId,ye,q),{historyCacheRef:Te,historyPageStartRef:Ae,hydrateVisibleHistory:Ne,messagesSessionIdRef:De,remapCachedHistory:Pe,appendCachedDelta:Le,appendCachedHistory:Fe,appendInfoMessage:qe,clearHistoryLoading:Oe,ensureCachedHistoryEntry:_e,setCachedMessageDelivery:$e,removeCachedMessage:ze,resolveCachedMessageSession:He,historyLoading:Be,hasOlderHistory:Ue,olderHistoryLoading:We,messages:Ve,mergeCachedHistoryPage:Ge,removeCachedHistory:tt,renderCachedHistory:nt,replaceCachedHistory:st,requestHistory:rt,setMessages:it}=function(e){const n=t.useRef({}),s=function(e){return t.useMemo(()=>{const t=new Map,n=t=>JSON.stringify([e?.current??null,t]);return{has:(e,s)=>t.get(n(e))?.has(s)??!1,add:(e,s)=>{const r=t.get(n(e))??new Set;r.add(s),t.set(n(e),r)},filter:(e,s)=>{const r=t.get(n(e));return s.filter(e=>{if("user"!==e.role)return!0;const t=e.localClientMessageId??(e.historyKey?.startsWith("client:")?e.historyKey.slice(7):void 0);return!t||!r?.has(t)})},remap:(e,s)=>{const r=t.get(n(e));r&&(t.set(n(s),new Set([...t.get(n(s))??[],...r])),t.delete(n(e)))}}},[e])}(e.historyCacheDaemonIdRef),r=function(e,n){const s=t.useRef(new Map),r=t.useRef(new Set),i=t.useRef(null),o=e=>JSON.stringify([n?.current,e]),a=t.useCallback(()=>{i.current&&clearTimeout(i.current),i.current=null;for(const[e,t]of s.current)sr(e,t);s.current.clear()},[]);return t.useEffect(()=>(window.addEventListener("pagehide",a),window.addEventListener("beforeunload",a),()=>{a(),window.removeEventListener("pagehide",a),window.removeEventListener("beforeunload",a)}),[a]),{changed:t=>{const r=n?.current;r&&(s.current.set(r,{...s.current.get(r),[t]:e.current[t]}),i.current||(i.current=setTimeout(a,500)))},fresh:e=>r.current.delete(o(e)),isStale:e=>r.current.has(o(e)),restore:t=>{if(!n?.current||Object.hasOwn(e.current,t))return;const s=function(e,t){return nr().find(n=>n.daemonId===e&&n.sessionId===t)?.messages.map(yt)}(n.current,t);return s?(e.current={...e.current,[t]:s},r.current.add(o(t)),!0):void 0}}}(n,e.historyCacheDaemonIdRef),i=t.useRef(r);i.current=r;const o=t.useRef(null),a=t.useRef({}),c=t.useRef({}),l=t.useRef(new Map),[d,u]=t.useState(null),h=t.useRef(null),[f,p]=t.useState(!1),[m,g]=t.useState([]),v=t.useCallback(e=>!(e&&o.current&&o.current!==e||(o.current=null,p(!1),0)),[]),y=t.useCallback(t=>(i.current.restore(t)&&(delete a.current[t],delete c.current[t]),!!ls(n.current,t)&&(h.current=t,e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),g(n.current[t]??[]),!0)),[e.onDeliveryHistoryChanged]),b=t.useCallback((t,r,o)=>{n.current=function(e,t,n){return t?{...e,[t]:us(e[t]??[],n)}:e}(n.current,t,s.filter(t,r)),i.current.changed(t),i.current.fresh(t);const a=n.current[t]??[];for(const n of a)n.localClientMessageId&&n.localDelivery&&e.onDeliveryChanged?.(t,n.localClientMessageId,n.localDelivery);return e.onDeliveryHistoryChanged?.(t,a),!1!==o?.renderActive&&t===e.activeSessionIdRef.current&&(h.current=t,g(a)),a},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,s]),w=t.useCallback((t,s,r)=>{const i=l.current.get(t);i?.client===e.clientRef.current&&(void 0===i.before||r&&r.start<i.before)&&(i.received=!0),t===e.activeSessionIdRef.current&&e.setErrorText(t=>t===e.historyTimeoutMessage?null:t);const o=ls(n.current,t)?c.current[t]:void 0;if(c.current[t]=r,"byte"===r?.cursorMode){const e=function(e,t,n,s){if(!n||"byte"!==n.cursorMode)return[...t];if(s.start<n.start){const n=new Set(t.map(er).filter(Boolean));return[...t,...e.filter(e=>{const t=er(e);return!t||!n.has(t)})]}const r=t[0],i=r?e.findIndex(e=>r.historyKey&&e.historyKey?r.historyKey===e.historyKey:Boolean(r.timestamp)&&r.timestamp===e.timestamp&&r.role===e.role&&r.type===e.type&&r.content===e.content&&JSON.stringify(r.images)===JSON.stringify(e.images)&&r.toolName===e.toolName&&JSON.stringify(r.toolInput)===JSON.stringify(e.toolInput)):-1;return i>=0?[...e.slice(0,i),...t]:[...t]}(n.current[t]??[],s,o,r);return"byte"===o?.cursorMode&&e.length>s.length&&r.start>=o.start&&(c.current[t]={...r,start:o.start,hasMore:o.hasMore}),a.current[t]=c.current[t]?.start,b(t,e)}if(!r)return a.current[t]=void 0,b(t,s);const d=a.current[t],u=n.current[t]??[],h=r.start+s.length;if(void 0===d||h<d||r.start>d+u.length)return a.current[t]=r.start,b(t,s);a.current[t]=Math.min(d,r.start),c.current[t]={...r,start:Math.min(d,r.start),hasMore:Math.min(d,r.start)>0};const f=u.slice(0,Math.max(0,r.start-d)),p=u.slice(Math.max(0,h-d),Math.max(0,r.total-d));return b(t,[...f,...s,...p])},[b,e.clientRef,e.activeSessionIdRef,e.setErrorText,e.historyTimeoutMessage]),x=t.useCallback((e,t)=>{delete c.current[e],a.current[e]=0;const n=b(e,t,{renderActive:!1});h.current=e,g(n)},[b]),S=t.useCallback((t,r)=>{n.current=ds(n.current,t,s.filter(t,r)),i.current.changed(t),e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[]))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,s]),k=t.useCallback((t,r)=>{s.filter(t,[r]).length&&(n.current=function(e,t,n){return n.historyKey&&e[t]?.some(e=>e.historyKey===n.historyKey)?e:ds(e,t,[n])}(n.current,t,r),i.current.changed(t),e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[])))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,s]),I=t.useCallback((e,t)=>function(e,t,n){const s=e=>e?.some(e=>e.localClientMessageId===n||e.historyKey===`client:${n}`);return s(e[t])?t:Object.entries(e).find(([,e])=>s(e))?.[0]??t}(n.current,e,t),[]),C=t.useCallback((t,r,o,a)=>{if(t=I(t,r),s.has(t,r))return;if(!a&&!n.current[t]?.some(e=>e.localClientMessageId===r||e.historyKey===`client:${r}`))return;const c=function(e,t,n,s){const r=e.findIndex(e=>e.localClientMessageId===t||e.historyKey===`client:${t}`),i=e.slice();if(r<0)s&&i.push({role:"user",...s,timestamp:(new Date).toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const s=e[r],o="delivered"===s.localDelivery||"accepted"===s.delivery||s.historyKey&&!s.historyKey.startsWith("client:");i[r]={...s,localClientMessageId:t,localDelivery:o&&"failed"===n?"delivered":n}}return i}(n.current[t]??[],r,o,a);n.current={...n.current,[t]:c},i.current.changed(t),t!==e.activeSessionIdRef.current&&t!==h.current||(h.current=t,g(n.current[t]??[]));const l=c.find(e=>e.localClientMessageId===r)?.localDelivery;return l&&e.onDeliveryChanged?.(t,r,l),e.onDeliveryHistoryChanged?.(t,c),l},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,s]),j=t.useCallback((t,r)=>{t=I(t,r),s.add(t,r);const o=n.current[t];if(!o)return;const a=o.filter(e=>"user"!==e.role||e.localClientMessageId!==r&&e.historyKey!==`client:${r}`);a.length!==o.length&&(e.onDeliveryRemoved?.(t,r),e.onDeliveryHistoryChanged?.(t,a),n.current={...n.current,[t]:a},i.current.changed(t),t!==e.activeSessionIdRef.current&&t!==h.current||g(a))},[e.activeSessionIdRef,e.onDeliveryRemoved,e.onDeliveryHistoryChanged,I,s]),R=t.useCallback((t,s)=>{n.current=function(e,t,n){return t&&n?{...e,[t]:Rt(yn(e[t]??[],n))}:e}(n.current,t,s),i.current.changed(t),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[]))},[e.activeSessionIdRef,s]),E=t.useCallback((e,t)=>{S(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[S]),M=t.useCallback(e=>{n.current=function(e,t){if(!ls(e,t))return e;const n={...e};return delete n[t],n}(n.current,e),i.current.changed(e),delete a.current[e],delete c.current[e]},[]),T=t.useCallback((e,t)=>{s.remap(e,t),n.current=function(e,t,n){if(!t||!n||t===n||!ls(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}(n.current,e,t),i.current.changed(e),i.current.changed(t),a.current[t]=a.current[e],delete a.current[e],c.current[t]=c.current[e],delete c.current[e]},[s]),A=t.useCallback(async(t,{older:n=!1,refresh:s=!1}={})=>{const r=e.clientRef.current;if(!r?.isConnected)return;for(;l.current.get(t.sessionId)?.client===r;){if(!s)return;if(await l.current.get(t.sessionId).settled,e.clientRef.current!==r||!r.isConnected||e.activeSessionIdRef.current!==t.sessionId)return}const d=c.current[t.sessionId];if(n&&(!d?.hasMore||d.start<=0))return;let h;const f={client:r,received:!1,before:n?d?.start:void 0,settled:new Promise(e=>{h=e})};l.current.set(t.sessionId,f),n&&u(t.sessionId);const m=()=>e.clientRef.current===r,g=y(t.sessionId);g?v(t.sessionId):(o.current=t.sessionId,delete a.current[t.sessionId],p(!0),e.setErrorText(null));try{if(!n&&!s&&g&&!i.current.isStale(t.sessionId)){const n=await r.request({action:"reconnect.snapshot",id:r.makeId("snapshot"),activeSessionId:t.sessionId,activeAgent:t.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0});if(!m())return;const s=n.snapshot.activeSession;if(s?.sessionId===t.sessionId){e.setPendingQueues(e=>({...e,[t.sessionId]:s.pendingQueue??[]}));for(const e of s.acceptedClientMessageIds??[])C(t.sessionId,e,"delivered")}return}if(await r.request({action:"session.history",id:r.makeId("history"),sessionId:t.sessionId,agent:t.agent,limit:n?100:20,...n&&"byte"!==d?.cursorMode?{before:d?.start}:{pageMode:"cursor",...n?{beforeCursor:d?.start}:{}}},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:15e3}),!m())return}catch(b){!m()||e.activeSessionIdRef.current!==t.sessionId||b instanceof dn&&f.received||e.setErrorText(b instanceof Error?b.message:String(b))}finally{l.current.get(t.sessionId)===f&&l.current.delete(t.sessionId),h(),m()&&(n&&u(e=>e===t.sessionId?null:e),v(t.sessionId))}},[v,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,y,C]);return{hasOlderHistory:Boolean(c.current[e.activeSessionIdRef.current??""]?.hasMore),olderHistoryLoading:d===e.activeSessionIdRef.current&&null!==d,resolveCachedMessageSession:I,setCachedMessageDelivery:C,removeCachedMessage:j,appendCachedDelta:R,appendCachedHistory:S,appendInfoMessage:E,clearHistoryLoading:v,ensureCachedHistoryEntry:k,historyCacheRef:n,historyLoading:f,historyPageStartRef:a,hydrateVisibleHistory:x,messages:m,messagesSessionIdRef:h,mergeCachedHistoryPage:w,remapCachedHistory:T,removeCachedHistory:M,renderCachedHistory:y,replaceCachedHistory:b,requestHistory:A,setMessages:g}}({onDeliveryChanged:Ee.deliveryChanged,onDeliveryHistoryChanged:Ee.reconcileDeliveries,onDeliveryRemoved:Ee.deliveryRemoved,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:i,clientRef:r,historyTimeoutMessage:re.historyRequestTimedOut,setPendingQueues:W,setErrorText:E}),dt=t.useMemo(()=>new Set(Object.entries(Te.current).filter(([,e])=>Us(e)).map(([e])=>e)),[Te.current]),{activeSession:ut,activeApproval:ht,activeQuestion:ft,displaySessions:mt,groupedSessions:bt,pendingSessionIds:wt,visibleSessions:xt}=function(e){const n=t.useRef({protectedSessionIds:[]}),s=t.useMemo(()=>Cn(Cn(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),r=t.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),i=t.useMemo(()=>s.find(t=>t.sessionId===e.activeSessionId)??null,[e.activeSessionId,s]),a=(e.activeSessionId?e.pendingApprovals[e.activeSessionId]:null)??Object.values(e.pendingApprovals)[0]??null,c=(e.activeSessionId?e.pendingQuestions[e.activeSessionId]:null)??Object.values(e.pendingQuestions)[0]??null,d=t.useMemo(()=>l(function(e,t){return e.filter(e=>(!t.hideArchived||!e.archived)&&("all"===t.agentFilter||e.agent===t.agentFilter)&&function(e,t){const n=t.trim().toLowerCase();return!n||[o(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(e=>e.toLowerCase().includes(n))}(e,t.search))}(s,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated",!1),[s,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),u=t.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions),...e.reviewSessionIds??[],...e.failedSessionIds??[]]),[e.pendingApprovals,e.pendingQuestions,e.reviewSessionIds,e.failedSessionIds]),h=t.useMemo(()=>{if(e.search.trim()||"updated"!==(e.sessionSort??"updated"))return d;const t=function(e,t,n){if(0===e.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const s=new Map,r=[];for(const l of e)s.set(l.sessionId,l),(t[l.sessionId]||l.runtime.isResponding)&&r.push(l.sessionId);if(0===r.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const i=new Set(r),o=n.protectedSessionIds.filter(e=>s.has(e)&&i.has(e)),a=new Set(o);let c=o.length!==n.protectedSessionIds.length;for(const l of r)a.has(l)||(a.add(l),o.push(l),c=!0);return{sessions:Nt(e,o,s),state:c?{protectedSessionIds:o}:n}}(d,Object.fromEntries([...e.respondingSessionIds].map(e=>[e,!0])),n.current);return n.current=t.state,t.sessions},[d,e.respondingSessionIds,e.search,e.sessionSort]),f=t.useMemo(()=>Object.fromEntries(h.map((e,t)=>[e.sessionId,t])),[h]),p=t.useMemo(()=>[...l(h.filter(e=>e.pinned&&!e.archived),"updated"),...h.filter(e=>!e.pinned||e.archived)],[h]),g=t.useMemo(()=>m(function(e,t={}){const n=e=>Object.fromEntries(Array.from(e??[],e=>[e,!0])),s=function(e,t,n,s={}){const r=new Map,i=[],o=[],a=[];for(const l of e){const e=l.cwd||"/",n=!0!==l.archived;if(Boolean(s.showNeedsAttentionGroup&&n&&(s.needsAttentionSessionIds?.[l.sessionId]||l.interruptReason||l.runtime.needsAttention&&!l.stallWarning))?o.push(l):s.showRunningGroup&&n&&(t?.[l.sessionId]||l.runtime.isResponding)&&a.push(l),s.separatePinnedGroup&&Mt(l,s.pinnedSessionIds,s.pendingPinnedSessionIds)&&n){i.push(l);continue}const c=r.get(e);c?c.push(l):r.set(e,[l])}const c=[];o.length&&c.push({folder:"@vibelet/needs-attention",kind:"attention",sessions:Tt(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:Tt(a,s.regularSessionOrderById)}),i.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?At(i):Tt(i,s.regularSessionOrderById)});for(const[l,d]of r)c.push({folder:l,kind:"folder",sessions:d});return c}(e,n(t.respondingSessionIds),0,{...t,needsAttentionSessionIds:n(t.needsAttentionSessionIds),orderPinnedByLastActivity:!0}),r=new Map(t.runningSessionOrder?.map((e,t)=>[e,t]));if(r.size){const e=s.find(e=>"running"===e.kind);e?.sessions.sort((e,t)=>(r.get(e.sessionId)??1/0)-(r.get(t.sessionId)??1/0))}return s}(p,{needsAttentionSessionIds:u,regularSessionOrderById:f,respondingSessionIds:e.respondingSessionIds,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[u,f,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,p]);return{activeApproval:a,activeQuestion:c,activeSession:i,displaySessions:s,groupedSessions:g,pendingSessionIds:r,visibleSessions:p}}({activeSessionId:L,reviewSessionIds:Me,failedSessionIds:dt,hideArchived:te,optimisticSessions:we,pendingApprovals:_,pendingQuestions:z,pendingSessions:be,respondingSessionIds:q,search:Y,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ye,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});Hs(i,L),Hs(k,M),Hs(C,q),Hs(u,pe),Hs(d,ge),Hs(h,Z);const{updateNewSessionDraft:St,updateDraft:kt,updateSessionDraft:It}=function({activeSessionIdRef:e,composerDraftsRef:n,setComposerDrafts:s,setDraft:r}){const i=t.useRef(null),o=t.useRef(null),a=t.useRef(!1);t.useEffect(()=>Qs(()=>a.current),[]);const c=t.useCallback(()=>{if(i.current&&clearTimeout(i.current),o.current&&clearTimeout(o.current),i.current=o.current=null,a.current){a.current=!1;try{ss(n.current)}catch{a.current=!0}}},[n]),l=t.useCallback(()=>{a.current=!0,i.current&&clearTimeout(i.current),i.current=setTimeout(c,300),o.current||(o.current=setTimeout(c,2e3))},[c]);t.useEffect(()=>{const e=()=>{"hidden"===document.visibilityState&&c()};return window.addEventListener(Gs,c),window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener(Gs,c),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]);const d=t.useCallback((t,i)=>{const o=rs(n.current,t,i);n.current=o,s(o),e.current===t&&r(i),l()},[e,n,s,r,l]);return{updateDraft:t.useCallback(t=>d(e.current,t),[e,d]),updateNewSessionDraft:t.useCallback(e=>d(null,e),[d]),updateSessionDraft:d}}({activeSessionIdRef:i,composerDraftsRef:h,setComposerDrafts:X,setDraft:xe});t.useEffect(()=>{w();const e=x();e&&(St(e),oe("session"),S())},[St]),t.useEffect(()=>{const e=()=>{me(gt()),ve(vt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&ve(vt())},[ie]),t.useEffect(()=>()=>{I.current&&window.clearTimeout(I.current)},[]);const Ct=t.useCallback((e,t=!1)=>{T(n=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return Cn(n?e:e.filter(e=>s.has(e.sessionId)),t)}(n,e.sessions,t)),A(t=>{const n=new Set(e.sessions.map(e=>e.sessionId)),s=Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e)));return Object.keys(s).length===Object.keys(t).length?t:s}),N(e.nextCursor),P(e.inventoryVersion),e.folderCounts&&D(e.folderCounts),t||function(e,t,n=s(),r=(new Date).toISOString()){if(!e)return;const i=[{daemonId:e,page:{...t,sessions:t.sessions.slice(0,120)},cachedAt:r},...Jn(n).filter(t=>t.daemonId!==e)].slice(0,8);try{n.setItem(Qn,JSON.stringify(i))}catch{}}(k.current?.daemonId,e),R(e.inventoryBackfillInFlight?re.connectedIndexing:re.connected)},[re.connected,re.connectedIndexing]),jt=function({clientRef:e,sessions:n,setSessions:s,activeSessionIdRef:r}){const i=t.useRef(new Map),o=t.useRef(n);o.current=n,t.useEffect(()=>()=>i.current.clear(),[]);const a=t.useCallback(async t=>{const n=e.current;if(!n?.isConnected)return;const o=t.find(e=>e.sessionId===r?.current),a=o?[o,...t]:t,c=[...new Set(a.map(e=>e.cwd).filter(Boolean))];if(0===c.length)return;const l={};for(const e of c)i.current.set(e,l);try{const t=await n.request({action:"sessions.gitMetadata",id:n.makeId("git"),cwds:c});if(e.current!==n||!n.isConnected)return;s(s=>s.map(s=>{if(e.current!==n||!n.isConnected||i.current.get(s.cwd)!==l)return s;const r=Object.hasOwn(t.branches,s.cwd),o=r?t.branches[s.cwd]??void 0:s.branch,a=r&&o!==s.branch,c=t.gitLinksCwds?.includes(s.cwd)??r;return{...s,pullRequest:c?t.pullRequests?.[s.cwd]:a?void 0:s.pullRequest,branchUrl:t.branchUrls?.[s.cwd]??(c||a?void 0:s.branchUrl),branch:o,diffStat:Object.hasOwn(t.diffStats,s.cwd)?t.diffStats[s.cwd]??void 0:s.diffStat}}))}catch{}},[e,s,r]);return t.useEffect(()=>{let e=!1;const t=()=>{"hidden"===document.visibilityState||e||(e=!0,a(o.current).finally(()=>{e=!1}))},n=window.setInterval(t,15e3);return window.addEventListener("focus",t),document.addEventListener("visibilitychange",t),()=>{window.clearInterval(n),window.removeEventListener("focus",t),document.removeEventListener("visibilitychange",t)}},[a]),a}({clientRef:r,sessions:ye,setSessions:T,activeSessionIdRef:i}),Dt=t.useCallback((e,t=C.current)=>{const n=r.current;if(!n?.isConnected||0===e.length)return;const s=function(e,t,n,s,r=6){if(r<=0)return[];const i=[];for(const o of e){if(i.length>=r)break;o.sessionId&&or(o,n)&&(ls(t,o.sessionId)||s.has(o.sessionId)||i.push(o))}return i}(e.filter(e=>e.sessionId!==i.current),Te.current,t,p.current);for(const r of s)p.current.add(r.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:r.sessionId,agent:r.agent},{timeoutMessage:re.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{p.current.delete(r.sessionId)})},[re.historyPrefetchTimedOut]),Pt=t.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},r={},i={};for(const f of e.sessions)f.runtime.isResponding&&n.add(f.sessionId);for(const f of e.pendingApprovals??[])s[f.sessionId]={type:"approval.request",...f};for(const f of e.pendingQuestions??[])r[f.sessionId]={type:"question.request",...f};let o,a,c,l,d,u,h=null;if(e.activeSession){const f=e.activeSession,p=e.sessions.find(e=>e.sessionId===f.sessionId);if(h=f.sessionId,o=f.agent,a=p?.cwd||t.currentCwd||pn,c=f.approvalMode??p?.approvalMode??mn,l=f.approvalMode??null,d=Et(f.messages??[],f.partialReplyText),(f.isResponding||f.externallyResponding)&&n.add(f.sessionId),f.pendingApproval&&(s[f.sessionId]={type:"approval.request",sessionId:f.sessionId,...f.pendingApproval}),f.pendingQuestion){const e={type:"question.request",sessionId:f.sessionId,...f.pendingQuestion};r[f.sessionId]=e,u=Sn(e)}f.pendingQueue?.length&&(i[f.sessionId]=f.pendingQueue)}else{const n=t.currentActiveSessionId??null;if(n){const t=e.sessionAliases?.[n];t?h=t:e.sessions.some(e=>e.sessionId===n)&&(h=n)}h=h??e.sessions[0]?.sessionId??null;const s=e.sessions.find(e=>e.sessionId===h);s&&(o=s.agent,a=s.cwd||pn,c=s.approvalMode??mn)}return{page:{sessions:e.sessions,nextCursor:fn(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:h,activeAgent:o,activeCwd:a,activeApprovalMode:c,activeApprovalOverride:l,messages:d,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:r,pendingQueues:i,questionAnswers:u}}(e,{currentActiveSessionId:i.current,currentCwd:Q});Ct(t.page,!1),N(t.page.nextCursor),P(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&Ne(t.activeSessionId,t.messages);for(const n of e.activeSession?.acceptedClientMessageIds??[])$e(e.activeSession.sessionId,n,"delivered");e.activeSession&&void 0===e.activeSession.messages&&rt(e.activeSession,{refresh:!0}),i.current=t.activeSessionId,F(t.activeSessionId),t.activeAgent&&V(t.activeAgent),t.activeCwd&&G(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&B(t.questionAnswers),C.current=new Set(t.respondingSessionIds),O(C.current),$(t.pendingApprovals),H(t.pendingQuestions),W(t.pendingQueues),jt(e.sessions),Dt(e.sessions,new Set(t.respondingSessionIds))},[Q,jt,Ne,Dt,rt,Ct,$e]),Lt=function(e){const{clientRef:n,activeSessionIdRef:s,search:r,sinceFilter:i,hideArchived:o,sessionAgentFilter:a}=e,c=t.useMemo(()=>({}),[r,i,o,a]),l=t.useRef({scope:c,options:e,request:0});return l.current.scope=c,l.current.options=e,t.useEffect(()=>()=>{l.current.request++},[]),t.useCallback(async()=>{const e=n.current;if(!e?.isConnected)return;const t=++l.current.request,r=()=>n.current===e&&e.isConnected&&l.current.request===t;for(;r();){const t=l.current,n=t.scope,o=t.options,a=s.current,c=()=>l.current.scope===n;try{const t=await e.request({action:"reconnect.snapshot",id:e.makeId("snapshot"),activeSessionId:a??void 0,activeAgent:o.activeAgent,agent:"all"===o.sessionAgentFilter?void 0:o.sessionAgentFilter,search:o.search.trim()||void 0,sinceMs:In(o.sinceFilter),hideArchived:o.hideArchived,skipGitMetadata:!0,skipActiveSessionHistory:!0});if(!r())return;if(!c())continue;return void l.current.options.apply(s.current===a?t.snapshot:{...t.snapshot,activeSession:void 0})}catch(i){if(!r())return;if(c())throw i}}},[n,s])}({clientRef:r,activeSessionIdRef:i,activeAgent:ut?.agent??K,sessionAgentFilter:ne,search:Y,sinceFilter:ee,hideArchived:te,apply:Pt}),Ft=function(e){const{clientRef:n,search:s,sinceFilter:r,hideArchived:i,sessionAgentFilter:o,viewKey:a}=e,c=t.useMemo(()=>({refresh:0}),[s,r,i,o,a]),l=t.useRef({options:e,scope:c});l.current={options:e,scope:c};const d=t.useRef(c);t.useLayoutEffect(()=>{d.current!==c&&(d.current=c,e.setNextCursor(void 0))},[e.setNextCursor,c]);const u=t.useRef(!0);return t.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]),t.useCallback(async e=>{const t=n.current;if(!u.current||!t?.isConnected||l.current.scope!==c)return;const a=e?.append?c.refresh:++c.refresh,d=()=>u.current&&n.current===t&&t.isConnected&&l.current.scope===c&&(e?.append||a===c.refresh);try{const n=await t.request({action:"sessions.list",id:t.makeId(e?.append?"sessions_more":"sessions"),limit:e?.preserveLoaded?Math.max(80,l.current.options.loadedCount):80,cursor:e?.cursor,agent:"all"===o?void 0:o,search:s.trim()||void 0,sinceMs:In(r),hideArchived:i,skipGitMetadata:!0,force:e?.force});if(!d())return;const a=bn(n),c=l.current.options;c.setSessionsFromPage(a,e?.append),c.setActiveSessionId(e=>e??a.sessions[0]?.sessionId??null),c.hydrateGitMetadata(a.sessions),c.prefetchActiveHistories(a.sessions)}catch(h){if(d())throw h}},[n,c,s,r,i,o])}({clientRef:r,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,viewKey:[e.sessionSort,e.groupFolders,n.showNeedsAttentionGroup,n.showRunningGroup,n.separatePinnedGroup].join(":"),loadedCount:ye.length,setNextCursor:N,setSessionsFromPage:Ct,setActiveSessionId:F,hydrateGitMetadata:jt,prefetchActiveHistories:Dt}),qt=function({clientRef:e,setModelOptions:n,setUsageLimits:s,setSkills:r,setErrorText:i,t:o}){const a=t.useRef(0),c=t.useRef(null);return t.useEffect(()=>()=>{a.current++},[]),t.useCallback((t,l)=>{const d=e.current;if(!d?.isConnected)return Promise.resolve();if(c.current?.client===d&&c.current.agent===t&&c.current.cwd===l)return c.current.promise;const u=++a.current,h=()=>a.current===u&&e.current===d&&d.isConnected,f="codex"===t?"Codex":"Claude",p=[],m=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:t},{timeoutMs:cs}).then(e=>{h()&&n(n=>({...n,[t]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);p.push(/timeout|timed out/i.test(n)?o.resourceLoadTimedOut(e):o.resourceLoadFailed(e,n)),i(p.join("\n"))})(`${f} · ${o.model}`)),Bs(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:t}),h).then(e=>{e&&h()&&s(n=>({...n,[t]:e}))}),Bs(d,()=>({action:"skills.list",id:d.makeId("skills"),cwd:l||void 0}),h).then(e=>{e&&h()&&r(Array.isArray(e.skills)?e.skills:[])})]).then(()=>{a.current===u&&(c.current=null)});return c.current={client:d,agent:t,cwd:l,promise:m},m},[e,n,s,r,i,o])}({t:re,clientRef:r,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:E}),Ot=t.useCallback((e,t,n="info")=>{const s=r.current;s?.isConnected&&s.request({action:"log.report",id:s.makeId("log"),entries:[{level:n,event:e,data:t,ts:(new Date).toISOString()}]}).catch(()=>{})},[]);!function(e){t.useEffect(()=>{const t=performance.now(),n=(t,n,s="info")=>e(t,function(e){const t={};for(const[n,s]of Object.entries(e))rr.has(n)&&("string"==typeof s?t[n]=s.slice(0,48):"number"==typeof s&&Number.isFinite(s)?t[n]=Math.round(s):"boolean"==typeof s&&(t[n]=s));return t}(n),s),s=e=>{n("web.telemetry.runtime_error",{errorKind:ir(e.error)},"error")},r=e=>{n("web.telemetry.unhandled_rejection",{errorKind:ir(e.reason)},"error")},i=window.setTimeout(()=>{n("web.telemetry.workspace_ready",{durationMs:performance.now()-t,domNodes:document.getElementsByTagName("*").length,online:navigator.onLine,visibilityState:document.visibilityState})},1500);let o=0,a=0,c=null;return"undefined"!=typeof PerformanceObserver&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(c=new PerformanceObserver(e=>{for(const t of e.getEntries())o+=1,a=Math.max(a,t.duration)}),c.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",r),()=>{window.clearTimeout(i),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",r),c?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:a},"warn")}},[e])}(Ot);const _t=t.useCallback(async(e=k.current)=>{if(e){fe(e=>({...e,loading:!0,error:null}));try{const t=await fetch(function(e,t){const n=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const e=new URL(n);return"ws:"===e.protocol&&(e.protocol="http:"),"wss:"===e.protocol&&(e.protocol="https:"),e.pathname="/health",e.search="",e.hash="",e.toString()}catch{return new URL("/health",t.origin).toString()}}(e,window.location),{cache:"no-store",signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);if(k.current?.daemonId!==e.daemonId)return;const n=function(e){if(!e||"object"!=typeof e)return{version:"",latestVersion:""};const t=e;return{version:"string"==typeof t.version?t.version.trim():"",latestVersion:"string"==typeof t.latestVersion?t.latestVersion.trim():""}}(await t.json().catch(()=>null));fe({...n,loading:!1,error:null})}catch{if(k.current?.daemonId!==e.daemonId)return;fe(e=>({...e,loading:!1,error:re.connectorVersionFailed}))}}else fe(Wn)},[re.connectorVersionFailed]);t.useEffect(()=>{const e=()=>{me(gt()),ve(vt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&"connected"===j&&_t()},[ie,j,_t]),t.useEffect(()=>{if("connected"!==j)return;const e=()=>{_t()},t=window.setInterval(e,3e4);return window.addEventListener("focus",e),()=>{window.clearInterval(t),window.removeEventListener("focus",e)}},[j,_t]);const $t=t.useCallback(e=>{me(t=>{const n={...t,...e};return u.current=n,function(e,t=s()){t.setItem(pt,JSON.stringify(e))}(n),n})},[]),zt=t.useCallback((t,n)=>{t&&n&&t!==n&&(Qe({action:"remap",daemonId:k.current?.daemonId??null,sessionId:t,nextSessionId:n}),i.current===t&&(i.current=n),F(e=>e===t?n:e),f.current===t&&(f.current=n),De.current===t&&(De.current=n),Ee.remap(t,n),Pe(t,n),C.current=Mn(C.current,t,n),O(e=>Mn(e,t,n)),$(e=>En(e,t,n)),H(e=>En(e,t,n)),e.remapPendingQueue(t,n),W(e=>En(e,t,n)),A(e=>{const s=e[t];if(!s)return e;const r={...e};return delete r[t],r[n]={...s,sessionId:n},r}),X(e=>{const s=function(e,t,n){if(!t||!n||t===n)return e;const s=e.draftsBySessionId[t];if(void 0===s)return e;const r={...e.draftsBySessionId};return delete r[t],s.trim()&&(r[n]=s),{...e,draftsBySessionId:r}}(e,t,n);if(s!==e){h.current=s;try{ss(s)}catch{}}return s}))},[Ee]);return{completionAttention:Ee,...e,...n,...ke,pendingActionsCount:Ie,activeQueue:Ce,activeModelOptions:je,activeUsage:Re,activeApproval:ht,activeQuestion:ft,activeSession:ut,displaySessions:mt,groupedSessions:bt,pendingSessionIds:wt,visibleSessions:xt,appendCachedDelta:Le,appendCachedHistory:Fe,appendInfoMessage:qe,clearHistoryLoading:Oe,ensureCachedHistoryEntry:_e,setCachedMessageDelivery:$e,removeCachedMessage:ze,resolveCachedMessageSession:He,historyCacheRef:Te,historyLoading:Be,hasOlderHistory:Ue,olderHistoryLoading:We,historyPageStartRef:Ae,hydrateVisibleHistory:Ne,messages:Ve,messagesSessionIdRef:De,mergeCachedHistoryPage:Ge,remapCachedHistory:Pe,removeCachedHistory:tt,renderCachedHistory:nt,replaceCachedHistory:st,requestHistory:rt,setMessages:it,updateDraft:kt,updateNewSessionDraft:St,updateSessionDraft:It,setSessionsFromPage:Ct,hydrateGitMetadata:jt,prefetchActiveHistories:Dt,applyReconnectSnapshot:Pt,requestReconnectSnapshot:Lt,requestSessions:Ft,fetchAgentResources:qt,reportLog:Ot,refreshDaemonMetadata:_t,updateNotificationSettings:$t,remapLocalSessionState:zt}}();!function(e){const n=t.useRef({daemonId:"",pending:!0,initial:!0});t.useLayoutEffect(()=>{const t=e.pairing?.daemonId;if("desktop"!==r().kind||"connected"!==e.phase||!t)return;if(n.current.daemonId!==t&&(n.current={daemonId:t,pending:!0,initial:!n.current.daemonId}),!n.current.pending)return;const s=l(e.visibleSessions,"updated",!1)[0];s&&(n.current.initial&&e.activeSessionId||e.setActiveSessionId(s.sessionId),n.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e),function(e,n,s){const r=Ye(e,n?.sessionId),[i,o]=Ze(r,!1),a=t.useRef(null);t.useEffect(()=>{if(!n)return;const t=a.current?.daemonId===e?a.current?.scope:void 0;if(a.current={daemonId:e,scope:r},i)return;o(!0);const c=qs();s(e=>function(e,t,n,s,r){if(t===n)return e;const i=!t&&r?r:s||pn;return i===e.path?e:{path:i,entries:[],loading:!1,loaded:!1}}(e,t,r,n.cwd||pn,c.folder||c.cwd))},[e,r,n?.sessionId,n?.cwd,i,o,s])}(e.pairing?.daemonId,e.activeSession,e.setDirectory);const n=function(e){const n=t.useRef(!1);return async t=>{const s=e.activeSession,r=e.clientRef.current;if(!s||!r?.isConnected||n.current||e.busy)return;const i=$s(),o=e.historyCacheRef.current[s.sessionId]??[],a=function(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s)return e.findIndex(e=>e.historyKey===s);const r=t.rewindPoint;if(r)return e.findIndex(e=>JSON.stringify(e.rewindPoint)===JSON.stringify(r));const i=e.flatMap((e,n)=>e.role===t.role&&e.type===t.type&&e.content===t.content&&e.timestamp===t.timestamp&&JSON.stringify(e.images)===JSON.stringify(t.images)?[n]:[]);return 1===i.length?i[0]:-1}(o,t);if(a<0||"user"!==t.role||"info"===t.type)return void e.setErrorText(i.unavailable);if((e.historyPageStartRef.current[s.sessionId]??0)>0)return void e.setErrorText(i.incompleteHistory);n.current=!0;let c=!1;try{c=await p({message:i.confirmRewind})}finally{n.current=!1}if(c&&e.clientRef.current===r&&r.isConnected&&e.activeSessionIdRef.current===s.sessionId){n.current=!0,e.setBusy(!0),e.setRewinding(!0),e.setErrorText(null);try{const n=await fs("sessionRewind");if(e.clientRef.current!==r||!r.isConnected)return;const c=await r.request({action:"session.rewind",id:r.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetUserMessageIndex:o.slice(0,a+1).filter(e=>"user"===e.role&&"info"!==e.type).length-1,featureEntitlements:n},{timeoutMs:15e4,timeoutMessage:i.rewindFailed});if(e.clientRef.current!==r)return;if(!c||"string"!=typeof c.sessionId||!c.sessionId||c.sessionId===s.sessionId||c.sourceSessionId!==s.sessionId||!0!==c.archivedSource||!Array.isArray(c.messages)||c.messages.some(e=>!e||"string"!=typeof e.content||!["user","assistant","tool"].includes(e.role)))throw new Error(i.invalidResponse);const l={...s,sessionId:c.sessionId,archived:!1};e.setOptimisticSessions(e=>{const t={...e};return delete t[s.sessionId],t[c.sessionId]=l,t}),e.setSessions(e=>[...e.filter(e=>e.sessionId!==c.sessionId).map(e=>e.sessionId===s.sessionId?{...e,archived:!0,pinned:!1}:e),l]),e.replaceCachedHistory(c.sessionId,c.messages),e.activeSessionIdRef.current===s.sessionId&&(e.lastHistorySessionIdRef.current=c.sessionId,e.activeSessionIdRef.current=c.sessionId,e.setActiveSessionId(c.sessionId),e.renderCachedHistory(c.sessionId)),e.updateSessionDraft(c.sessionId,bt(t.content,t.images)),e.setSessionAttachments(c.sessionId,(t.images??[]).map(e=>({path:e,name:e.split("/").pop()??e,type:"application/octet-stream",size:0}))),await e.requestSessions({force:!0}).catch(()=>{})}catch(l){e.clientRef.current===r&&e.setErrorText(l instanceof Error?l.message:i.rewindFailed)}finally{n.current=!1,e.setBusy(!1),e.setRewinding(!1)}}}}(e),{initialSavedTargetsRef:i,composerDraftsRef:k,lastHistorySessionIdRef:I,respondingSessionsRef:C,phase:j,setErrorText:R,pairing:E,setSessions:M,pendingSessions:T,activeSessionId:A,setActiveSessionId:N,setRespondingSessions:D,setPendingApprovals:P,setPendingQuestions:L,setPendingQueues:F,setLivePendingQueue:q,agent:O,setAgent:_,cwd:$,setCwd:z,setApprovalMode:H,setModel:B,setEffort:U,setFastMode:W,setRenameTitle:K,setDraft:V,archiveSyncedDaemonIds:Q,archiveSyncCardDismissedDaemonIds:G,setControlTabAndOpen:J,daemonMetadata:Z,notificationPermission:X,displaySessions:Y,appendInfoMessage:ee,clearHistoryLoading:te,messagesSessionIdRef:ne,renderCachedHistory:se,replaceCachedHistory:re,requestHistory:ie,setMessages:oe,requestSessions:ae,remapLocalSessionState:ce,attachments:le,setAttachments:de,listDirectory:ue,activeApproval:he,activeQuestion:fe,activeSession:pe,appendCachedDelta:me,appendCachedHistory:ge,ensureCachedHistoryEntry:ve,setCachedMessageDelivery:ye,resolveCachedMessageSession:be,historyCacheRef:we,messages:xe,mergeCachedHistoryPage:Se,removeCachedHistory:ke,updateDraft:Ie,setSessionsFromPage:Ce,requestReconnectSnapshot:je,fetchAgentResources:Re,reportLog:Ee,refreshDaemonMetadata:Me,updateNotificationSettings:Te,clientRef:Ae,connectWithPairingRef:Ne,activeSessionIdRef:De,notificationPermissionRef:Pe,notificationSettingsRef:Le,historyCacheDaemonIdRef:Fe,pairingRef:qe,notifiedEventsRef:Oe,reconnectTimerRef:_e,connectionAttemptIdRef:$e,turnNotificationCountsRef:ze,intentionalDisconnectRef:He,setPhase:Be,setStatusText:Ue,setPairing:We,setPendingSessions:Ve,setOptimisticSessions:tt,questionAnswers:nt,setQuestionAnswers:st,approvalMode:rt,continueSession:it,model:dt,effort:ut,fastMode:ht,renameTitle:mt,setComposerDrafts:wt,draft:xt,search:St,sinceFilter:kt,savedTargets:It,setSavedTargets:Ct,saveTargets:jt,updateSessionListPreferences:Dt,t:Pt,busy:Lt,setBusy:Ot,setDetailsOpen:$t,setAdmin:Bt,setDaemonMetadata:Ut,setNotificationPermission:Kt,archiveSyncBusy:Vt,setArchiveSyncBusy:Qt,setArchiveSyncStatus:Gt}=e,Jt=t.useCallback(async(e,t,n)=>{const s="string"==typeof n.sessionId?n.sessionId:e,r="string"==typeof n.oldSessionId?n.oldSessionId:e;r&&s&&r!==s&&ce(r,s),"clear"===t.name?(re(s,[]),F(e=>{const t={...e};return delete t[s],delete t[r],t}),P(e=>{const t={...e};return delete t[s],delete t[r],t}),L(e=>{const t={...e};return delete t[s],delete t[r],t}),N(s)):"new"===t.name?(N(s),ne.current=s,se(s)):"exit"===t.name?(M(e=>e.map(e=>e.sessionId===s?{...e,archived:!0}:e)),N(null),ne.current=null,I.current=null,oe([])):"goal"===t.name&&"goal"in n&&ee(s,function(e){const t="string"==typeof e?.objective?e.objective.trim():"";return t?`Goal${"string"==typeof e?.status&&e.status?` (${e.status})`:""}: ${t}`:"Goal: none."}(n.goal)),n.turnStarted&&!n.queued&&(C.current=new Set(C.current).add(s),D(e=>new Set(e).add(s))),await ae({force:!0})},[ee,ce,se,re,ae]),Zt=function(e){const n=t=>{e.setSessions(e=>{const n=e.findIndex(e=>e.sessionId===t&&e.stallWarning);if(n<0)return e;const s=[...e];return s[n]={...e[n],stallWarning:void 0},s})},s=t=>{e.setSessions(e=>e.map(e=>e.sessionId===t&&e.interruptReason?{...e,interruptReason:void 0,runtime:{...e.runtime,needsAttention:!1}}:e))},i=t.useCallback((t,n,s,i,o)=>{const a=e.notificationSettingsRef.current;a[i]&&!e.notifiedEventsRef.current.has(t)&&function(e,t,n={}){const s=n.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!s&&!r().notifications)return!1;if(!function(e,t,n=("undefined"==typeof document?"visible":document.visibilityState)){return!(!e.enabled||"granted"!==t||e.hiddenOnly&&"visible"===n)}(n.settings??{enabled:!0,hiddenOnly:!1},n.permission??vt(),n.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(r().notifications)return r().notifications.show(e,t,n.onClick),!0;const i=new s(e,{body:t,tag:n.tag});return n.onClick&&(i.onclick=n.onClick),!0}(n,s,{onClick:()=>{window.focus(),o&&e.setActiveSessionId(o)},permission:e.notificationPermissionRef.current,settings:a,tag:t,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(t)},[e]);return t.useCallback(t=>{switch(t.type){case"daemon.update.failed":return void e.setErrorText(t.message);case"response":gn(t.data)&&"string"==typeof t.data.oldSessionId&&"string"==typeof t.data.sessionId&&e.remapLocalSessionState(t.data.oldSessionId,t.data.sessionId);break;case"sessions.changed":e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.history":t.isResponding||t.externallyResponding?e.completionAttention?.observe(t.sessionId):e.completionAttention?.complete(t.sessionId),e.setSessions(e=>{const n=e.findIndex(e=>e.sessionId===t.sessionId&&e.stallWarning!==t.stallWarning);if(n<0)return e;const s=[...e];return s[n]={...e[n],stallWarning:t.stallWarning},s}),e.setPendingQueues(e=>({...e,[t.sessionId]:t.pendingQueue??[]})),e.clearHistoryLoading(t.sessionId),e.mergeCachedHistoryPage(t.sessionId,function(e,t){return Et(e.map(e=>({...e})),t)}(t.messages,t.partialReplyText),t.historyPage);for(const n of t.acceptedClientMessageIds??[])e.setCachedMessageDelivery(t.sessionId,n,"delivered");t.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(e=>{const n={...e};return t.pendingApproval?n[t.sessionId]={type:"approval.request",sessionId:t.sessionId,...t.pendingApproval}:delete n[t.sessionId],n}),e.setPendingQuestions(n=>{const s={...n};if(t.pendingQuestion){const n={type:"question.request",sessionId:t.sessionId,...t.pendingQuestion};s[t.sessionId]=n,e.setQuestionAnswers(Sn(n))}else delete s[t.sessionId];return s})),e.setRespondingSessions(n=>{const s=hs(n,t.sessionId,Boolean(t.isResponding||t.externallyResponding));return e.respondingSessionsRef.current=s,s});break;case"session.history.append":e.appendCachedHistory(t.sessionId,t.messages);break;case"text.delta":s(t.sessionId),e.completionAttention?.observe(t.sessionId),n(t.sessionId),e.appendCachedDelta(t.sessionId,t.content),e.respondingSessionsRef.current=hs(e.respondingSessionsRef.current,t.sessionId,!0),e.setRespondingSessions(e=>hs(e,t.sessionId,!0));break;case"session.background_terminals":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,runtime:{...e.runtime,backgroundTerminals:t.terminals}}:e));break;case"tool.call":s(t.sessionId),n(t.sessionId),e.appendCachedHistory(t.sessionId,[{role:"tool",type:"info",toolName:t.toolName,toolInput:t.input,content:`${e.t.toolCallLabel}: ${t.toolName}\n\n${xn(t.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":s(t.sessionId),n(t.sessionId),e.appendCachedHistory(t.sessionId,[{role:"tool",type:"info",content:t.output,timestamp:(new Date).toISOString()}]);break;case"approval.request":e.setPendingApprovals(e=>({...e,[t.sessionId]:t})),i(`approval:${t.sessionId}:${t.requestId}`,e.t.notificationApprovalTitle,t.description||t.toolName,"approvals",t.sessionId);break;case"question.request":e.setPendingQuestions(e=>({...e,[t.sessionId]:t})),i(`question:${t.sessionId}:${t.requestId}`,e.t.notificationQuestionTitle,e.t.notificationQuestionCount(t.questions.length),"questions",t.sessionId);break;case"question.cleared":e.setPendingQuestions(e=>{const n={...e};return n[t.sessionId]?.requestId===t.requestId&&delete n[t.sessionId],n});break;case"session.queue":e.setLivePendingQueue(t.sessionId,t.pending);break;case"session.stall_warning":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,stallWarning:t.warning}:e));break;case"session.interrupted_notice":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,interruptReason:t.reason,stallWarning:void 0}:e));break;case"session.done":if(e.respondingSessionsRef.current.has(t.sessionId)&&e.completionAttention?.observe(t.sessionId),e.completionAttention?.complete(t.sessionId),n(t.sessionId),e.respondingSessionsRef.current.has(t.sessionId)){const n=(e.turnNotificationCountsRef.current[t.sessionId]??0)+1;e.turnNotificationCountsRef.current[t.sessionId]=n,i(`done:${t.sessionId}:${n}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",t.sessionId)}e.respondingSessionsRef.current=hs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>hs(e,t.sessionId,!1)),e.setPendingApprovals(e=>{const n={...e};return delete n[t.sessionId],n}),e.setPendingQuestions(e=>{const n={...e};return delete n[t.sessionId],n}),t.usage&&e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,lastUsage:t.usage}:e)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.interrupted":e.refreshInterruptedHistory?.(t.sessionId),e.respondingSessionsRef.current=hs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>hs(e,t.sessionId,!1)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.renamed":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:t.title}:e));break;case"error":e.respondingSessionsRef.current=hs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>hs(e,t.sessionId,!1)),n(t.sessionId),e.setPendingApprovals(e=>{const n={...e};return delete n[t.sessionId],n}),e.setPendingQuestions(e=>{const n={...e};return delete n[t.sessionId],n}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,runtime:{...e.runtime,isResponding:!1},interruptReason:t.reason??{kind:"driver_error",at:(new Date).toISOString(),humanText:t.message}}:e)),t.sessionId||e.setErrorText(t.message)}},[e,i])}({refreshInterruptedHistory:e=>{if(e!==De.current)return;const t=Y.find(t=>t.sessionId===e);t&&ie(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:Le,notifiedEventsRef:Oe,notificationPermissionRef:Pe,activeSessionIdRef:De,respondingSessionsRef:C,turnNotificationCountsRef:ze,t:Pt,setActiveSessionId:N,setErrorText:R,setPendingQueues:F,setLivePendingQueue:q,setPendingApprovals:P,setPendingQuestions:L,setQuestionAnswers:st,setRespondingSessions:D,setSessions:M,remapLocalSessionState:ce,requestSessions:ae,clearHistoryLoading:te,replaceCachedHistory:re,setCachedMessageDelivery:ye,mergeCachedHistoryPage:Se,appendCachedHistory:ge,appendCachedDelta:me});(function(e){const n=t.useRef(null),i=t.useRef(null),o=()=>{null!==i.current&&window.clearTimeout(i.current),i.current=null},a=t.useRef(null),c=t.useRef(e);c.current=e;const l=t.useCallback(e=>{const t=c.current,n=e??t.pairingRef.current;n&&!t.intentionalDisconnectRef.current&&(t.reconnectTimerRef.current&&window.clearTimeout(t.reconnectTimerRef.current),t.reconnectTimerRef.current=window.setTimeout(()=>{t.reconnectTimerRef.current=null,t.connectWithPairingRef.current(n,!0)},1600))},[]),d=t.useCallback(async(e,t=!1)=>{const n=c.current;o(),n.reconnectTimerRef.current&&(window.clearTimeout(n.reconnectTimerRef.current),n.reconnectTimerRef.current=null),n.intentionalDisconnectRef.current=!1,n.setPhase("connecting"),n.setStatusText(t?n.t.reconnectingToDaemon:n.t.connectingToDaemon),n.setErrorText(null);const a=new hn,d=n.connectionAttemptIdRef.current+1;n.connectionAttemptIdRef.current=d;const u=n.clientRef.current;n.clientRef.current=a,u?.disconnect();const h=()=>n.connectionAttemptIdRef.current===d&&n.clientRef.current===a;a.onMessage(e=>{h()&&c.current.handleServerMessage(e)});let f=!1;a.onClose(()=>{h()&&f&&(n.clientRef.current=null,o(),n.intentionalDisconnectRef.current||(n.setPhase("connecting"),n.setStatusText(n.t.reconnectingToDaemon),n.setErrorText(n.t.webSocketClosedRetrying),l(e)))});const p=!!n.pairingRef.current&&n.pairingRef.current.daemonId!==e.daemonId;p&&n.resetDeviceWorkspace(),n.historyCacheDaemonIdRef.current&&n.historyCacheDaemonIdRef.current!==e.daemonId&&(n.historyCacheRef.current={},n.messagesSessionIdRef.current=null,n.lastHistorySessionIdRef.current=null,n.setMessages([])),n.historyCacheDaemonIdRef.current=e.daemonId,n.setPairing(e),n.pairingRef.current=e;const m=function(e,t=s()){return e?Jn(t).find(t=>t.daemonId===e)?.page??null:null}(e.daemonId);m&&n.setSessionsFromPage(m,!1),n.setStatusText(t?n.t.reconnectingToDaemon:n.t.connectingToDaemon);try{const s=await(r().prepareConnection?.(e))??e;if(!h())return;let o,l=s;try{o=await a.connect(s)}catch(g){if(!h()||!s.webSocketUrl||Zn(g))throw g;l={...s,webSocketUrl:void 0},n.setStatusText(n.t.reconnectingToDaemon),o=await a.connect(l)}if(!h())return;f=!0;const d={...l,displayName:o.displayName??l.displayName};n.setPairing(d),n.pairingRef.current=d,rn(d),n.setSavedTargets(e=>{const t=function(e,t,n=(new Date).toISOString()){const s=e.find(e=>e.daemonId===t.daemonId);return[{...t,label:s?.label||t.displayName||t.daemonId.slice(0,10),lastConnectedAt:n},...e.filter(e=>e.daemonId!==t.daemonId)].slice(0,12)}(e,d);return Un(t),t}),n.setPhase("connected"),n.setStatusText(n.t.connectedTo(o.displayName??e.displayName??"Vibelet Daemon")),n.refreshDaemonMetadata(d);let u=null;const m=async()=>{if(h())try{if(await c.current.requestReconnectSnapshot(),h()&&u){const e=u;n.setErrorText(t=>t===e?null:t)}}catch(g){if(!h())return;u=g instanceof Error?g.message:String(g),n.setErrorText(u),i.current=window.setTimeout(()=>{i.current=null,m()},1600)}};m();const v=c.current;v.fetchAgentResources(v.agent,p?pn:v.cwd).catch(e=>{h()&&n.setErrorText(e instanceof Error?e.message:String(e))}),n.reportLog("web.connected",{reconnecting:t})}catch(g){if(!h())return;n.clientRef.current=null,a.disconnect(),Zn(g)&&sn()?.pairToken===e.pairToken&&on(),n.setPhase("error"),n.setStatusText(n.t.connectionFailed),n.setErrorText(Zn(g)?n.t.pairingAuthFailed:g instanceof Error?g.message:String(g)),Zn(g)||l(e)}},[l]);t.useEffect(()=>{c.current.connectWithPairingRef.current=d},[d]),t.useEffect(()=>{const e=c.current;let t=!1;return async function(){const n=en(),s=sn()??e.rememberedTarget;if(!n&&!s)return e.setPhase("missing-pair"),void e.setStatusText(e.t.missingPair);try{e.setPhase("pairing"),n&&a.current?.pairNonce!==n.pairNonce&&(a.current={pairNonce:n.pairNonce,promise:an(n,s)});const r=n?await(a.current?.promise):s;if(!r||t)return;n&&(rn(r),a.current=null,function(){if(!window.location.hash.includes(`${Ht}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}()),await e.connectWithPairingRef.current(r)}catch(r){if(t)return;n&&(a.current=null),e.setPhase("error"),e.setStatusText(e.t.pairingFailed),e.setErrorText(function(e,t){return e instanceof Wt&&"pair_window_expired"===e.code?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}(r,e.t))}}(),()=>{t=!0,o(),e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,e.reconnectTimerRef.current&&window.clearTimeout(e.reconnectTimerRef.current),e.clientRef.current?.disconnect()}},[e.t]),t.useEffect(()=>{const e=c.current;if("connected"!==e.phase)return;const t=n.current;if(n.current={client:e.clientRef.current,request:e.requestSessions},!t||t.client!==e.clientRef.current||t.request===e.requestSessions)return;const s=window.setTimeout(()=>{e.requestSessions({force:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)))},260);return()=>window.clearTimeout(s)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),t.useEffect(()=>{const e=c.current;"connected"===e.phase&&e.fetchAgentResources(e.agent,e.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])})({clientRef:Ae,connectWithPairingRef:Ne,pairingRef:qe,reconnectTimerRef:_e,connectionAttemptIdRef:$e,intentionalDisconnectRef:He,historyCacheRef:we,historyCacheDaemonIdRef:Fe,messagesSessionIdRef:ne,lastHistorySessionIdRef:I,rememberedTarget:i.current[0]??null,agent:O,cwd:$,phase:j,search:St,sinceFilter:kt,t:Pt,handleServerMessage:Zt,setPhase:Be,setStatusText:Ue,setErrorText:R,setMessages:oe,setPairing:We,setSavedTargets:Ct,setSessionsFromPage:Ce,resetDeviceWorkspace:()=>{De.current=null,N(null),z(pn),M([]),Ve({}),tt({}),e.setDiffSessionId(null),P({}),L({}),F({}),C.current=new Set,D(new Set),Os({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:Me,requestReconnectSnapshot:je,fetchAgentResources:Re,reportLog:Ee,requestSessions:ae}),t.useLayoutEffect(()=>{V(is(k.current,A))},[A,E?.daemonId]),t.useEffect(()=>{const e=Y.find(e=>e.sessionId===A);if(!e)return I.current=null,ne.current=null,te(),void oe([]);if(_(e.agent),z(e.cwd||pn),K(e.customTitle??e.title??""),T[e.sessionId])return I.current=e.sessionId,te(),void(ne.current!==e.sessionId&&(ne.current=e.sessionId,oe([])));if(se(e.sessionId)){const t=I.current!==e.sessionId;return I.current=e.sessionId,te(e.sessionId),void(t&&ie(e,{refresh:!0}))}I.current!==e.sessionId&&(I.current=e.sessionId,ne.current!==e.sessionId&&(ne.current=e.sessionId,oe([])),ie(e,{refresh:!0}))},[A,te,Y,T,se,ie]);const Xt=function({daemonId:e,session:n,setModel:r,setEffort:i,setFastMode:o,setApprovalMode:a,setPendingSessions:c}){const l=t.useRef(null);l.current||(l.current=function(){try{const e=JSON.parse(s().getItem(zs)||"{}");return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}());const d=JSON.stringify([e??"",n?.sessionId??""]),u={model:n?.model??"",effort:n?.effort??"",fastMode:n?.fastMode??!1,approvalMode:n?.approvalMode??mn},h=()=>{try{s().setItem(zs,JSON.stringify(l.current))}catch{}},f=e=>{const t=l.current[d]?.[e];return void 0===t?u[e]:(u[e]===t&&delete l.current[d][e],t)};t.useLayoutEffect(()=>{n&&(r(f("model")),i(f("effort")),o(f("fastMode")),a(f("approvalMode")),h())},[d,u.model,u.effort,u.fastMode,u.approvalMode]);const p=(e,t)=>{n&&(l.current[d]={...l.current[d],[e]:t},h(),c(s=>{const r=s[n.sessionId];if(!r)return s;const i="model"===e?kn(t):"effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...r,[e]:i}}})),"model"===e&&r(t),"effort"===e&&i(t),"fastMode"===e&&o(t),"approvalMode"===e&&a(t)};return{applyConfirmedSettings:(t,s)=>{const i=JSON.stringify([e??"",t]),a=l.current[i];a&&(void 0!==s.fastMode&&delete a.fastMode,void 0!==s.model&&delete a.model,h()),n?.sessionId===t&&(void 0!==s.fastMode&&o(s.fastMode),void 0!==s.model&&r(s.model))},setModel:e=>p("model",e),setEffort:e=>p("effort",e),setFastMode:e=>p("fastMode",e),setApprovalMode:e=>p("approvalMode",e)}}({daemonId:E?.daemonId,session:pe,setModel:B,setEffort:U,setFastMode:W,setApprovalMode:H,setPendingSessions:Ve}),{stagePendingSession:Yt,failedSend:tn,dismissFailedSend:nn,retryFailedSend:cn,sendDraft:un,sendQuickReply:vn}=function(e){const[n]=t.useState(vs),[s,r]=function(e,t,n){const s=Xe(Ye(n,e),{}),r=()=>{for(const[r,i]of s.getAll()){const[s,o]=JSON.parse(r);if(s===(n??null)&&o)for(const n of Object.values(i)){const s=t(o,n.clientMessageId);if(s===e)return{scope:r,failure:n.sessionId===s?n:{...n,sessionId:s}}}}return null},i=r();return[i?.failure??null,e=>{const o=i??r(),a=o?s.getForScope(o.scope):void 0,c=o?a?.[o.failure.clientMessageId]??null:null,l=c&&o?.failure.sessionId!==c.sessionId?{...c,sessionId:o.failure.sessionId}:c,d="function"==typeof e?e(l):e;if("function"!=typeof e||d!==l){if((null===e||"function"==typeof e)&&c&&o){if(d?.clientMessageId===c.clientMessageId)return void s.setForScope(o.scope,{...a,[d.clientMessageId]:d});const e={...a};delete e[c.clientMessageId],s.setForScope(o.scope,e)}if(d){const e=Ye(n,t(d.sessionId,d.clientMessageId));s.setForScope(e,{...s.getForScope(e),[d.clientMessageId]:d})}}}]}(e.activeSessionId,e.resolveCachedMessageSession,e.daemonId),[i,o]=t.useState(null);t.useEffect(()=>{s&&e.messagesSessionIdRef.current===e.resolveCachedMessageSession(s.sessionId,s.clientMessageId)&&e.messages.some(e=>(e.localClientMessageId===s.clientMessageId||e.historyKey===s.historyKey)&&("accepted"===e.delivery||"delivered"===e.localDelivery||Boolean(e.historyKey&&!e.historyKey.startsWith("client:"))))&&r(null)},[s,e]);const a=t.useCallback(t=>{e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(t),e.setRespondingSessions(e=>{const n=new Set(e);return n.delete(t),n})},[e]),c=t.useCallback((t,n,s)=>{const r=Ls(t)??Ls(e.cwd)??pn,i=n??e.agent,a=function(e=Date.now()){return jn=(jn+1)%1e4,`pending_local_${e}_${jn}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||pn,...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},fastMode:e.fastMode??!1,...e.title?{title:e.title}:{},createdAt:t,lastActivityAt:t,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver"},managed:!0,approvalMode:e.approvalMode}}({sessionId:a,agent:i,cwd:r,approvalMode:s?.approvalMode??e.approvalMode,model:kn(s?.model??e.model),effort:(s?.effort??e.effort)||void 0,fastMode:s?.fastMode??e.fastMode,title:"codex"===i?e.t.newCodexSession:e.t.newClaudeSession});Object.assign(c,{preparationId:s?.preparationId});const l=s?.draft??(e.activeSessionIdRef.current?"":is(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.revealCreatedSession(r),e.setComposerDrafts(t=>{let n=rs(t,a,l);return e.activeSessionIdRef.current||(n=rs(n,null,"")),e.composerDraftsRef.current=n,ss(n),n}),e.setCwd(r),e.setAgent(i),e.activeSessionIdRef.current=a,e.setActiveSessionId(a),e.lastHistorySessionIdRef.current=a,e.messagesSessionIdRef.current=a,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(l),(s?.draft?.trim()||s?.attachments?.length)&&o({sessionId:a,attachments:s.attachments??[]}),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:a,agent:i,cwd:r}),a},[e]),l=function(e){const n=t.useRef(new Map),s=t.useCallback(async(t,n,s)=>{const r=e.clientRef.current;if(!r?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const i=s?e.pendingSessions[s]:void 0,o=Ds(t)??Ds(i?.cwd)??Ds(e.cwd)??pn,a=n??i?.agent??e.agent,c=i?.approvalMode??e.approvalMode,l=i?i.model:kn(e.model),d=i?i.effort:e.effort||void 0,u=i?.fastMode??e.fastMode;e.setErrorText(null),s&&e.setPendingSessions(e=>{const t=e[s];return t?{...e,[s]:{...t,creationError:void 0,creationPending:!0}}:e});try{const t=await r.request({action:"session.create",id:r.makeId("create"),agent:a,cwd:o,approvalMode:c,continueSession:e.continueSession,model:l,effort:d,fastMode:u,...s?{clientSessionId:s}:{},preparationId:i?.preparationId});if(e.clientRef.current!==r)return null;const n=function(e){const t=e;return"string"==typeof t.sessionId?t.sessionId:null}(t);if(!n)throw new Error(e.t.sessionIdMissing);const h=gn(t)&&"string"==typeof t.oldSessionId?t.oldSessionId:s;if(e.activeSessionIdRef.current!==(s??null)&&e.activeSessionIdRef.current!==n||(e.setCwd(o),e.setAgent(a),e.activeSessionIdRef.current=n,e.setActiveSessionId(n),e.lastHistorySessionIdRef.current=n,e.messagesSessionIdRef.current=n,e.clearHistoryLoading()),s&&i){e.setPendingSessions(e=>{const t={...e};return delete t[s],h&&h!==s&&delete t[h],t});const{preparationId:t,creationError:r,creationPending:o,...a}=i;e.setOptimisticSessions(e=>({...e,[n]:Rn(a,n)})),h&&h!==n&&e.remapLocalSessionState(h,n),s!==n&&e.remapLocalSessionState(s,n)}else await e.requestSessions({force:!0});return e.reportLog("web.session.create",{sessionId:n,clientSessionId:s,agent:a,cwd:o}),n}catch(h){if(e.clientRef.current!==r)return null;const t=h instanceof Error?h.message:String(h);return s&&e.setPendingSessions(e=>{const n=e[s];return n?{...e,[s]:{...n,creationError:t,creationPending:!1}}:e}),e.activeSessionIdRef.current===(s??null)&&e.setErrorText(t),null}},[e]);return t.useCallback((t,r,i)=>{if(!i)return s(t,r);const o=e.clientRef.current,a=n.current.get(i);if(a?.client===o)return a.promise;const c=s(t,r,i),l={client:o,promise:c};return n.current.set(i,l),c.finally(()=>{n.current.get(i)===l&&n.current.delete(i)}),c},[s,e.clientRef])}(e);!function(e,n,s){const r=t.useRef(null);t.useEffect(()=>{const t=e.clientRef.current,n=e.activeSession;if(!t?.isConnected||!n||"codex"!==n.agent||e.pendingSessions[n.sessionId]||!e.draft||e.messages.some(e=>"user"===e.role))return;const s=JSON.stringify([n.sessionId,e.model,e.effort,e.fastMode]),i=r.current;i?.client===t&&i.key===s&&Date.now()-i.at<3e4||(r.current={client:t,key:s,at:Date.now()},t.request({action:"session.prepare",id:t.makeId("prepare"),sessionId:n.sessionId}).catch(()=>{}))},[e.activeSession,e.clientRef,e.draft,e.messages,e.pendingSessions,e.model,e.effort,e.fastMode]);const i=t.useRef(new Set);t.useEffect(()=>{for(const n of i.current)e.pendingSessions[n]||i.current.delete(n);const t=e.activeSessionId,r=t?e.pendingSessions[t]:void 0;!(e.clientRef.current?.isConnected&&t&&r&&"codex"===r.agent)||"creationError"in r&&r.creationError||n===t||i.current.has(t)||(i.current.add(t),s(r.cwd,r.agent,t))},[e.activeSessionId,e.pendingSessions,e.clientRef,n,s])}(e,i?.sessionId,l);const d=t.useCallback(async t=>{if(!e.sessions.some(e=>e.sessionId===t&&e.archived))return;const n=e.clientRef.current;if(!n?.isConnected)throw new Error(e.t.webSocketNotConnected);await n.request({action:"session.setArchived",id:n.makeId("unarchive"),sessionId:t,archived:!1}),e.clientRef.current===n&&(e.setSessions(e=>e.map(e=>e.sessionId===t?{...e,archived:!1}:e)),e.setOptimisticSessions(e=>e[t]?{...e,[t]:{...e[t],archived:!1}}:e),e.requestSessions({force:!0}).catch(()=>{}))},[e]),u=t.useCallback(async(t,s,i)=>{t?.preventDefault();const o=(i??e.draft).trim(),u=s??e.attachments;if(u.some(e=>e.uploading))return;if(!o&&!u.length||e.busy||n.has(e.activeSessionId))return;const h=e.clientRef.current;if(!h?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);if(!e.activeSessionId)return void c(void 0,void 0,{draft:o,attachments:u});const f=n.start(e.activeSessionId);try{const t=Ts(o)?"agentSkills":0===u.length&&Cs(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await fs(t)}catch(p){if(e.clientRef.current!==h)return;return void e.setErrorText(p instanceof Error?p.message:String(p))}if(e.clientRef.current!==h||e.activeSessionIdRef.current!==e.activeSessionId)return;e.setErrorText(null),void 0===i&&e.updateDraft("");const s=u;void 0===i&&e.setAttachments([]);let c=e.activeSessionId,m=e.activeSession?.agent??e.agent;const g=c?e.pendingSessions[c]:void 0,v=g?.fastMode??e.fastMode,y=g?g.model:kn(e.model),b=g?g.effort:e.effort||void 0;if(c&&e.pendingSessions[c]){const t=await l(e.pendingSessions[c].cwd,e.pendingSessions[c].agent,c);if(e.clientRef.current!==h)return;if(!t)return void(void 0===i&&Ns(e,o,s));c=t,m=e.pendingSessions[e.activeSessionId??""]?.agent??m}if(!c)return void(void 0===i&&Ns(e,o,s));f.remap(c);const w=0===s.length?Cs(o,m):null;if(w){const t=function(e){return"compact"===e.name?"/compact":"goal"!==e.name?null:"clear"===e.operation?"/goal clear":"pause"===e.operation?"/goal pause":"resume"===e.operation?"/goal resume":"set"===e.operation&&e.objective?.trim()?`/goal ${e.objective.trim()}`:"/goal"}(w.command),s=t?h.makeId("cmd_msg"):void 0;t&&(e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.appendCachedHistory(c,[{role:"user",content:t,timestamp:(new Date).toISOString()}]),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c));try{if(t&&await d(c),e.clientRef.current!==h)return;const r=await h.request({action:"session.command",id:h.makeId("command"),sessionId:c,agent:m,command:w.command,...s?{clientMessageId:s}:{},featureEntitlements:n});if(e.clientRef.current!==h)return;await e.handleSessionCommandResponse(c,w.command,r)}catch(p){if(e.clientRef.current!==h)return;const t=p instanceof Error?p.message:String(p);e.appendInfoMessage(c,js(t)),e.activeSessionIdRef.current===c&&e.setErrorText(js(t))}return}const x=function(e){return e.startsWith("//")?e.slice(1):e}(o),S=s.map(e=>e.path),k=h.makeId("msg"),I=`client:${k}`;e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.setCachedMessageDelivery(c,k,"sending",{content:x,...S.length?{images:S}:{}}),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(c),e.setRespondingSessions(e=>new Set(e).add(c));const C=Ts(x)??void 0,j=C?n:void 0;try{if(await d(c),e.clientRef.current!==h)return;const t=await gs(h,{action:"session.send",id:h.makeId("send"),sessionId:c,agent:m,message:x,clientMessageId:k,images:S.length?S:void 0,model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:j},{timeoutMs:cs,timeoutMessage:Ps},t=>e.appendInfoMessage(c,t));if(e.clientRef.current!==h)return;gn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(f.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(gn(t)&&"string"==typeof t.sessionId?t.sessionId:c,k,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:S.length}),r(e=>e?.historyKey===I?null:e)}catch(p){if(e.clientRef.current!==h)return;c=e.resolveCachedMessageSession(c,k);const t=as(Ln(p instanceof Error?p.message:String(p),Boolean(C)));if("delivered"===e.setCachedMessageDelivery(c,k,"failed"))return;e.activeSessionIdRef.current===c&&e.setErrorText(null),r({sessionId:c,agent:m,message:x,clientMessageId:k,historyKey:I,kind:t,retrying:!1,...S.length?{images:S}:{},model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:j}),e.reportLog("web.telemetry.send_failed",{attachmentCount:S.length,failureKind:t},"warn"),a(c)}}finally{f.finish()}},[a,c,l,e,n,d]),h=t.useCallback(async()=>{if(!s||s.retrying||e.busy||n.has(e.activeSessionId))return;const t=e.clientRef.current;if(!t?.isConnected)return void r(e=>e?{...e,kind:"network"}:null);let i=e.resolveCachedMessageSession(s.sessionId,s.clientMessageId);const o=n.start(i);r(e=>e?{...e,retrying:!0}:null),e.ensureCachedHistoryEntry(i,{role:"user",content:s.message,historyKey:s.historyKey,...s.images?.length?{images:s.images}:{}}),e.setCachedMessageDelivery(i,s.clientMessageId,"sending"),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(i),e.setRespondingSessions(e=>new Set(e).add(i));try{await d(i);const n=s.skillInvocation?await fs("agentSkills"):void 0;if(e.clientRef.current!==t)return;const a=await gs(t,{action:"session.send",id:t.makeId("retry_send"),sessionId:i,agent:s.agent,message:s.message,clientMessageId:s.clientMessageId,images:s.images,model:s.model,effort:s.effort,fastMode:s.fastMode,skillInvocation:s.skillInvocation??void 0,featureEntitlements:n},{timeoutMs:cs,timeoutMessage:Ps},t=>e.appendInfoMessage(i,t));if(e.clientRef.current!==t)return;gn(a)&&"string"==typeof a.oldSessionId&&"string"==typeof a.sessionId&&(o.remap(a.sessionId),e.remapLocalSessionState(a.oldSessionId,a.sessionId)),e.setCachedMessageDelivery(gn(a)&&"string"==typeof a.sessionId?a.sessionId:i,s.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:s.images?.length??0}),r(null)}catch(c){if(e.clientRef.current!==t)return;i=e.resolveCachedMessageSession(i,s.clientMessageId);const n=as(Ln(c instanceof Error?c.message:String(c),Boolean(s.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(i,s.clientMessageId,"failed"))return void r(null);r(e=>e?{...e,sessionId:i,kind:n,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:s.images?.length??0,failureKind:n},"warn"),a(i)}finally{r(e=>e?.clientMessageId===s.clientMessageId&&e.retrying?{...e,retrying:!1}:e),o.finish()}},[a,s,e,n,d]);return t.useEffect(()=>{!i||e.busy||n.has(e.activeSessionId)||(e.activeSessionId===i.sessionId&&e.pendingSessions[i.sessionId]?(o(null),u(void 0,i.attachments)):o(null))},[i,e.activeSessionId,e.busy,e.pendingSessions,u]),{failedSend:s,dismissFailedSend:()=>r(null),retryFailedSend:h,stagePendingSession:c,sendDraft:Object.assign(u,{submission:n}),sendQuickReply:e=>u(void 0,[],e)}}({daemonId:E?.daemonId,revealCreatedSession:t=>{e.setSearch(""),e.setSessionAgentFilter("all"),e.setCollapsedFolders(e=>({...e,[t]:!1}))},messages:xe,sessions:Y,setSessions:M,clientRef:Ae,activeSessionIdRef:De,composerDraftsRef:k,lastHistorySessionIdRef:I,messagesSessionIdRef:ne,respondingSessionsRef:C,agent:O,cwd:$,approvalMode:rt,continueSession:it,model:dt,effort:ut,fastMode:ht,activeSessionId:A,activeSession:pe,pendingSessions:T,draft:xt,busy:Lt,attachments:le,t:Pt,setPendingSessions:Ve,setOptimisticSessions:tt,setComposerDrafts:wt,setCwd:z,setAgent:_,setActiveSessionId:N,setMessages:oe,setDraft:V,setErrorText:R,setBusy:Ot,setAttachments:de,setRespondingSessions:D,clearHistoryLoading:te,reportLog:Ee,remapLocalSessionState:ce,requestSessions:ae,updateDraft:Ie,appendCachedHistory:ge,ensureCachedHistoryEntry:ve,setCachedMessageDelivery:ye,resolveCachedMessageSession:be,renderCachedHistory:se,handleSessionCommandResponse:Jt,appendInfoMessage:ee}),{respondApproval:An,respondQuestion:Fn,cancelQuestion:qn,setQuestionChoice:On,requestActiveAction:$n,interruptActiveSession:zn,retrySessions:Hn,updateApprovalMode:Kn,setSessionPinned:Gn,setSessionArchived:Xn,deleteSession:Yn,updatePinned:es,updateArchived:ts,renameSession:ps}=function(e){const n=function(e){return t.useCallback(async t=>{const n=t.sessionId,s=e.clientRef.current,r=Boolean(e.pendingSessions[n]);if(!r&&!s?.isConnected)return!1;const i={daemonId:e.daemonId,sessionId:n},a=()=>r&&(e.isSessionSubmitting(n)||e.pendingSessions[n]?.creationPending)?(p({message:u().sessionStarting,notice:!0}),!1):!!function(e){return window.dispatchEvent(new CustomEvent(Ke,{cancelable:!0,detail:e}))}(i)||(p({message:u().saveSessionFiles,notice:!0}),!1);if(!a())return!1;if(!(await d(u().deleteSession(o(t)))))return!1;if(e.clientRef.current!==s||!r&&!s?.isConnected||!a())return!1;e.setBusy(!0),e.setErrorText(null),Ge(i,!0);try{if(r||await s.request({action:"session.delete",id:s.makeId("delete"),sessionId:n}),e.clientRef.current!==s)return!1;Qe({...i,action:"remove"}),e.removeCachedHistory(n);const t=e=>{if(!e[n])return e;const t={...e};return delete t[n],t};return e.setPendingSessions(t),e.setOptimisticSessions(t),e.setPendingQueues(t),e.setPendingApprovals(t),e.setPendingQuestions(t),e.setSessions(e=>e.filter(e=>e.sessionId!==n)),e.updateSessionDraft(n,""),e.respondingSessionsRef.current.delete(n),e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(n),t}),e.activeSessionIdRef.current===n&&(e.activeSessionIdRef.current=null,e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(is(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)),r||await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(c){return e.clientRef.current!==s||p({message:c instanceof Error?c.message:String(c),notice:!0}),!1}finally{Ge(i,!1),e.setBusy(!1)}},[e])}(e),s=t.useCallback(async t=>{const n=e.clientRef.current,s=e.activeApproval;if(n?.isConnected&&s){e.setBusy(!0),e.setErrorText(null);try{if(await n.request({action:"session.approve",id:n.makeId("approve"),sessionId:s.sessionId,requestId:s.requestId,approved:t}),e.clientRef.current!==n)return;e.setPendingApprovals(e=>{const t={...e};return t[s.sessionId]?.requestId===s.requestId&&delete t[s.sessionId],t})}catch(r){if(e.clientRef.current!==n)return;const t=r instanceof Error?r.message:String(r);/session not found|session .* inactive/i.test(t)&&e.setPendingApprovals(e=>{if(e[s.sessionId]?.requestId!==s.requestId)return e;const t={...e};return delete t[s.sessionId],t}),e.setErrorText(t)}finally{e.setBusy(!1)}}},[e]),r=t.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.respondQuestion",id:t.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),i=t.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.cancelQuestion",id:t.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),a=t.useCallback((t,n,s)=>{e.setQuestionAnswers(e=>function(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const r=e[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,[t]:i}}(e,t,n,Boolean(s)))},[e]),c=t.useCallback(async t=>{const s=e.clientRef.current,r=e.activeSession,i=r?.sessionId??("session.interrupt"===t?e.activeSessionIdRef.current:null);if(!s?.isConnected||!i)return!1;if("session.interrupt"!==t&&!r)return!1;if("session.delete"===t)return n(r);if(e.clientRef.current!==s||!s.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{if("session.resume"===t){if(await s.request({action:t,id:s.makeId("resume"),sessionId:i,agent:r.agent}),e.clientRef.current!==s)return!1}else if(await s.request({action:t,id:s.makeId(t.split(".").at(-1)??"session"),sessionId:i}),e.clientRef.current!==s)return!1;return"session.interrupt"!==t&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(o){return e.clientRef.current!==s||e.setErrorText(o instanceof Error?o.message:String(o)),!1}finally{e.setBusy(!1)}},[e,n]),l=t.useCallback(async t=>{const n=e.clientRef.current;if(e.activeSession){if(n?.isConnected){e.setErrorText(null);try{if(await n.request({action:"session.setApprovalMode",id:n.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:t}),e.clientRef.current!==n)return;e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(t),e.setSessions(n=>n.map(n=>n.sessionId===e.activeSession.sessionId?{...n,approvalMode:t}:n))}catch(s){if(e.clientRef.current!==n)return;e.setErrorText(s instanceof Error?s.message:String(s))}}}else e.setApprovalMode(t)},[e]),h=t.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const r=n?Date.now():void 0;if(await s.request({action:"session.setPinned",id:s.makeId("pin"),sessionId:t.sessionId,pinned:n,...r?{pinnedAt:r}:{}}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,pinned:n,pinnedAt:r}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),f=t.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{if(await s.request({action:"session.setArchived",id:s.makeId("archive"),sessionId:t.sessionId,archived:n}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),m=t.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.pinned)},[e.activeSession,h]),g=t.useCallback(async()=>{e.activeSession&&await f(e.activeSession,!e.activeSession.archived)},[e.activeSession,f]),v=t.useCallback(()=>{c("session.interrupt")},[c]),y=t.useCallback(()=>{e.setErrorText(null),"connected"===e.phase?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),b=t.useCallback(async(t=e.activeSession,n=e.renameTitle)=>{const s=n.trim();if(t&&e.pendingSessions[t.sessionId])return e.setPendingSessions(e=>{const n=e[t.sessionId];return n?{...e,[t.sessionId]:{...n,title:s||n.title,customTitle:s||void 0}}:e}),!0;const r=e.clientRef.current;if(!r?.isConnected||!t)return!1;e.setBusy(!0),e.setErrorText(null);try{return await r.request({action:"session.rename",id:r.makeId("rename"),sessionId:t.sessionId,title:s||void 0}),e.clientRef.current===r&&(e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:s||void 0}:e)),!0)}catch(i){return e.clientRef.current!==r||e.setErrorText(i instanceof Error?i.message:String(i)),!1}finally{e.setBusy(!1)}},[e]);return{respondApproval:s,respondQuestion:r,cancelQuestion:i,setQuestionChoice:a,requestActiveAction:c,interruptActiveSession:v,retrySessions:y,updateApprovalMode:l,setSessionPinned:h,setSessionArchived:f,deleteSession:n,updatePinned:m,updateArchived:g,renameSession:b}}({daemonId:E?.daemonId??null,isSessionSubmitting:un.submission.has,updateSessionDraft:e.updateSessionDraft,clientRef:Ae,activeSessionIdRef:De,composerDraftsRef:k,lastHistorySessionIdRef:I,messagesSessionIdRef:ne,respondingSessionsRef:C,activeApproval:he,activeQuestion:fe,activeSession:pe,activeSessionId:A,questionAnswers:nt,pendingSessions:T,phase:j,renameTitle:mt,setBusy:Ot,setErrorText:R,setPendingApprovals:P,setPendingQuestions:L,setQuestionAnswers:st,setPendingQueues:F,setActiveSessionId:N,setMessages:oe,setApprovalMode:H,setSessions:M,setPendingSessions:Ve,setComposerDrafts:wt,setDraft:V,setAttachments:de,setDetailsOpen:$t,setRespondingSessions:D,setOptimisticSessions:tt,removeCachedHistory:ke,requestSessions:ae,removeCachedMessage:e.removeCachedMessage}),{runArchiveSync:ms,skipArchiveSync:ys,runAdminAction:bs,exportActiveSession:ws,clearPairing:xs,setNotificationsEnabled:Ss,connectSavedTarget:ks,forgetSavedTarget:Is,openSessionDetails:Rs,editFolderTags:Es,browseFolder:Ms,copyResumeCommand:As,resumeInTerminal:Fs}=function(e){const n=t.useCallback((t,n)=>{e.updateSessionListPreferences(e=>({...e,archiveSyncedDaemonIds:"synced"===n?{...e.archiveSyncedDaemonIds,[t]:!0}:e.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...e.archiveSyncCardDismissedDaemonIds,[t]:!0}}))},[e]),s=t.useCallback((t,s)=>{const r="pull"===t?e.t.archiveSyncSuccessPull:"pushMerge"===t?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(function(e,t,n){return e.ok?{tone:"success",message:t.replace("{n}",String(e.archivedSessionIds.length))}:"timeout"===e.error?{tone:"error",message:n.timeout}:"not_connected"===e.error?{tone:"error",message:n.disconnected}:{tone:"error",message:n.generic.replace("{error}",e.error)}}(s,r,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!s.ok)return;const i=new Set(s.archivedSessionIds);e.setSessions(e=>e.map(e=>({...e,archived:i.has(e.sessionId)}))),e.pairingRef.current?.daemonId&&n(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[n,e]),i=t.useCallback(async t=>{if(e.archiveSyncBusy)return;e.setArchiveSyncBusy(t),e.setArchiveSyncStatus(null);const n=await async function(e,t,n){if(!e?.isConnected)return{ok:!1,error:"not_connected"};try{const s=await e.request({action:"sessions.archiveSync",id:e.makeId("archive_sync"),mode:t,..."pull"===t?{}:{archivedSessionIds:n??[]}});return{ok:!0,archivedSessionIds:Array.isArray(s.archivedSessionIds)?s.archivedSessionIds.filter(e=>"string"==typeof e&&e.length>0):[]}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}(e.clientRef.current,t,function(e){return e.filter(e=>!0===e.archived).map(e=>e.sessionId)}(e.displaySessions));s(t,n),e.setArchiveSyncBusy(null)},[s,e]),a=t.useCallback(()=>{e.pairing?.daemonId&&(n(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[n,e]),c=t.useCallback(async t=>{const n=e.clientRef.current;if(n?.isConnected&&("update"!==t||await d(u().update))&&("restart"!==t||await d(u().restart))&&e.clientRef.current===n&&n.isConnected){e.setAdmin(e=>({...e,loading:!0,action:t,statusText:""})),e.setErrorText(null);try{if("update"===t){const t=function(e){const t=e.toLowerCase();return t.includes("alpha")?"alpha":t.includes("beta")?"beta":e.trim()?"latest":void 0}(e.daemonMetadata.version),s=await n.request({action:"daemon.update",id:n.makeId("daemon_update"),...t?{channel:t}:{}});return void e.setAdmin(t=>({...t,loading:!1,action:null,statusText:s.alreadyRunning?e.t.daemonUpdateAlreadyRunning:e.t.daemonUpdateStarted}))}await n.request({action:"daemon.restart",id:n.makeId("daemon_restart")}),e.setAdmin(t=>({...t,loading:!1,action:null,statusText:e.t.daemonRestartRequested})),e.refreshDaemonMetadata()}catch(s){e.setAdmin(e=>({...e,loading:!1,action:null,statusText:s instanceof Error?s.message:String(s)})),e.setErrorText(s instanceof Error?s.message:String(s))}}},[e]),l=t.useCallback(async()=>{if(!e.activeSession)return;const t=function(e,t){return function(e,t){const n=o(e),{markdown:s}=function({title:e,session:t,messages:n,labels:s,exportedAt:r=new Date}){const i=[];for(const a of n){if("user"!==a.type&&"assistant"!==a.type)continue;const e=zt(a,s);e&&i.push(`## ${"user"===a.type?s.userMessage:s.assistantMessage}\n\n${e}`)}const o=[`# ${qt(e)||t.sessionId}`,"",`- ${s.agent}: ${_t(t.agent)}`,`- ${s.sessionId}: \`${t.sessionId}\``,`- ${s.workingDirectory}: \`${t.cwd}\``,`- ${s.createdAt}: ${t.createdAt}`,`- ${s.exportedAt}: ${r.toISOString()}`];return{markdown:i.length>0?`${o.join("\n")}\n\n${i.join("\n\n")}`:o.join("\n"),messageCount:i.length}}({title:n,session:e,messages:t.filter(e=>"info"!==e.type).map(e=>({type:e.role,content:"assistant"===e.role?Ft(e.content):e.content,images:e.images})),labels:{agent:"Agent",sessionId:"Session",workingDirectory:"Working directory",createdAt:"Created",exportedAt:"Exported",userMessage:"User",assistantMessage:"Assistant",attachedImage:"Attachment"}});return{title:n,markdown:s}}(e,t).markdown}(e.activeSession,e.messages);!function(e,t){const n=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=utf-8"})),s=document.createElement("a");s.href=n,s.download=e,s.click(),URL.revokeObjectURL(n)}(function(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}(o(e.activeSession),e.activeSession.sessionId),t),await(navigator.clipboard?.writeText(t).catch(()=>{}))},[e.activeSession,e.messages]),p=t.useCallback(async()=>{if(!("Notification"in window))return e.setNotificationPermission("unsupported"),void e.setErrorText("Browser notifications are not supported.");const t=await Notification.requestPermission();e.notificationPermissionRef.current=t,e.setNotificationPermission(t),"granted"===t&&e.updateNotificationSettings({enabled:!0}),e.setStatusText("granted"===t?"Browser notifications enabled":"Browser notifications not enabled")},[e]),m=t.useCallback(async()=>{const t=e.pairingRef.current;await d(u().forget)&&e.pairingRef.current===t&&(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,on(),e.clientRef.current?.disconnect(),e.historyCacheRef.current={},e.historyCacheDaemonIdRef.current=null,e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setPairing(null),e.setDaemonMetadata(Wn),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),g=t.useCallback(t=>{t&&"default"===e.notificationPermission?p():e.updateNotificationSettings({enabled:t})},[e,p]),v=t.useCallback(t=>{e.connectWithPairingRef.current(t,!0)},[e]),y=t.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),b=t.useCallback(t=>{e.setActiveSessionId(t.sessionId),e.setRenameTitle(t.customTitle??t.title??""),e.setDetailsOpen(!0)},[e]),w=t.useCallback((t,n)=>{const s=h(n);e.updateSessionListPreferences(e=>({...e,directoryTags:f(e.directoryTags,t,s)}))},[e]),x=t.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),S=t.useCallback(async t=>{try{const n=ft(t);if(!n)return;await _n(n),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),k=t.useRef(!1);return{runArchiveSync:i,skipArchiveSync:a,runAdminAction:c,exportActiveSession:l,clearPairing:m,setNotificationsEnabled:g,connectSavedTarget:v,forgetSavedTarget:y,openSessionDetails:b,editFolderTags:w,browseFolder:x,copyResumeCommand:S,resumeInTerminal:t.useCallback(async t=>{if(k.current)return;const n=r(),s=e.pairingRef.current?.daemonId;if(s&&n.resumeInTerminal&&n.isLocalDaemon?.(s)){k.current=!0;try{const r=e.clientRef.current;if(!r)throw new Error("Not connected");await r.request({action:"session.release",id:r.makeId("release"),sessionId:t.sessionId,agent:t.agent}),await n.resumeInTerminal({...t,daemonId:s,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(i){e.setErrorText(String(i).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{k.current=!1}}},[e])}}({clientRef:Ae,pairingRef:qe,connectWithPairingRef:Ne,notificationPermissionRef:Pe,intentionalDisconnectRef:He,connectionAttemptIdRef:$e,historyCacheRef:we,historyCacheDaemonIdRef:Fe,messagesSessionIdRef:ne,lastHistorySessionIdRef:I,displaySessions:Y,pairing:E,t:Pt,archiveSyncBusy:Vt,daemonMetadata:Z,activeSession:pe,messages:xe,notificationPermission:X,savedTargets:It,setArchiveSyncBusy:Qt,setArchiveSyncStatus:Gt,setSessions:M,setAdmin:Bt,setErrorText:R,setNotificationPermission:Kt,setStatusText:Ue,setMessages:oe,setPairing:We,setDaemonMetadata:Ut,setPhase:Be,setActiveSessionId:N,setRenameTitle:K,setDetailsOpen:$t,setControlTab:J,updateSessionListPreferences:Dt,requestSessions:ae,refreshDaemonMetadata:Me,updateNotificationSettings:Te,saveTargets:jt,listDirectory:ue}),{listSessionModels:_s,applyToAllSessions:Vs}=function(e,n,s){const r=t.useRef(s);return r.current=s,{listSessionModels:t.useCallback(async t=>{const n=e.current;return n?.isConnected?(await n.request({action:"models.list",id:n.makeId("models"),agent:t})).options??[]:[]},[e]),applyToAllSessions:async(t,s)=>{const i=e.current;if(!i?.isConnected)throw new Error("not_connected");let o=!1;const a=i.onClose(()=>{o=!0});try{return await async function(e,t){const n=new Map,s=new Set;let r;do{if(!t.isCurrentConnection())throw new Error("connection_changed");const e=await t.request({action:"sessions.list",id:t.nextId(),limit:500,cursor:r,skipGitMetadata:!0});if(!Array.isArray(e?.sessions))throw new Error("invalid_session_list");for(const t of e.sessions)t.sessionId.startsWith("pending_")||n.set(t.sessionId,t);if(r=e.nextCursor,r){const e=JSON.stringify(r);if(s.has(e))throw new Error("repeated_cursor");s.add(e)}}while(r);const i={updated:0,failed:0};for(const o of n.values()){const n=e.models[o.agent],s={...void 0!==n?{model:n}:{},...void 0!==e.fastMode?{fastMode:e.fastMode}:{}};try{if(!t.isCurrentConnection())throw new Error("connection_changed");if(await t.request({action:"session.configure",id:t.nextId(),sessionId:o.sessionId,...s}),!t.isCurrentConnection())throw new Error("connection_changed");t.onApplied(o,s),i.updated++}catch{i.failed++}t.onProgress?.({...i})}return i}(t,{nextId:()=>i.makeId("bulkcfg"),request:e=>i.request(e,{timeoutMs:15e3}),isCurrentConnection:()=>!o&&e.current===i&&i.isConnected,onProgress:s,onApplied:(e,t)=>{r.current(e.sessionId,t),n(n=>n.map(n=>n.sessionId===e.sessionId?{...n,...t}:n))}})}finally{a()}}}}(Ae,M,Xt.applyConfirmedSettings),Xs=t.useCallback(async e=>{const t=Ae.current;if(!t?.isConnected)throw new Error(Pt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[Ae,Pt.webSocketNotConnected]),tr="denied"===X||"unsupported"===X,lr=Boolean(Z.version&&Z.latestVersion&&Vn(Z.version,Z.latestVersion)),dr=E?.daemonId,ur=Boolean(dr&&Q[dr]),hr=Boolean(dr&&G[dr]),fr=function(e){const[n,s]=t.useState(null),r=e.clientRef.current,i=(t,n,s)=>{const r=n.map(t=>t.content||e.t.failedSendImages(t.images?.length??0)).join(" / ");return function(e,t,n,s){switch(os(s)){case"turn-changed":return e.queueGuideTurnChanged;case"no-active-turn":return e.queueGuideNoActiveTurn;case"not-ready":return e.queueSessionNotReady;case"stale-selection":return e.queueSelectionChanged;case"pending-request":return e.queuePendingRequest;case"unsupported":return e.queueGuideUnsupported}const r=s instanceof Error?s.message:String(s);return s instanceof ln?e.queueRequestRejected(t,n,r):e.queueRequestFailed(t,n,/timeout|timed out/i.test(r)?e.queueRequestTimeout:r)}(e.t,t,r,s)},o=e.activeSessionId,{busy:a,begin:c}=function(e,n){const s=t.useRef(new Set),[r,i]=t.useState([]),o=t=>t.client===e&&t.sessionId===n;return{busy:r.some(o),begin:()=>{if(!e||!n||[...s.current].some(o))return null;const t={client:e,sessionId:n};return s.current.add(t),i([...s.current]),()=>{s.current.delete(t),i([...s.current])}}}}(r,o),l=()=>e.clientRef.current===r,d=async()=>{l()&&await Promise.allSettled([e.requestSessions({force:!0,preserveLoaded:!0}),...e.activeSession?[e.requestHistory(e.activeSession,{refresh:!0})]:[]])},u=t=>n?.sessionId===o&&n.action===t&&n.runtime===e.activeSession?.runtime,h="daemonActive"===e.activeSession?.runtime.state&&!e.activeQueue.some(e=>e.waitingForStartup),f=!o||Boolean(e.pendingApprovals[o]||e.pendingQuestions[o]),m=!f&&!0===r?.supportsSessionSteer&&!!o&&e.respondingSessions.has(o)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),g=!f&&h&&!u("sendNow")&&!0===r?.supportsQueueSendNow,v=function(e){return t.useCallback(async t=>{const n=e.clientRef.current;if(!n?.isConnected||!e.activeSessionId||!t.clientMessageId)return;const s=e.activeSessionId,r=e.begin();if(r){e.setErrorText(null);try{const r=await n.request({action:"session.queue.cancel",id:n.makeId("queue_cancel"),sessionId:s,clientMessageId:t.clientMessageId},{timeoutMs:cs});if(e.clientRef.current!==n)return;if(e.confirmPendingQueueRemoval(s,[t.clientMessageId]),0===r?.removed&&!r.interrupted)return await e.refreshState(),void(e.clientRef.current===n&&e.activeSessionIdRef.current===s&&p({message:e.t.queueSelectionChanged,notice:!0}));if(r?.interrupted||e.removeCachedMessage(s,t.clientMessageId),e.updateSessionDraft(s,[is(e.composerDraftsRef.current,s),t.content].filter(Boolean).join("\n\n")),t.images?.length){const n=[...new Set(t.images)];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...n.filter(e=>!t.has(e)).map(e=>({path:e,name:wn(e),type:"image/*",size:0}))]})}r?.interrupted&&e.activeSessionIdRef.current===s&&p({message:e.t.queueWithdrawalInterrupted,notice:!0})}catch(i){if(e.clientRef.current!==n)return;await e.refreshState(),e.clientRef.current===n&&e.activeSessionIdRef.current===s&&e.setErrorText(i instanceof Error?i.message:String(i))}finally{r()}}},[e])}({...e,begin:c,refreshState:d});return{busy:a,canGuide:m,canSendNow:g,onAction:async(t,n)=>{if(!o||!r?.isConnected||!("guide"===n?m:g))return;const a=new Set(t.map(e=>e.clientMessageId).filter(Boolean)),u=e.activeQueue.filter(e=>e.clientMessageId&&a.has(e.clientMessageId));if(!u.length)return;const h=c();if(!h)return;e.setErrorText(null);const f=new Set;for(const s of u)e.setCachedMessageDelivery(o,s.clientMessageId,"sending",s);const p=t=>{f.add(t.clientMessageId),e.setCachedMessageDelivery(o,t.clientMessageId,"delivered"),e.confirmPendingQueueRemoval(o,[t.clientMessageId])};try{if("sendNow"===n){if(await r.request({action:"session.queue.sendNow",id:r.makeId("queue_now"),sessionId:o,clientMessageIds:u.map(e=>e.clientMessageId)},{timeoutMs:cs}),!l())return;u.forEach(p)}else for(const e of u){if(!l())return;if(await r.request({action:"session.steer",id:r.makeId("queue_guide"),sessionId:o,clientMessageId:e.clientMessageId,message:e.content,images:e.images},{timeoutMs:cs}),!l())return;p(e)}}catch(v){if(!l())return;const t=os(v);let r=!1;for(const n of u)f.has(n.clientMessageId)||(r="delivered"!==e.setCachedMessageDelivery(o,n.clientMessageId,"failed")||r);t&&("no-active-turn"===t&&e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(o),t}),e.activeSession&&s({sessionId:o,action:n,runtime:e.activeSession.runtime}),await d()),r&&l()&&e.activeSessionIdRef.current===o&&e.setErrorText(i("guide"===n?e.t.queueGuide:e.t.queueSendNow,u.filter(e=>!f.has(e.clientMessageId)),v))}finally{h()}},onCollect:async t=>{if(!o||!r?.isConnected)return;const n=new Set(t.map(e=>e.clientMessageId).filter(e=>!!e)),s=e.activeQueue.filter(e=>e.clientMessageId&&n.has(e.clientMessageId));if(s.length<2)return;const a=c();if(a){e.setErrorText(null);try{const t=await r.request({action:"session.queue.collect",id:r.makeId("queue_collect"),sessionId:o,clientMessageIds:s.map(e=>e.clientMessageId)},{timeoutMs:cs});if(!l())return;const i=t.entries;if(!Array.isArray(i))throw new Error("Invalid queue collection response");const a=i.map(e=>e.content).filter(e=>e.trim()).join("\n\n"),c=e=>[e,a].filter(e=>e.trim()).join("\n\n");e.updateSessionDraft(o,c(is(e.composerDraftsRef.current,o)));const d=[...new Set(i.flatMap(e=>e.images??[]))];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...d.filter(e=>!t.has(e)).map(e=>({path:e,name:wn(e),type:"image/*",size:0}))]}),e.confirmPendingQueueRemoval(o,[...n]);for(const n of i)n.clientMessageId&&e.removeCachedMessage(o,n.clientMessageId)}catch(u){if(!l())return;os(u)&&await d(),l()&&e.activeSessionIdRef.current===o&&e.setErrorText(i(e.t.queueCollectAll,s,u))}finally{a()}}},onCancel:v}}(e);return{...e,setModel:Xt.setModel,setEffort:Xt.setEffort,setFastMode:Xt.setFastMode,queueControls:fr,listSessionModels:_s,applyToAllSessions:Vs,loadDirectoryGitMetadata:Xs,rewindMessage:n,handleSessionCommandResponse:Jt,handleServerMessage:Zt,failedSend:tn,dismissFailedSend:nn,retryFailedSend:cn,stagePendingSession:Yt,sendDraft:un,sendQuickReply:vn,respondApproval:An,respondQuestion:Fn,cancelQuestion:qn,setQuestionChoice:On,requestActiveAction:$n,interruptActiveSession:zn,retrySessions:Hn,updateApprovalMode:async e=>{Xt.setApprovalMode(e),pe&&!T[pe.sessionId]&&await Kn(e)},cancelQueuedTurn:fr.onCancel,setSessionPinned:Gn,setSessionArchived:Xn,deleteSession:Yn,updatePinned:es,updateArchived:ts,renameSession:ps,runArchiveSync:ms,skipArchiveSync:ys,runAdminAction:bs,exportActiveSession:ws,clearPairing:xs,setNotificationsEnabled:Ss,connectSavedTarget:ks,forgetSavedTarget:Is,openSessionDetails:Rs,editFolderTags:Es,browseFolder:Ms,copyResumeCommand:As,resumeInTerminal:Fs,notificationsBlocked:tr,hasDaemonUpdate:lr,activeDaemonId:dr,archiveSynced:ur,archiveSyncDismissed:hr}}();return n.jsx(nt,{scopeKey:Ye(e.pairing?.daemonId,e.activeSessionId),children:n.jsx(On,{workspace:e,children:n.jsx(cu,{workspace:e})})})}},Symbol.toStringTag,{value:"Module"}));export{$,Ni as A,q as B,O as C,ie as D,Rr as E,dl as F,ae as G,Tn as H,le as I,Si as J,Ci as K,pe as L,F as M,ke as N,rt as O,Ce as P,Ze as Q,Re as R,Pe as S,ze as T,sn as U,ct as V,An as W,Be as X,dt as Y,Ue as Z,_,ai as a,se as a0,ee as a1,qn as a2,ta as a3,ea as a4,Bo as a5,Wo as a6,Uo as a7,Xo as a8,Vo as a9,hn as aA,qo as aB,lu as aC,ha as aa,sa as ab,Fo as ac,ca as ad,aa as ae,Zo as af,Yo as ag,_o as ah,Qd as ai,Ud as aj,hi as ak,Gd as al,Dn as am,Jd as an,Xd as ao,Yd as ap,Ao as aq,yc as ar,je as as,Wr as at,gc as au,Ne as av,z as aw,Oe as ax,D as ay,qe as az,ri as b,wn as c,xn as d,V as e,kc as f,_n as g,mi as h,no as i,G as j,Dt as k,Vn as l,Mr as m,te as n,Ri as o,fi as p,ki as q,Yr as r,wr as s,Ii as t,ui as u,Js as v,co as w,Mi as x,Ti as y,Ei as z};