vibelet 1.2.250 → 1.2.251

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 (146) hide show
  1. package/dist/index.cjs +7 -1
  2. package/dist/inventory-scan-worker.cjs +1 -1
  3. package/dist/runtime-version.cjs +1 -1
  4. package/dist/web/assets/App-Bx92ZYqP.js +2 -0
  5. package/dist/web/assets/App-C7OILF5b.css +97 -0
  6. package/dist/web/assets/{BrowserControlPanel-BuNWFba-.js → BrowserControlPanel-BSBCQsTC.js} +1 -1
  7. package/dist/web/assets/ChatPane-CNkEpPZD.js +1 -0
  8. package/dist/web/assets/{ChipGroup-JUUZjxeF.js → ChipGroup-BGteDQAS.js} +1 -1
  9. package/dist/web/assets/ComposerMenus-7XnPTSod.js +1 -0
  10. package/dist/web/assets/{DiffDrawer-BOo0z8j9.js → DiffDrawer-DLUBB9ig.js} +1 -1
  11. package/dist/web/assets/FilesControlPanel-BC8Kvjf2.js +1 -0
  12. package/dist/web/assets/GlobalPendingDialog-ZjYyhVoG.js +1 -0
  13. package/dist/web/assets/{ImageViewer-B3zT7wZQ.js → ImageViewer-D_-eK1aP.js} +1 -1
  14. package/dist/web/assets/InteractionPolish-CQwU9CEi.css +1 -0
  15. package/dist/web/assets/{LanguageSettingsPanel-BZOXQSpl.js → LanguageSettingsPanel-Btyc58mw.js} +1 -1
  16. package/dist/web/assets/{MarkdownModePanel-DMtxlov8.js → MarkdownModePanel-q63q8r9N.js} +1 -1
  17. package/dist/web/assets/{NewSessionDialog-eX_6NPbk.css → NewSessionDialog-CWW1T1s7.css} +1 -1
  18. package/dist/web/assets/NewSessionDialog-Cqymzgm4.js +1 -0
  19. package/dist/web/assets/{NotificationSettingsPanel-DNnl9a9p.js → NotificationSettingsPanel-CKYNiUya.js} +1 -1
  20. package/dist/web/assets/{PanelFind-D3fC27md.js → PanelFind-BA1eUXgS.js} +1 -1
  21. package/dist/web/assets/{RemoteLifeOSBlock-B31t36fb.js → RemoteLifeOSBlock-Bq3YQBy7.js} +2 -2
  22. package/dist/web/assets/RemoteWorkspaceSettings-Cs_zzqpf.css +1 -0
  23. package/dist/web/assets/RemoteWorkspaceSettings-D8_jQ7Wt.js +1 -0
  24. package/dist/web/assets/{SessionTerminalPanel-nTZ0CuII.js → SessionTerminalPanel-Dmt2m_B6.js} +2 -2
  25. package/dist/web/assets/{SpeechInputSettingsPanel-Dbtr1xpS.js → SpeechInputSettingsPanel-9qu4_cQx.js} +1 -1
  26. package/dist/web/assets/{ThemeSettingsPanel-BKow3xYE.js → ThemeSettingsPanel-zefRQEDV.js} +1 -1
  27. package/dist/web/assets/{__vite-browser-external-2447137e-CaO64LnT.js → __vite-browser-external-2447137e-BMiSckAV.js} +1 -1
  28. package/dist/web/assets/_baseMerge-CwDZKfvJ.js +1 -0
  29. package/dist/web/assets/{_initCloneObject-CgHgrY9n.js → _initCloneObject-C781OlVa.js} +1 -1
  30. package/dist/web/assets/{abnfDiagram-VRR7QNED-g0J0uJH0.js → abnfDiagram-VRR7QNED-THI3SIgB.js} +1 -1
  31. package/dist/web/assets/arc-DgeTKeM5.js +1 -0
  32. package/dist/web/assets/{architectureDiagram-ZJ3FMSHR-P688vuM0.js → architectureDiagram-ZJ3FMSHR-CPVnaW5G.js} +1 -1
  33. package/dist/web/assets/{arrow-left-BKWZB-GS.js → arrow-left-dANl3leX.js} +1 -1
  34. package/dist/web/assets/{arrow-right-D37ZKCxV.js → arrow-right-DTaF5t16.js} +1 -1
  35. package/dist/web/assets/{blockDiagram-677ZJIJ3-DVQABFjb.js → blockDiagram-677ZJIJ3-BDME3ZFA.js} +1 -1
  36. package/dist/web/assets/{c4Diagram-LMCZKHZV-XVayABM3.js → c4Diagram-LMCZKHZV-CMY3o7XE.js} +1 -1
  37. package/dist/web/assets/channel-BE7FnnNv.js +1 -0
  38. package/dist/web/assets/chevron-up-C3_IR2td.js +1 -0
  39. package/dist/web/assets/{chunk-2Q5K7J3B-8qckFKlv.js → chunk-2Q5K7J3B-Brbuto5C.js} +1 -1
  40. package/dist/web/assets/{chunk-32BRIVSS-ZfILJ0hp.js → chunk-32BRIVSS-BGCuhDXk.js} +1 -1
  41. package/dist/web/assets/{chunk-5VM5RSS4-BkUINLoD.js → chunk-5VM5RSS4-D85xFHwk.js} +1 -1
  42. package/dist/web/assets/{chunk-EX3LRPZG-lcNciUr3.js → chunk-EX3LRPZG-W6U7GsD7.js} +1 -1
  43. package/dist/web/assets/{chunk-JWPE2WC7-D5YKZJ83.js → chunk-JWPE2WC7-CKdx8e0r.js} +1 -1
  44. package/dist/web/assets/{chunk-MOJQB5TN--5_60IeM.js → chunk-MOJQB5TN-Cjf1dDyf.js} +1 -1
  45. package/dist/web/assets/{chunk-RYQCIY6F-BnJepqNX.js → chunk-RYQCIY6F-DFxqNYlG.js} +1 -1
  46. package/dist/web/assets/{chunk-V7JOEXUC-C4JsJhyH.js → chunk-V7JOEXUC-lwXYy3Zq.js} +1 -1
  47. package/dist/web/assets/{chunk-VR4S4FIN-D5FvSfaQ.js → chunk-VR4S4FIN-BxiP-OR0.js} +1 -1
  48. package/dist/web/assets/{chunk-XXDRQBXY-C5OUOhJR.js → chunk-XXDRQBXY-BhED1rK6.js} +1 -1
  49. package/dist/web/assets/classDiagram-OUVF2IWQ-C0-VAw-b.js +1 -0
  50. package/dist/web/assets/classDiagram-v2-EOCWNBFH-C0-VAw-b.js +1 -0
  51. package/dist/web/assets/{clsx-DoZLeicy.js → clsx-Dy3K9oBb.js} +1 -1
  52. package/dist/web/assets/{collectMessageImages-CLhjY1R-.js → collectMessageImages-DEnoDhBs.js} +1 -1
  53. package/dist/web/assets/composerOptions-0DZvXA1-.js +1 -0
  54. package/dist/web/assets/{cose-bilkent-JH36ORCC-Ddb7CSGw.js → cose-bilkent-JH36ORCC-DC9M3QOS.js} +1 -1
  55. package/dist/web/assets/{cynefin-VYW2F7L2-CEDiFzaT.js → cynefin-VYW2F7L2-D1LRWQeS.js} +1 -1
  56. package/dist/web/assets/{cynefinDiagram-TSTJHNR4-C6u3xLGy.js → cynefinDiagram-TSTJHNR4-BJvzO8nK.js} +1 -1
  57. package/dist/web/assets/{dagre-VKFMJZFB-DtCUfTd8.js → dagre-VKFMJZFB-u4EU1mWb.js} +1 -1
  58. package/dist/web/assets/{diagram-FQU43EPY-C0_HvALH.js → diagram-FQU43EPY-DfvPNd6F.js} +1 -1
  59. package/dist/web/assets/{diagram-G47NLZAW-Bsyy_urB.js → diagram-G47NLZAW-DlJwWs1J.js} +1 -1
  60. package/dist/web/assets/{diagram-NH7WQ7WH-CdJtYqSJ.js → diagram-NH7WQ7WH-DcgpOjQV.js} +1 -1
  61. package/dist/web/assets/{diagram-OA4YK3LP-BvOArA9-.js → diagram-OA4YK3LP-BrNCuljO.js} +1 -1
  62. package/dist/web/assets/{diagram-WEI45ONY-DCZyDgVZ.js → diagram-WEI45ONY-DxT28KUR.js} +1 -1
  63. package/dist/web/assets/{ebnfDiagram-CCIWWBDH-BUD-Vp1u.js → ebnfDiagram-CCIWWBDH-FD63emzf.js} +1 -1
  64. package/dist/web/assets/{erDiagram-Q63AITRT-D80Jrt7q.js → erDiagram-Q63AITRT-COEH4rgh.js} +1 -1
  65. package/dist/web/assets/{file-editor-FileCodeEditor-C1eB-N6w.js → file-editor-FileCodeEditor-B0qv9YKs.js} +2 -2
  66. package/dist/web/assets/{file-editor-ObsidianCodeEditor-CbYkHjhQ.js → file-editor-ObsidianCodeEditor-q_YWJSDk.js} +1 -1
  67. package/dist/web/assets/file-editor-ObsidianFileEditor-bdzeuwke.js +2 -0
  68. package/dist/web/assets/{file-editor-index-BXupf89-.js → file-editor-index-B6XepRuc.js} +1 -1
  69. package/dist/web/assets/{file-editor-index-DuqNWTkz.js → file-editor-index-BUPn4zC8.js} +1 -1
  70. package/dist/web/assets/{file-editor-index-Dc4mA3Mx.js → file-editor-index-BmcxkKR_.js} +1 -1
  71. package/dist/web/assets/{file-editor-index-ORJkxheE.js → file-editor-index-C-sivrT3.js} +1 -1
  72. package/dist/web/assets/{file-editor-index-D3hWXNQc.js → file-editor-index-C8hW6Muj.js} +1 -1
  73. package/dist/web/assets/{file-editor-index-CP7DVsyc.js → file-editor-index-CthnNAMC.js} +1 -1
  74. package/dist/web/assets/{file-editor-index-Ce_Hrot9.js → file-editor-index-DOP_6x0k.js} +1 -1
  75. package/dist/web/assets/{file-editor-index-BEhJJ-2S.js → file-editor-index-Db8cbNln.js} +1 -1
  76. package/dist/web/assets/{file-editor-index-CIj8OyuX.js → file-editor-index-Dg5e3Cpy.js} +1 -1
  77. package/dist/web/assets/{file-editor-index-DX8Fwz0S.js → file-editor-index-DqKTONJ4.js} +1 -1
  78. package/dist/web/assets/{file-editor-index-CrvkFqLZ.js → file-editor-index-JhH0nqee.js} +1 -1
  79. package/dist/web/assets/{file-editor-index-7BDUBERb.js → file-editor-index-WDJmssCC.js} +1 -1
  80. package/dist/web/assets/{file-editor-index-DL4CfMoo.js → file-editor-index-YBbEVrxT.js} +1 -1
  81. package/dist/web/assets/{flowDiagram-23GEKE2U-Bp-296xB.js → flowDiagram-23GEKE2U-kWBomx5I.js} +1 -1
  82. package/dist/web/assets/{folder-plus-mFYdi3vx.js → folder-plus-ChLrua3z.js} +1 -1
  83. package/dist/web/assets/ganttDiagram-NO4QXBWP-bd158wNu.js +1 -0
  84. package/dist/web/assets/{gitGraphDiagram-IHSO6WYX-AZjosTB3.js → gitGraphDiagram-IHSO6WYX-BsWMZB1T.js} +1 -1
  85. package/dist/web/assets/{highlighted-body-TPN3WLV5-Ras4GZ3t.js → highlighted-body-TPN3WLV5-BcvTxHra.js} +1 -1
  86. package/dist/web/assets/index-kcB9N5v8.js +2 -0
  87. package/dist/web/assets/{infoDiagram-FWYZ7A6U-F_UnDtTr.js → infoDiagram-FWYZ7A6U-DtvGyYt0.js} +1 -1
  88. package/dist/web/assets/{ishikawaDiagram-FXEZZL3T-BUluH5mf.js → ishikawaDiagram-FXEZZL3T-CHsj8iVR.js} +1 -1
  89. package/dist/web/assets/{journeyDiagram-5HDEW3XC-DQCNFXSj.js → journeyDiagram-5HDEW3XC-Ben3XW9L.js} +1 -1
  90. package/dist/web/assets/{kanban-definition-HUTT4EX6-BiCguUtw.js → kanban-definition-HUTT4EX6-w1H0lvRK.js} +1 -1
  91. package/dist/web/assets/{key-round-dym69oi9.js → key-round-Csanuqei.js} +1 -1
  92. package/dist/web/assets/{layout-CAp4KseL.js → layout-DvVF2R1Q.js} +1 -1
  93. package/dist/web/assets/{linear-CZqAZmMb.js → linear-CYqpDCXS.js} +1 -1
  94. package/dist/web/assets/{map-XtUTTYLw.js → map-yP9qyz-l.js} +1 -1
  95. package/dist/web/assets/{mermaid-O7DHMXV3-DcfB_Nfq.js → mermaid-O7DHMXV3-DUoHFycq.js} +2 -2
  96. package/dist/web/assets/{mermaid.core-B-9Lh0Bf.js → mermaid.core-CSuHyCbU.js} +2 -2
  97. package/dist/web/assets/{mic-Bs_YstUD.js → mic-D6yq4BVC.js} +1 -1
  98. package/dist/web/assets/{mindmap-definition-LN4V7U3C-0wq70AWv.js → mindmap-definition-LN4V7U3C-BariZ1mC.js} +1 -1
  99. package/dist/web/assets/newSessionDefaults-DY7-PuSf.js +1 -0
  100. package/dist/web/assets/pegDiagram-2B236MQR-DsjvsiG-.js +1 -0
  101. package/dist/web/assets/{pieDiagram-ENE6RG2P-DzMu5QtI.js → pieDiagram-ENE6RG2P-CVDkx6T3.js} +1 -1
  102. package/dist/web/assets/{quadrantDiagram-ABIIQ3AL-CzeKWuoN.js → quadrantDiagram-ABIIQ3AL-CZfhv8B5.js} +1 -1
  103. package/dist/web/assets/{railroadDiagram-RFXS5EU6-Bk1xGINt.js → railroadDiagram-RFXS5EU6-DPiV-o4k.js} +1 -1
  104. package/dist/web/assets/{requirementDiagram-TGXJPOKE-CUXgKiw9.js → requirementDiagram-TGXJPOKE-ifd3KNkN.js} +1 -1
  105. package/dist/web/assets/{sankeyDiagram-HTMAVEWB-Cz4U7qMk.js → sankeyDiagram-HTMAVEWB-BTgBAMv9.js} +1 -1
  106. package/dist/web/assets/{sequenceDiagram-DBY2YBRQ-B-bhALmV.js → sequenceDiagram-DBY2YBRQ-6-7v8n8u.js} +1 -1
  107. package/dist/web/assets/{sizeCapture-X5ZJPWSS-BV7vYGtd.js → sizeCapture-X5ZJPWSS-BRFGoPEh.js} +1 -1
  108. package/dist/web/assets/{square-CnIgvIvG.js → square-Dl4fOYPP.js} +1 -1
  109. package/dist/web/assets/{stateDiagram-2N3HPSRC-D_OfgMzy.js → stateDiagram-2N3HPSRC-BBiXuN7R.js} +1 -1
  110. package/dist/web/assets/stateDiagram-v2-6OUMAXLB-DRJJe0JN.js +1 -0
  111. package/dist/web/assets/{swimlanes-5IMT3BWC-CR_34bdL.js → swimlanes-5IMT3BWC-C40_UKFy.js} +2 -2
  112. package/dist/web/assets/swimlanesDiagram-G3AALYLV-DEaTTKbV.js +1 -0
  113. package/dist/web/assets/{timeline-definition-FHXFAJF6-B0RjwjZL.js → timeline-definition-FHXFAJF6-cuYaryrF.js} +1 -1
  114. package/dist/web/assets/useComposerCompletion-DBl1CTPC.js +1 -0
  115. package/dist/web/assets/{vennDiagram-L72KCM5P-B9onja4E.js → vennDiagram-L72KCM5P-BjSt5IQl.js} +1 -1
  116. package/dist/web/assets/{wardleyDiagram-EHGQE667-DQNpXRcp.js → wardleyDiagram-EHGQE667-DAJYQgOm.js} +1 -1
  117. package/dist/web/assets/{xychartDiagram-FW5EYKEG-Dlw9N9fP.js → xychartDiagram-FW5EYKEG-DwQxHkEv.js} +1 -1
  118. package/dist/web/assets/zap-D3JafXHq.js +1 -0
  119. package/dist/web/index.html +1 -1
  120. package/dist/web/obsidian-editor-assets.json +1 -1
  121. package/package.json +1 -1
  122. package/dist/web/assets/App-CqANyaMK.css +0 -97
  123. package/dist/web/assets/App-nYpLxr2P.js +0 -2
  124. package/dist/web/assets/ChatPane-FOqiEb_l.js +0 -1
  125. package/dist/web/assets/ComposerMenus-Cmy67eKP.js +0 -1
  126. package/dist/web/assets/FilesControlPanel-DdgfLvcS.js +0 -1
  127. package/dist/web/assets/GlobalPendingDialog-BHvNAgCA.js +0 -1
  128. package/dist/web/assets/InteractionPolish-Nkww8pqM.css +0 -1
  129. package/dist/web/assets/NewSessionDialog-Cca7q4mL.js +0 -1
  130. package/dist/web/assets/RemoteWorkspaceSettings-7jz8oX59.css +0 -1
  131. package/dist/web/assets/RemoteWorkspaceSettings-tLFMGBTO.js +0 -1
  132. package/dist/web/assets/_baseMerge-YHvLFG89.js +0 -1
  133. package/dist/web/assets/arc-CSmO3u1k.js +0 -1
  134. package/dist/web/assets/channel-CfHLFf-p.js +0 -1
  135. package/dist/web/assets/chevron-up--OL3xO3m.js +0 -1
  136. package/dist/web/assets/classDiagram-OUVF2IWQ-CU3UoiIZ.js +0 -1
  137. package/dist/web/assets/classDiagram-v2-EOCWNBFH-CU3UoiIZ.js +0 -1
  138. package/dist/web/assets/file-editor-ObsidianFileEditor-BcW1PoxX.js +0 -2
  139. package/dist/web/assets/ganttDiagram-NO4QXBWP-yp0x7W6c.js +0 -1
  140. package/dist/web/assets/index-D7ToIS_p.js +0 -2
  141. package/dist/web/assets/pegDiagram-2B236MQR-DMaSxFNx.js +0 -1
  142. package/dist/web/assets/shield-check-DHU4OMNx.js +0 -1
  143. package/dist/web/assets/stateDiagram-v2-6OUMAXLB-BtN1UWrw.js +0 -1
  144. package/dist/web/assets/swimlanesDiagram-G3AALYLV-Bk0M29A8.js +0 -1
  145. package/dist/web/assets/useComposerCompletion-C35JoOnf.js +0 -1
  146. package/dist/web/assets/zap-CVmMJ_Jz.js +0 -1
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ImageViewer-B3zT7wZQ.js","assets/index-D7ToIS_p.js","assets/index-76-ZfKAK.css","assets/arrow-right-D37ZKCxV.js","assets/arrow-left-BKWZB-GS.js","assets/ImageViewer-DilwNKHW.css","assets/DiffDrawer-BOo0z8j9.js","assets/git-actions-DHCQ17VG.js","assets/RemoteWorkspaceSettings-tLFMGBTO.js","assets/ComposerMenus-Cmy67eKP.js","assets/chevron-up--OL3xO3m.js","assets/ComposerMenus-8RI97wiO.css","assets/zap-CVmMJ_Jz.js","assets/key-round-dym69oi9.js","assets/RemoteWorkspaceSettings-7jz8oX59.css","assets/FilesControlPanel-DdgfLvcS.js","assets/folder-plus-mFYdi3vx.js","assets/__vite-browser-external-2447137e-CaO64LnT.js","assets/FilesControlPanel-JMh8U1IC.css","assets/LanguageSettingsPanel-BZOXQSpl.js","assets/ChipGroup-JUUZjxeF.js","assets/ThemeSettingsPanel-BKow3xYE.js","assets/NotificationSettingsPanel-DNnl9a9p.js","assets/SpeechInputSettingsPanel-Dbtr1xpS.js","assets/mic-Bs_YstUD.js","assets/ChatPane-FOqiEb_l.js","assets/useComposerCompletion-C35JoOnf.js","assets/shield-check-DHU4OMNx.js","assets/useComposerCompletion-B0xUeljY.css","assets/square-CnIgvIvG.js","assets/index-S4bzeLfy.js","assets/ChatPane-CWKGXZWT.css","assets/InteractionPolish-Nkww8pqM.css","assets/BrowserControlPanel-BuNWFba-.js","assets/PanelFind-D3fC27md.js","assets/PanelFind-Du02CWMm.css","assets/SessionTerminalPanel-nTZ0CuII.js","assets/NewSessionDialog-Cca7q4mL.js","assets/NewSessionDialog-eX_6NPbk.css","assets/mermaid-O7DHMXV3-DcfB_Nfq.js","assets/index-8TM1eFHE.js","assets/collectMessageImages-CLhjY1R-.js","assets/clsx-DoZLeicy.js","assets/index-1M7_HtDu.js","assets/mermaid-O7DHMXV3-rMhXRrUE.css","assets/MarkdownModePanel-DMtxlov8.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-C1eB-N6w.js","assets/file-editor-CodeHighlight-aQ9kP3Wv.js","assets/CodeHighlight-aMZr054w.css","assets/FileCodeEditor-DX7Mn5Bu.css","assets/file-editor-ObsidianCodeEditor-CbYkHjhQ.js","assets/file-editor-index-Dc4mA3Mx.js","assets/file-editor-index-BEhJJ-2S.js","assets/file-editor-index-CrvkFqLZ.js","assets/file-editor-index-Br9mmThB.js","assets/file-editor-index-zEnXm9gB.js","assets/file-editor-index-BXupf89-.js","assets/RemoteLifeOSBlock-B31t36fb.js","assets/RemoteLifeOSBlock-D7P9Ftlh.css","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-BcW1PoxX.js","assets/purify.es-BNLkGfTg.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-YHvLFG89.js","assets/_initCloneObject-CgHgrY9n.js","assets/ObsidianFileEditor-D2QjjPA3.css","assets/GlobalPendingDialog-BHvNAgCA.js"])))=>i.map(i=>d[i]);
2
- import{c as e,r as t,j as n,h as s,w as r,i,x as o,t as a,b as c,d as l,y as d,z as u,A as h,B as m,m as f,C as p,o as g,F as v,G as y,p as w,H as b,I as S,J as x,f as I,S as k,_ as C,u as R,E,k as j,K as M,L as A,M as T}from"./index-D7ToIS_p.js";const N=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"}]]),P=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"}]]),L=e("arrow-left-right",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]),F=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"}]]),O=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"}]]),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"}]]),_=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"}]]),z=e("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),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("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"}]]),U=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"}]]),W=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"}]]),K=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"}]]),G=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"}]]),V=e("file-question-mark",[["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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]),Q=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"}]]),J=e("flip-horizontal-2",[["path",{d:"m3 7 5 5-5 5V7",key:"couhi7"}],["path",{d:"m21 7-5 5 5 5V7",key:"6ouia7"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]),Z=e("flip-vertical-2",[["path",{d:"m17 3-5 5-5-5h10",key:"1ftt6x"}],["path",{d:"m17 21-5-5-5 5h10",key:"1m0wmu"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]),X=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"}]]),Y=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"}]]),ee=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"}]]),te=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"}]]),ne=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"}]]),se=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"}]]),re=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"}]]),ie=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"}]]),oe=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ae=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"}]]),ce=e("maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]),le=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"}]]),de=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"}]]),ue=e("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),he=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),me=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),fe=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"}]]),pe=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"}]]),ge=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"}]]),ve=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"}]]),ye=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),we=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"}]]),be=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"}]]),Se=e("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),xe=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"}]]),Ie=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),ke=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"}]]),Ce=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"}]]),Re=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"}]]),Ee=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"}]]),je=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"}]]),Me=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),Ae=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"}]]),Te=e("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Ne=e("undo-2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]),Pe=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"}]]),De=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Le="vibelet:session-workspace-change",Fe="vibelet:session-workspace-before-remove",Oe="vibelet:session-workspace-removing";function qe(e){window.dispatchEvent(new CustomEvent(Le,{detail:e}))}function _e(e,t){window.dispatchEvent(new CustomEvent(Oe,{detail:{...e,removing:t}}))}function $e(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=$e(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}=He(e,t);return[n,s]}function He(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=$e(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),m=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]),f=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]),p=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=$e(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(Le,e),()=>window.removeEventListener(Le,e)},[u]),{value:h,set:m,setForScope:f,getForScope:p,getAll:g,updateAll:v,resolveScope:i}}function Be(e,t){return JSON.stringify([e??null,t??null])}function Ue(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}}function We(e){try{return new URL(e).href}catch{return e}}const Ke=t.createContext(null);function Ge({children:e,scopeKey:s}){const r=function(e="default"){const{remember:n,take:s,clear:r}=function(e){const n=t.useRef([]);return t.useEffect(()=>{const e=e=>{const t=e.detail;n.current=n.current.flatMap(e=>{const n=$e(e.scopeKey??"default",t);return null===n?[]:[{...e,scopeKey:n}]})};return window.addEventListener(Le,e),()=>window.removeEventListener(Le,e)},[]),{remember:t.useCallback(e=>{"diff"===e.kind||e.emptyPlaceholder||(n.current=[...n.current.filter(t=>t.id!==e.id),e].slice(-30))},[]),take:t.useCallback(()=>{const t=n.current.findLastIndex(t=>(t.scopeKey??"default")===e);if(t<0)return null;const[s]=n.current.splice(t,1);return{...s,id:crypto.randomUUID(),url:s.currentUrl||s.url,emptyPlaceholder:!1,autoOpenTerminal:!0}},[e]),clear:t.useCallback(()=>{n.current=[]},[])}}(e),i=t.useRef(null),o=t.useRef(null),a=t.useRef({browser:0,terminal:0}),[c,l]=t.useState(0),[d,u]=t.useState([]),h=d.filter(t=>(t.scopeKey??"default")===e),{value:m,set:f,setForScope:p}=He(JSON.stringify([e,c]),null),{value:g,set:v,setForScope:y,getForScope:w}=He(JSON.stringify([e,c]),()=>({}));t.useEffect(()=>{const e=e=>{const t=e.detail;u(e=>e.flatMap(e=>{const n=$e(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(Le,e),()=>window.removeEventListener(Le,e)},[]);const[b,S]=t.useState({}),x=t.useCallback((t,n,s,r,i,o)=>{const c=crypto.randomUUID(),l="diff"===t?"center":"right",d=n;return"diff"!==t&&(n=`${n} ${++a.current[t]}`),u(a=>[...a,{id:c,kind:t,title:n,defaultTitle:d,cwd:s,session:r,scope:i,path:o,location:l,scopeKey:e}]),"center"===l?f(c):v(e=>({...e,[t]:c})),c},[e,f,v]),I=t.useRef(new Set),k=t.useCallback(t=>{const n=d.find(e=>e.id===t);if(!n)return;const s=n.scopeKey??"default",r=JSON.stringify([s,c]);"center"===n.location?p(r,t):(y(r,{...w(r),[n.kind]:t}),i.current?.(n.kind)),s!==e&&window.dispatchEvent(new CustomEvent("vibelet.dock.restore-session",{detail:s}))},[d,c,e,p,y,w]),C=t.useCallback((t,n)=>{const s=h.find(e=>"browser"===e.kind&&"right"===e.location&&We(e.currentUrl||e.url||"")===We(t));if(s)return v(e=>({...e,browser:s.id})),void i.current?.("browser",!0);const r=h.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!I.current.has(e.id)),o=r.find(e=>e.id===g.browser)??r[0],a=o?.id??crypto.randomUUID();o&&I.current.add(a),u(s=>o?s.map(e=>e.id===a?{...e,title:n,url:t,emptyPlaceholder:!1}:e):[...s,{id:a,kind:"browser",location:"right",title:n,defaultTitle:n,url:t,scopeKey:e}]),v(e=>({...e,browser:a})),i.current?.("browser",!0)},[h,g.browser,e,v]),R=t.useCallback((e,t)=>{u(n=>n.map(n=>n.id===e&&n.currentUrl!==t?{...n,currentUrl:t,emptyPlaceholder:!t&&n.emptyPlaceholder}:n))},[]),E=t.useCallback((e,t)=>{const n=h.find(t=>t.id===e);n&&(u(n=>n.map(n=>n.id===e?{...n,location:t}:n)),"center"===t?("right"!==n.location||h.some(t=>t.id!==e&&t.kind===n.kind&&"right"===t.location)||o.current?.(n.kind),f(e),v(t=>({...t,[n.kind]:h.find(t=>t.id!==e&&t.kind===n.kind&&"right"===t.location)?.id}))):(v(t=>({...t,[n.kind]:e})),i.current?.(n.kind),m===e&&f(null)))},[h,m,f,v]),j=t.useCallback(t=>{I.current.delete(t);const s=h.find(e=>e.id===t);if(!s)return;n(s);const r=h.find(e=>e.id!==t&&e.kind===s.kind&&e.location===s.location),i=r||"diff"===s.kind||"right"!==s.location&&h.some(e=>e.id!==t&&e.kind===s.kind)?void 0:{id:crypto.randomUUID(),kind:s.kind,location:"right",title:s.defaultTitle??s.title,defaultTitle:s.defaultTitle,cwd:s.cwd,scopeKey:e,autoOpenTerminal:!0,emptyPlaceholder:!0};u(e=>[...e.filter(e=>e.id!==t),...i?[i]:[]]),r||"right"!==s.location||"diff"===s.kind||o.current?.(s.kind),m===t&&f(null),(i||g[s.kind]===t)&&v(e=>({...e,[s.kind]:i?.id??r?.id}))},[h,m,g,e,f,v,n]),M=t.useCallback(()=>{const t=s();t&&(u(n=>[...n.filter(n=>!("right"===t.location&&n.emptyPlaceholder&&n.kind===t.kind&&(n.scopeKey??"default")===e)),t]),"center"===t.location?f(t.id):(v(e=>({...e,[t.kind]:t.id})),i.current?.(t.kind)))},[s,e,f,v]),A=t.useCallback(e=>{u(t=>t.map(t=>t.id===e&&t.emptyPlaceholder?{...t,emptyPlaceholder:!1}:t))},[]),T=t.useCallback((e,t)=>u(n=>n.map(n=>n.id===e&&n.title!==t?{...n,title:t}:n)),[]),N=t.useCallback((e,t)=>S(n=>{if(n[e]===t||!n[e]&&!t)return n;const s={...n};return t?s[e]=t:delete s[e],s}),[]),P=t.useCallback(()=>{r(),I.current.clear(),u([]),f(null),v({}),l(e=>e+1)},[f,v,r]);return t.useMemo(()=>({scopeKey:e,allItems:d,openRight:i,closeRight:o,openBrowser:C,reveal:k,updateBrowserUrl:R,activate:A,epoch:c,items:h,center:m,right:g,hosts:b,add:x,move:E,close:j,reopenClosed:M,rename:T,register:N,reset:P,setCenter:f,setRight:v}),[e,d,C,k,R,A,c,h,m,g,b,x,E,j,M,T,N,P])}(s);return n.jsx(Ke.Provider,{value:r,children:e})}function Ve(){const e=t.useContext(Ke);if(!e)throw new Error("Dock workspace provider missing");return e}function Qe(){return t.useContext(Ke)}const Je="application/x-vibelet-workspace-tab";function Ze(e){return null}function Xe(e){return null}function Ye(e){return null}function et(){return null}const tt=()=>null;function nt({children:e}){return n.jsx(n.Fragment,{children:e})}function st(e,t,n=!1){const s=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/,r=s.exec(e),i=s.exec(t);if(!r||!i||i[4])return!1;for(let o=1;o<=3;o++){const e=Number(i[o]),t=Number(r[o]);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))return!1;if(e!==t)return e>t}return Boolean(r[4])||n}function rt(e="en"){return/^zh/i.test(e)?/tw|hant/i.test(e)?{title:"有更新的正式版",description:(e,t)=>`目前使用 ${e},正式版 ${t} 已發布,建議切換更新。`,action:"切換至正式版"}:{title:"有更新的正式版",description:(e,t)=>`当前使用 ${e},正式版 ${t} 已发布,建议切换更新。`,action:"切换到正式版"}:{title:"A newer stable release is available",description:(e,t)=>`You are using ${e}. Stable ${t} is now available. Switch to stable to update.`,action:"Switch to stable"}}const it="pair",ot="vibelet.web.pairing",at="vibelet.web.deviceId";class ct extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function lt(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function dt(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 ut(e){if(!lt(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 ht(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 mt(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 ft(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 pt(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 gt(e,t,n=window.location,s=!0){if(s&&ht(n.hostname))return;const r=[...t?.connections??[],...e.connections??[],...pt(e,t)].map(ut).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>ft(e)-ft(t));for(const i of r){const e=mt(i,n);if(e)return e}}function vt(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(it);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(!lt(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(dt).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 yt(e){const t=e.getItem(ot);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 wt(e){if("undefined"==typeof window)return null;try{return e===i()?window.sessionStorage:null}catch{return null}}function bt(e=i(),t=wt(e)){const n=yt(e);if(n)return n;const s=t?yt(t):null;return s?(e.setItem(ot,JSON.stringify(s)),t?.removeItem(ot),s):null}function St(e,t=i(),n=wt(t)){t.setItem(ot,JSON.stringify(e)),n?.removeItem(ot)}function xt(e=i(),t=wt(e)){e.removeItem(ot),t?.removeItem(ot)}async function It(e,t){try{return await async function(e,t=function(e=i()){const t=e.getItem(at);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(at,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 ct("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(lt(e)&&"pair_window_expired"===e.error)return new ct("pair_window_expired","Pairing link expired.")}catch{}return new ct("pairing_failed",t||"Pairing failed.")}(n);const s=await n.json();return{daemonId:s.daemonId,displayName:s.displayName||e.displayName,deviceId:s.deviceId,pairToken:s.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:gt(e,s,window.location,!0)}}(e,t?.deviceId)}catch(n){if(n instanceof ct&&"pair_window_expired"===n.code&&t?.daemonId===e.daemonId)return t;throw n}}async function kt(e){const t=s().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e))}catch{}const n=document.activeElement,r=window.getSelection(),i=r?Array.from({length:r.rangeCount},(e,t)=>r.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),r){r.removeAllRanges();for(const e of i)r.addRange(e)}}}function Ct(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Rt(e){return"antigravity"!==e.agent&&Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function Et(e,t={}){return Rt(e)?`cd ${Ct(e.cwd||".")} && ${function(e,t={}){if(!Rt(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(Ct).join(" ")}(e,t)}`:""}const jt="vibelet.web.notificationSettings",Mt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function At(e=i()){try{const t=e.getItem(jt);if(!t)return{...Mt};const n=JSON.parse(t);return pn(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 Tt(e=("undefined"==typeof Notification?void 0:Notification)){return s().notifications?s().notifications.permission():e?.permission??"unsupported"}function Nt(e){return Boolean(e.historyKey?.startsWith("client:")&&!e.rewindPoint)}function Pt(e){return JSON.stringify([e.provider,"codex"===e.provider?e.turnId:e.messageId])}function Dt(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s){const t=e.filter(e=>e.historyKey===s);if(t.length)return 1===t.length?e.indexOf(t[0]):-1}const r=t.rewindPoint;if(r)return function(e){const n=e.flatMap((e,n)=>(e=>e.role===t.role&&Boolean(e.rewindPoint)&&Pt(e.rewindPoint)===Pt(r))(e)?[n]:[]);return 1===n.length?n[0]:-1}(e);if(s)return-1;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}function Lt(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 Ft(e,t){return t?.length?e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e}function Ot(e,t){const n={...e,...t,delivery:t.delivery};return!Number.isFinite(Date.parse(t.timestamp??""))&&Number.isFinite(Date.parse(e.timestamp??""))&&(n.timestamp=e.timestamp),n}function qt(e){return"user"===e.role?Ft(e.content,e.images):e.content}function _t(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&qt(e)===qt(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function $t(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"interrupted"===e.localDelivery||"user"!==e.role||"user"!==t.role||!_t(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 zt(e,t){if(e.historyKey&&t.historyKey)return e.historyKey===t.historyKey;if(e.rewindPoint&&t.rewindPoint)return Pt(e.rewindPoint)===Pt(t.rewindPoint)&&_t(e,t);const n=e.timestamp?Date.parse(e.timestamp):NaN;return Number.isFinite(n)&&n>0&&n===Date.parse(t.timestamp??"")&&_t(e,t)}function Ht(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function Bt(e,t,n){let s=e.map(Lt);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=>zt(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=i.find(e=>!r.has(e)&&$t(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){s[e]=Ot(s[e],d),d.delivery&&"interrupted"!==s[e].localDelivery&&(s[e].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)&&"interrupted"!==t.localDelivery&&(!!zt(t,d)||!!$t(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===Ht(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&_t(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&&$t(s[t],d);s[t]=Ot(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 Ut(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function Wt(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},Ut(s)}return Ut([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function Kt(e){return e&&/^[a-z]:\/+$/i.test(e)?`${e.slice(0,2)}/`:e?.replace(/\/+$/,"")||"/"}function Gt(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function Vt(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 Qt(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 Jt(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 Zt(e,t=Date.now(),n=o){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const r=t-s,i=36e5,a=24*i;return r<6e4?n.timeNow:r<i?n.timeMinutesAgo(Math.floor(r/6e4)):r<a?n.timeHoursAgo(Math.floor(r/i)):n.timeDaysAgo(Math.floor(r/a))}function Xt(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}const Yt="<oai-mem-citation>";function en(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")&&Yt.startsWith(t);if(t.startsWith(Yt)||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 tn=e=>e.replace(/\r\n?/g,"\n").trim(),nn=/^\[Attached image: ([^\n]+)\]$/gm;function sn(e){return"codex"===e?"Codex":"claude"===e?"Claude":e}function rn(e){const t=[],n=new Set;for(const s of e.matchAll(nn)){const e=s[1];e&&0!==e.trim().length&&!n.has(e)&&(n.add(e),t.push(e))}return t}function on(e,t){if("assistant"===e.type)return tn(e.content);const n=tn(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}([...rn(e.content),...e.images??[]]).map(e=>`- ${t.attachedImage}: \`${e}\``);return n&&s.length>0?`${n}\n\n${s.join("\n")}`:n||s.join("\n")}class an{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 cn extends Error{name="VibeletRequestRejectedError"}class ln extends Error{name="VibeletRequestTimeoutError"}function dn(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class un{heartbeat=new an;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&&ht(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:dn("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 ln(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 supportsAntigravityAcp(){return this.isConnected&&!0===this.capabilities.antigravityAcp}get supportsSessionSteer(){return this.isConnected&&!0===this.capabilities.sessionSteer}get supportsQueueSendNow(){return this.isConnected&&!0===this.capabilities.queueSendNow}get supportsSessionRewindByPoint(){return this.isConnected&&!0===this.capabilities.sessionRewindByPoint}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 dn(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 cn(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 cn(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 hn(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 mn=".",fn="normal";function pn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function gn(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 vn(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 yn(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:hn(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function wn(e){return e.split("/").filter(Boolean).at(-1)??e}function bn(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 xn(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 kn(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,model:s.model,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 Cn=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 jn(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 Mn(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 Tn(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Nn(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 Dn(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":c(l().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 Ln="vibelet.web.savedTargets";function Fn(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 On(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=Fn(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function qn(e=i()){const t=e.getItem(Ln);if(!t)return[];try{return On(JSON.parse(t))}catch{return[]}}function _n(e,t=i()){t.setItem(Ln,JSON.stringify(On(e)))}const $n={version:"",latestVersion:"",loading:!1,error:null};function zn(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Hn(e,t){return st(e,t)||function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(zn),s=t.split(/[+-]/,1)[0].split(".").map(zn),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}function Bn(e,t,n){if(n?.sameOrigin)return new URL("/health",t.origin).toString();const s=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const e=new URL(s);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()}}const Un="vibelet.web.sessionListCache";function Wn(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e)||"string"!=typeof e.daemonId||!e.daemonId)return null;const t=yn(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 Kn(e){try{const t=JSON.parse(e.getItem(Un)||"null");return(Array.isArray(t)?t:[t]).map(Wn).filter(e=>null!==e).slice(0,8)}catch{return[]}}function Gn(e){return e instanceof Error&&"auth_failed"===e.message}const Vn="vibelet.web.composerDrafts",Qn={draftsBySessionId:{},newSessionDraft:""};function Jn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Zn(e){return Jn(e)?{draftsBySessionId:Jn(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:Qn}function Xn(e=i()){const t=e.getItem(Vn);if(!t)return Qn;try{return Zn(JSON.parse(t))}catch{return Qn}}function Yn(e,t=i()){t.setItem(Vn,JSON.stringify(Zn(e)))}function es(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 ts(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function ns(e){switch(e instanceof Error?e.message:String(e)){case"Server is draining; retry after reconnecting":return"server-restarting";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}}const ss=["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"],rs=["authorization","proxy-authorization"],is=["cookie","set-cookie"],os=[...rs,...is],as=(e,t)=>t.length-e.length,cs=[...ss].sort(as).join("|"),ls=ss.filter(e=>!os.includes(e)).sort(as).join("|"),ds=[...rs].sort(as).join("|"),us=[...is].sort(as).join("|"),hs=new RegExp(`(?:${cs}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),ms=new RegExp(`(["']?(?:${ds})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),fs=new RegExp(`(["']?(?:${us})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),ps=new RegExp(`(["']?(?:${ls})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),gs=new RegExp(`([?&](?:${cs})=)[^&\\s]+`,"gi");function vs(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(ms,n).replace(fs,n).replace(ps,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(gs,`$1${t}`)}function ys(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]")}(vs(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 ws(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 bs(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??ws)({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)}}class Ss extends Error{constructor(){super("Feedback submission cancelled"),this.name="FeedbackSubmissionCancelledError"}}const xs={contactTitle:"Stay in touch about this feedback",contactReason:"Leave your email so we can contact you when the issue is fixed and ask you to check that it works. Email is optional; you can send feedback without it.",contactSubmit:"Send with email",contactSkip:"Send without email",contactCancel:"Back",contactInvalidEmail:"Enter a valid email, or choose Send without email.",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"},Is={contactTitle:"留下邮箱,方便联系你验证",contactReason:"问题修复后,我们可以通过邮箱联系你,请你确认是否已经恢复正常。邮箱是选填项,不留也可以提交反馈。",contactSubmit:"留下邮箱并提交",contactSkip:"不留邮箱,继续提交",contactCancel:"返回",contactInvalidEmail:"请输入有效邮箱,或选择不留邮箱继续提交。",title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},ks={contactTitle:"留下電子郵件,方便聯絡你驗證",contactReason:"問題修復後,我們可以透過電子郵件聯絡你,請你確認是否已恢復正常。電子郵件為選填,不留也可以提交回饋。",contactSubmit:"留下電子郵件並提交",contactSkip:"不留電子郵件,繼續提交",contactCancel:"返回",contactInvalidEmail:"請輸入有效的電子郵件,或選擇不留電子郵件繼續提交。",title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function Cs(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?ks:t.startsWith("zh")?Is:xs}let Rs=!1;const Es=({locale:e,email:t})=>Rs?Promise.reject(new Ss):"undefined"==typeof document?Promise.reject(new Error("Feedback email dialog requires a UI host")):(Rs=!0,new Promise((n,s)=>{const r=Cs(e),i=document.activeElement,o=document.createElement("div");o.dataset.feedbackEmailPrompt="";const a=o.attachShadow({mode:"open"}),c=document.createElement("style");c.textContent="\n :host { color-scheme: light dark; }\n dialog { box-sizing:border-box; width:min(440px,calc(100vw - 32px)); max-height:calc(100dvh - 32px);\n overflow:auto; padding:24px; border:1px solid light-dark(#dedee4,#44444c); border-radius:20px;\n background:light-dark(#fff,#24242b); color:light-dark(#252530,#f3f3f7); box-shadow:0 20px 80px #0003;\n font:15px/1.5 system-ui,sans-serif; }\n dialog::backdrop { background:#0006; }\n h2 { margin:0 0 10px; font-size:21px; line-height:1.3; }\n p { margin:0 0 20px; color:light-dark(#60606c,#bdbdc9); }\n label { display:block; margin-bottom:7px; font-weight:600; }\n input { box-sizing:border-box; width:100%; min-height:44px; padding:10px 12px; border-radius:10px;\n border:1px solid light-dark(#cfcfd8,#666672); background:light-dark(#fafafa,#303038); color:inherit; font:inherit; }\n input:focus-visible, button:focus-visible { outline:2px solid #8d70c3; outline-offset:3px; }\n .error { min-height:22px; margin:6px 0; color:light-dark(#b42318,#ff9992); font-size:13px; }\n .actions { display:flex; flex-direction:column; gap:8px; }\n button { min-height:44px; padding:10px 12px; border:1px solid light-dark(#dedee4,#555560);\n border-radius:10px; background:transparent; color:inherit; font:inherit; cursor:pointer; }\n .primary { background:light-dark(#eee6f8,#453653); border-color:transparent; font-weight:600; }\n .cancel { border-color:transparent; font-size:13px; }\n ";const l=document.createElement("dialog");l.setAttribute("aria-labelledby","feedback-contact-title"),l.setAttribute("aria-describedby","feedback-contact-reason");const d=document.createElement("h2");d.id="feedback-contact-title",d.textContent=r.contactTitle;const u=document.createElement("p");u.id="feedback-contact-reason",u.textContent=r.contactReason;const h=document.createElement("label");h.htmlFor="feedback-contact-email",h.textContent=r.email;const m=document.createElement("input");m.id=h.htmlFor,m.type="email",m.inputMode="email",m.autocomplete="email",m.maxLength=320,m.value=t??"",m.placeholder=r.emailPlaceholder;const f=document.createElement("div");f.className="error",f.id="feedback-contact-error",f.setAttribute("role","alert"),m.setAttribute("aria-describedby",f.id);const p=document.createElement("div");p.className="actions";let g=!1;const v=(e,t)=>{g||(g=!0,l.close(),o.remove(),Rs=!1,i?.focus(),e?s(new Ss):n(t))},y=(e,t,n)=>{const s=document.createElement("button");s.type="button",s.className=t,s.textContent=e,s.onclick=n,p.append(s)},w=()=>{if(!function(e){return e.trim().length<=320&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(e.trim())}(m.value))return f.textContent=r.contactInvalidEmail,m.setAttribute("aria-invalid","true"),void m.focus();v(!1,m.value.trim())};y(r.contactSubmit,"primary",w),y(r.contactSkip,"skip",()=>v(!1)),y(r.contactCancel,"cancel",()=>v(!0)),m.oninput=()=>{f.textContent="",m.removeAttribute("aria-invalid")},l.addEventListener("keydown",e=>{e.stopPropagation(),"Escape"===e.key&&(e.preventDefault(),v(!0)),"Enter"!==e.key||e.target!==m||e.isComposing||(e.preventDefault(),w())}),l.addEventListener("cancel",e=>{e.preventDefault(),v(!0)}),l.append(d,u,h,m,f,p),a.append(c,l),document.body.append(o);try{l.showModal(),m.focus()}catch(b){o.remove(),Rs=!1,s(b)}})),js=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 Ms(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))js.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=ys(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 ys(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=ys(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=hs.test(s)?"[REDACTED]":l(r,t+1)}return n};return l(e,0)}(t)}const As=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function Ts(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!As.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:ys(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 Ns(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 Ps=13e4;function Ds(e){return vs(e).trim()}function Ls(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}}function Fs(e,t){const n=new Set(e.interruptedClientMessageIds);for(const s of e.acceptedClientMessageIds??[])n.has(s)||t(e.sessionId,s,"delivered");for(const s of n)t(e.sessionId,s,"interrupted")}function Os(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}const qs={claude:"Claude",codex:"Codex",antigravity:"Antigravity"},_s=[{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 $s(e){return _s.filter(t=>!e||t.agents.includes(e))}function zs(e){return e.trim().toLowerCase()}function Hs(e,t,n=8){const s=zs(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>Bs(e,s)-Bs(t,s)):[...e]).slice(0,n)}function Bs(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function Us(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=zs(s[1]??""),i=$s(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 Ws(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}async function Ks(e){return{[e]:"desktop-free"}}const Gs={en:{mode:"Default send mode",queue:"Queue",queueHelp:"Wait until the current turn finishes.",guide:"Guide",guideHelp:"Guide the active turn; queue when unavailable.",restarting:"The Codex service is restarting. Your message remains queued; retry guidance after it reconnects.",unsupported:"This daemon does not support guidance; the message remains queued."},zh:{mode:"默认发送方式",queue:"排队",queueHelp:"等待当前回合完成后发送。",guide:"引导",guideHelp:"引导当前回合,暂不可用时排队。",restarting:"Codex 服务正在重启,消息已保留在队列中,请在服务重新连接后重试引导。",unsupported:"此服务不支持引导,消息已保留在队列。"},"zh-TW":{mode:"預設傳送方式",queue:"排隊",queueHelp:"等待目前回合完成後傳送。",guide:"引導",guideHelp:"引導目前回合,暫不可用時排隊。",restarting:"Codex 服務正在重新啟動,訊息已保留在佇列中,請在服務重新連線後重試引導。",unsupported:"此服務不支援引導,訊息已保留在佇列。"}};async function Vs(e,t,n,r){const i=l(),o="desktop"===s().kind&&"guide"===i.composer.sendMode,a=await e.request(t,n);if(!o||!pn(a)||!0!==a.queued)return a;const d=Gs[c(l().language)];try{if(!e.supportsSessionSteer)throw new Error(d.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(u){const e=u instanceof Error?u.message:String(u);r("Server is draining; retry after reconnecting"===e?d.restarting:`${d.guide}: ${e}`)}return a}function Qs(){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()}}}}}function Js(e){return e.trim().toLowerCase()}function Zs(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:Js(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function Xs(e,t,n=8){const s=Js(t);return(s?e.filter(e=>Js(e.name).includes(s)):e).slice(0,n)}function Ys(e,t,n){const s=ts(e.composerDraftsRef.current,e.activeSessionId),r=s===t?s:[s,t].filter(Boolean).join("\n\n"),i=es(e.composerDraftsRef.current,e.activeSessionId,r);e.composerDraftsRef.current=i,e.setComposerDrafts(i),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(r);try{Yn(i)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}const er=e=>e?.trim()?e:void 0,tr="Session send timed out.";function nr(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function sr(e=window.location.search){const t=new URLSearchParams(e),n=nr(t.get("folder")),s=nr(t.get("file")),r=nr(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...r?{cwd:r}:{}}}function rr(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 ir={en:{rewind:"Rewind to here",resend:"Resend message",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.",rewindUpdateRequired:"Update the Vibelet daemon to rewind this conversation safely.",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:"回退到这里",resend:"重新发送",rewinding:"正在回退会话…完成后,所选消息会回到输入框。",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",rewindUpdateRequired:"请先更新 Vibelet Daemon,再回退会话。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",resend:"重新傳送",rewinding:"正在回退對話…完成後,所選訊息會回到輸入框。",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",rewindUpdateRequired:"請先更新 Vibelet Daemon,再回退對話。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function or(){return ir[c(l().language)]}const ar="vibelet.web.sessionSettings";function cr(e,n){t.useEffect(()=>{e.current=n},[e,n])}async function lr(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}}let dr=0;class ur{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.acknowledged=new Set(t(e.acknowledged)),Array.isArray(e.readActivity))for(const n of e.readActivity)Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)&&this.readActivity.set(n[0],n[1]);if(Array.isArray(e.turns))for(const n of e.turns){if(!Array.isArray(n)||2!==n.length)continue;const[e,t]=n;"string"==typeof e&&t&&"string"==typeof t.key&&Number.isFinite(t.at)&&"boolean"==typeof t.read&&this.turns.set(e,t)}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()])}remapped=new Set;instance=++dr;activity=new Map;readActivity=new Map;refreshes=new Map;turns=new Map;acknowledged=new Set;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;synchronizeRead=()=>{try{const e=JSON.parse(this.storage?.getItem(this.key)??"null"),t=new Map(Array.isArray(e?.turns)?e.turns:[]);for(const[n,s]of t){if(this.remapped.has(n))continue;const t=this.turns.get(n);!s||!Number.isFinite(s.at)||t&&t.at>=s.at||(this.turns.set(n,{...s}),this.acknowledged.delete(n),this.observed.delete(n),this.recovered.delete(n),Array.isArray(e?.unseen)&&e.unseen.includes(n)?this.unseen.add(n):this.unseen.delete(n))}for(const n of Array.isArray(e?.acknowledged)?e.acknowledged:[]){if("string"!=typeof n||this.remapped.has(n))continue;const e=t.get(n),s=this.turns.get(n);s&&e&&s.at>e.at||(!s||e||s.read)&&(this.acknowledged.add(n),e&&(!s||e.at>=s.at)&&this.turns.set(n,{...e,read:!0}),this.unseen.delete(n),this.observed.delete(n))}}catch{}this.publish()};publish(){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()))}save(){this.synchronizeRead();try{this.storage?.setItem(this.key,JSON.stringify({turns:[...this.turns],readActivity:[...this.readActivity],acknowledged:[...this.acknowledged],observed:[...this.observed].slice(-256),unseen:[...this.unseen].slice(-256),failed:[...this.failed].slice(-256)}))}catch{}this.publish()}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()};reconcileTurn=(e,t,n="history")=>{const s=[...t].reverse().find(e=>"user"===e.role&&"failed"!==e.localDelivery&&"sending"!==e.localDelivery&&"interrupted"!==e.localDelivery&&"info"!==e.type);if(!s?.timestamp)return;const r=Date.parse(s.timestamp);if(!Number.isFinite(r))return;const i=s.localClientMessageId?`client:${s.localClientMessageId}`:s.historyKey??String(r),o=this.turns.get(e);if(o&&i===o.key)return void(r>o.at&&(o.at=r,this.save()));if(o&&r<=o.at)return;const a=!o&&this.acknowledged.has(e);this.turns.set(e,{key:i,at:r,read:a}),o&&(this.unseen.delete(e),this.acknowledged.delete(e),this.suppressed.delete(e),this.observed.add(e)),a||"session.history.append"!==n||this.observed.add(e),this.trace(e,n,o?"new-user-turn":"learn-user-turn"),this.save()};trace(e,t,n){try{const s=`${this.key}:changes`,r=JSON.parse(this.storage?.getItem(s)??"[]");this.storage?.setItem(s,JSON.stringify([...(Array.isArray(r)?r:[]).slice(-127),{at:(new Date).toISOString(),sessionId:e,instance:this.instance,source:t,reason:n,turn:this.turns.get(e)?.key??null,unseen:this.unseen.has(e)}]))}catch{}}reconcileDeliveries=(e,t)=>{this.reconcileTurn(e,t,"history-cache");for(const[s,r]of this.failed)r===e&&this.failed.delete(s);const n=Ls(t);n?.localClientMessageId&&this.failed.set(n.localClientMessageId,e),this.save()};deliveryRemoved=(e,t)=>{this.failed.delete(t)&&this.save()};observe=(e,t="observe")=>{this.synchronizeRead(),this.acknowledged.has(e)||this.turns.get(e)?.read?this.trace(e,t,"already-read"):(this.suppressed.delete(e),this.observed.has(e)||(this.observed.add(e),this.trace(e,t,"observed"),this.save()))};complete=(e,t="complete")=>{this.synchronizeRead(),this.observed.delete(e)&&(this.suppressed.add(e),this.recovered.delete(e),this.acknowledged.has(e)||this.turns.get(e)?.read||this.isReading(e)?(this.unseen.delete(e),this.markRead(e)):this.unseen.add(e),this.trace(e,t,this.unseen.has(e)?"completed-unread":"completed-read"),this.save())};takeHistoryRefresh=(e,t)=>!(!this.acknowledged.has(e)||this.readActivity.get(e)===t||this.refreshes.get(e)===t||(this.refreshes.set(e,t),0));reconcile=(e,t,n)=>{n&&this.activity.set(e,n);const s=this.runtime.get(e);this.runtime.set(e,t),t?this.suppressed.has(e)||!0===s||this.observe(e,"runtime-snapshot"):((!0===s||this.recovered.has(e))&&this.observed.has(e)&&this.complete(e,"runtime-snapshot"),this.suppressed.delete(e))};markRead(e){this.acknowledged.add(e);const t=this.activity.get(e);t&&this.readActivity.set(e,t);const n=this.turns.get(e);n&&(n.read=!0),this.observed.delete(e),this.recovered.delete(e)}acknowledgeOpened=e=>{this.unseen.delete(e)&&(this.markRead(e),this.trace(e,"navigation","acknowledged"),this.save())};acknowledgeVisible=()=>{let e=!1;for(const t of this.unseen)this.isReading(t)&&(this.unseen.delete(t),this.markRead(t),this.trace(t,"visible","acknowledged"),e=!0);e&&this.save()};remap=(e,t)=>{this.remapped.add(e);for(const s of[this.activity,this.readActivity,this.refreshes]){const n=s.get(e);n&&(s.set(t,n),s.delete(e))}const n=this.turns.get(e);n&&(this.turns.set(t,n),this.turns.delete(e));for(const s of[this.acknowledged,this.observed,this.unseen,this.suppressed,this.recovered])s.delete(e)&&s.add(t);this.runtime.has(e)&&(this.runtime.set(t,this.runtime.get(e)),this.runtime.delete(e));for(const[s,r]of this.failed)r===e&&this.failed.set(s,t);this.save()}}function hr(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 mr=new WeakMap;async function fr(e,t){let n;const s=e.onMessage(e=>{"session.history"===e.type&&e.sessionId===t.sessionId&&(n=e)});try{let s,r=!0;for(let i=0;i<64;i++){n=void 0,await e.request({action:"session.history",id:e.makeId("attention-history"),sessionId:t.sessionId,agent:t.agent,limit:100,...r?{pageMode:"cursor",beforeCursor:s}:{before:s}});const i=n;if(!i||i.messages.some(e=>"user"===e.role&&e.timestamp))return;const o=i.historyPage;if(!o?.hasMore||o.start<=0||void 0!==s&&o.start>=s)return;s=o.start,r="byte"===o.cursorMode}}finally{s()}}const pr=new Set;function gr(e){return pr.add(e),()=>{pr.delete(e)}}const vr="vibelet.workspace.flush",yr="vibelet:file-operation-before",wr="vibelet:file-operation-done";function br(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 Sr(e,t,n){const s=br(e,n),r=br(t,n);return s===r||s.startsWith(`${r}/`)}async function xr(e,t){const n=new CustomEvent(yr,{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(wr,{detail:{...i,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),i}async function Ir(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 kr(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 Cr(e){return`<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: blob:; media-src data: blob:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'"><script>\n(function() {\n function createStorage() {\n var values = new Map();\n var api = Object.create(null);\n Object.defineProperties(api, {\n length: { configurable: true, get: function() { return values.size; } },\n key: { configurable: true, value: function(index) { return Array.from(values.keys())[Number(index) >>> 0] ?? null; } },\n getItem: { configurable: true, value: function(key) { return values.get(String(key)) ?? null; } },\n setItem: { configurable: true, value: function(key, value) { values.set(String(key), String(value)); } },\n removeItem: { configurable: true, value: function(key) { values.delete(String(key)); } },\n clear: { configurable: true, value: function() { values.clear(); } }\n });\n return new Proxy(api, {\n get: function(target, key) { return Reflect.has(target, key) ? Reflect.get(target, key) : values.get(String(key)); },\n set: function(target, key, value) { values.set(String(key), String(value)); return true; },\n deleteProperty: function(target, key) { values.delete(String(key)); return true; },\n has: function(target, key) { return Reflect.has(target, key) || values.has(String(key)); },\n ownKeys: function() { return Array.from(values.keys()); },\n getOwnPropertyDescriptor: function(target, key) {\n if (values.has(String(key))) return { configurable: true, enumerable: true, writable: true, value: values.get(String(key)) };\n return Reflect.getOwnPropertyDescriptor(target, key);\n }\n });\n }\n ['localStorage', 'sessionStorage'].forEach(function(name) {\n try { if (window[name]) return; } catch (_) {}\n Object.defineProperty(window, name, { configurable: true, value: createStorage() });\n });\n})();\n<\/script>${e}`}const Rr=e=>/^(https?:|data:|blob:)/i.test(e.path)?e.path:br(e.path,e.cwd);function Er(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function jr(e,t,n){return t&&0!==n.length?{...e,[t]:Bt(e[t]??[],n)}:e}function Mr(e){return Boolean(e.localClientMessageId&&e.historyKey?.startsWith("client:"))}function Ar(e,t){const n=new Map,s=Bt(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??""),t=n.findIndex(e=>e===r||r.localClientMessageId&&e.localClientMessageId===r.localClientMessageId);let i=Number.isFinite(e)?s.findIndex(s=>{const r=Date.parse(s.timestamp??"");if(r!==e)return r>e;if(!s.localClientMessageId&&"assistant"!==s.role)return!1;const i=n.findIndex(e=>s.localClientMessageId&&e.localClientMessageId===s.localClientMessageId||s.historyKey&&e.historyKey===s.historyKey||s.liveReply&&e.liveReply&&e.timestamp===s.timestamp);return i<0?"assistant"===s.role:t<i}):-1;if(!Number.isFinite(e)){const e=n.slice(t+1);if(i=s.findIndex(t=>e.some(e=>e===t||e.historyKey&&e.historyKey===t.historyKey)),i<0){const e=n.slice(0,t);i=s.findLastIndex(t=>e.some(e=>e===t||e.historyKey&&e.historyKey===t.historyKey))+1}}s.splice(i<0?s.length:i,0,r)}return s}(r,s.filter(e=>Mr(e)&&!i.has(e.localClientMessageId)),e)}function Tr(e){return e.historyKey?`key:${e.historyKey}`:e.rewindPoint?`rewind:${e.role}:${Pt(e.rewindPoint)}`:e.timestamp?JSON.stringify([e.timestamp,e.role,e.type,e.content,e.images,e.toolName,e.toolInput]):void 0}const Nr="vibelet.web.historyDiskCache.v1";function Pr(){try{const e=JSON.parse(i().getItem(Nr)||"[]");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 Dr(e,t){try{const n=Pr().filter(n=>n.daemonId!==e||!Object.hasOwn(t,n.sessionId));for(const[r,i]of Object.entries(t)){if(!i)continue;const t={daemonId:e,sessionId:r,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 s=n.slice(0,40);for(;s.length&&(new TextEncoder).encode(JSON.stringify(s)).length>2097152;)s.pop();i().setItem(Nr,JSON.stringify(s))}catch{}}const Lr=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function Fr(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 qr(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}function _r(e){return`https://vibelet.icu/${"zh-TW"===e?"zh-tw/":"zh"===e?"zh/":""}#guide`}class $r{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 zr="vibelet.session.command",Hr=[{id:"sessionOpen",zh:"会话:打开",en:"Session: Open",default:""},{id:"sessionRename",zh:"会话:重命名",en:"Session: Rename",default:""},{id:"sessionDetails",zh:"会话:详情",en:"Session: Details",default:""},{id:"sessionCopyResume",zh:"会话:复制恢复命令",en:"Session: Copy resume command",default:""},{id:"sessionResumeTerminal",zh:"会话:在终端恢复",en:"Session: Resume in terminal",default:""},{id:"sessionPin",zh:"会话:置顶 / 取消置顶",en:"Session: Toggle pinned",default:""},{id:"sessionArchive",zh:"会话:归档 / 取消归档",en:"Session: Toggle archived",default:""},{id:"sessionDelete",zh:"会话:删除",en:"Session: Delete",default:""}],Br="vibelet.shortcuts.changed",Ur="vibelet.workspace.command",Wr=[...Hr,{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"previousSession",zh:"上一个会话",en:"Previous session",default:""},{id:"nextSession",zh:"下一个会话",en:"Next session",default:""},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"commandMode",zh:"打开命令模式",en:"Open command mode",default:"mod+p"},{id:"quickSearch",zh:"快速定位会话 / 标签",en:"Quick switch sessions / tabs",default:"mod+k"},{id:"searchMessages",zh:"查找聊天 / 浏览器 / 终端",en:"Find in chat / browser / terminal",default:"mod+f"},{id:"findNext",zh:"下一个匹配项",en:"Next match",default:"mod+g"},{id:"findPrevious",zh:"上一个匹配项",en:"Previous match",default:"mod+shift+g"},{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:"reopenTab",zh:"恢复已关闭的终端 / 浏览器标签",en:"Reopen closed terminal / browser tab",default:"mod+shift+t"},{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 Kr(){return/Mac|iPhone|iPad/.test(navigator.platform)}function Gr(e,t=Kr()){return t?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}const Vr={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function Qr(e,t=Kr()){const n=Vr[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 Jr(e,t=Kr()){const n=t?{mod:"⌘",ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",space:"Space",enter:"Enter"}:{mod:"Ctrl",ctrl:"Ctrl",meta:/Win/.test(navigator.platform)?"Win":"Super",alt:"Alt",shift:"Shift",space:"Space",enter:"Enter"};return Object.assign(n,{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→"}),e.split("+").map(e=>n[e]||e.toUpperCase()).join(t?"":"+")}function Zr(e,t,n,s=Kr()){return t?"mod+w"===t?"closeTab"===e?null:"reserved":!s&&["mod+y","alt+f4"].includes(t)||t===(s?"ctrl+tab":"mod+tab")||t===(s?"ctrl+shift+tab":"mod+shift+tab")||["mod+n","mod+alt+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":Wr.find(s=>s.id!==e&&function(e,t={}){return t[e]??Wr.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const Xr="vibelet.web.shortcuts";function Yr(){try{const e=JSON.parse(i().getItem(Xr)||"{}");return Object.fromEntries(Wr.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function ei(e,t=Yr()){return t[e]??("closeTab"===e&&"browser"===s().kind?"mod+alt+w":Wr.find(t=>t.id===e).default)}function ti(e,t){const n=ei(t);return n?`${e} (${Jr(n)})`:e}const ni="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",si="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 ri(){const e=c(l().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 ii(){const e=ri();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:si,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:ni,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 oi({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=ri().title;return I.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":ri().close,title:ri().close,onClick:e,children:n.jsx(De,{"aria-hidden":"true"})}),n.jsx(ii,{})]})}),document.body)}function ai({projectEditor:e,activeSession:r,client:i,busy:o,controlsOpen:a,pendingCount:c=0,t:l,onOpenControls:d,onRefreshSessions:u,onRestoreSnapshot:h,onToggleArchived:m,onTogglePinned:f,onViewChanges:p}){const[g,v]=t.useState(!1),[y,w]=t.useState(!1),b=t.useRef(null);t.useEffect(()=>{if(!y)return;const e=e=>{e.target instanceof Node&&!b.current?.contains(e.target)&&w(!1)},t=e=>{"Escape"===e.key&&w(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[y]);const S=e=>{w(!1),e()},x=s(),C=n.jsxs("div",{className:"header-actions",children:["desktop"!==x.kind&&r&&x.renderSessionShare?.(r,i),("desktop"!==x.kind||c>0)&&n.jsxs("button",{type:"button",className:"icon-button header-pending-button","aria-label":l.pendingActionCount(c),title:l.pendingActionCount(c),onClick:()=>window.dispatchEvent(new Event("vibelet.pending.open")),children:[n.jsx(q,{"aria-hidden":"true"}),c>0&&n.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:c})]}),e,g&&n.jsx(oi,{onClose:()=>v(!1)}),r?null:n.jsx("button",{"aria-label":l.refreshSessions,className:"icon-button",onClick:u,title:l.refreshSessions,type:"button",children:n.jsx(we,{"aria-hidden":"true"})}),n.jsx("button",{"aria-expanded":a,"aria-label":a?l.collapseControlsSidebar:l.workspaceTools,title:ti(a?l.collapseControlsSidebar:l.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:d,type:"button",children:n.jsx(me,{"aria-hidden":"true"})}),r||x.openSettings?n.jsxs("div",{className:"header-more-wrap",ref:b,children:[n.jsx("button",{"aria-expanded":y,"aria-haspopup":"menu","aria-label":l.moreActions,className:"icon-button",onClick:()=>w(e=>!e),title:l.moreActions,type:"button",children:n.jsx(W,{"aria-hidden":"true"})}),y?n.jsxs("div",{className:"header-action-menu",role:"menu",children:["desktop"===x.kind&&0===c&&n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>window.dispatchEvent(new Event("vibelet.pending.open"))),children:[n.jsx(q,{"aria-hidden":"true"}),n.jsx("span",{children:l.pendingActionCount(c)})]}),r&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:()=>S(()=>p(r.sessionId)),role:"menuitem",type:"button",children:[n.jsx(ne,{"aria-hidden":"true"}),n.jsx("span",{children:l.viewChanges})]}),n.jsxs("button",{disabled:o,onClick:()=>S(f),role:"menuitem",type:"button",children:[n.jsx(ge,{"aria-hidden":"true"}),n.jsx("span",{children:r.pinned?l.unpin:l.pin})]}),n.jsxs("button",{disabled:o,onClick:()=>S(m),role:"menuitem",type:"button",children:[n.jsx(P,{"aria-hidden":"true"}),n.jsx("span",{children:r.archived?l.unarchive:l.archive})]}),n.jsxs("button",{onClick:()=>S(h),role:"menuitem",type:"button",children:[n.jsx(be,{"aria-hidden":"true"}),n.jsx("span",{children:l.restoreSnapshot})]})]}),n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>v(!0)),children:[n.jsx(k,{"aria-hidden":"true"}),n.jsx("span",{children:ri().title})]}),n.jsxs("button",{onClick:()=>S(u),role:"menuitem",type:"button",children:[n.jsx(we,{"aria-hidden":"true"}),n.jsx("span",{children:l.refreshSessions})]})]}):null]}):null]}),R=x.toolbarTarget?.("right");return R?I.createPortal(C,R):C}function ci({language:e,entry:r="web-settings"}){const i=c(e),o=t.useMemo(()=>Cs(i),[i]),[a,l]=t.useState("bug"),[d,u]=t.useState(""),[h,m]=t.useState(""),[f,p]=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"===a?"primary-button":"",type:"button","aria-pressed":"bug"===a,onClick:()=>l("bug"),children:o.bug}),n.jsx("button",{className:"feature"===a?"primary-button":"",type:"button","aria-pressed":"feature"===a,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=>m(e.target.value)})]}),n.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===f,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==f){p("sending");try{await async function(e,t={}){const{requestEmail:n=Es,...s}=t,r=await n({locale:e.locale,email:e.email});return bs({...e,email:r},s)}(function(e){const t=function(e){return ys(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=ys(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:Ms(e.metadata),images:Ts(e.images)}}({product:"vibelet",source:"desktop"===s().kind?"desktop":"web",type:a,description:d,email:h,appVersion:s().appVersion||"web",locale:i,platform:navigator.platform||"web",metadata:{app:"desktop"===s().kind?"vibelet-desktop":"vibelet-web",entry:r,screen:"connection-guide"===r?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),u(""),p("success")}catch(e){p(function(e){return e instanceof Error&&"FeedbackSubmissionCancelledError"===e.name}(e)?"idle":"error")}}})()},children:"sending"===f?o.sending:o.submit}),"success"===f?n.jsx("p",{className:"empty-copy success-copy",children:o.success}):null,"error"===f?n.jsx("p",{className:"empty-copy error-copy",children:o.error}):null]})}const li=[[0,.024],[.05,.078],[.25,.157],[.5,.243],[.75,.325],[.9,.4],[.97,.459],[.995,.506],[1,.533]];function di(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 ui(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=di(d(r),i,s),h=di(d(r+1),i,s),m=di(d(r),i+1,s);return u+(h-u)*c+(m-u)*l+(u-h-m+di(d(r+1),i+1,s))*c*l}function hi(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*ui(o/e*n,i/e*(n/2),n,s+97*r),l+=c,c*=.5}r[i*e+o]=a/l}return r}function mi(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 fi(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 pi=null;const gi=["fixed","gradient-2","gradient-3","spectrum"],vi=["none","brighten","flow","spotlight"],yi={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},wi=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t)),bi=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 Si({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=()=>({...yi,...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}),m=t.useRef(h());return t.useEffect(()=>{m.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,f=0,p=0,g=0,v=0,y=!1,w=!1,b=[0,0],S=!0,x=!1,I=!1,k=1,C=1;const R=matchMedia("(prefers-reduced-motion: reduce)"),E=(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)},j=()=>{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=E(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");I=t&&!!n.getExtension("EXT_shader_texture_lod");const d=(t?"#define USE_CHROMATIC_DERIVATIVES\n":"")+(I?"#define USE_CHROMATIC_TEXTURE_LOD\n":"");if(o=E(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 j();if(s=n.createProgram(),n.attachShader(s,i),n.attachShader(s,o),n.linkProgram(s),!n.getProgramParameter(s,n.LINK_STATUS))return void j();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&&!x&&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(pi)return pi;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}(hi(128,4,4,11),li),t=mi(hi(128,3,3,29),.83,.05),n=mi(hi(128,5,2,53),.988,.03),s=new Uint8Array(65536);for(let r=0;r<16384;r++){const[i,o,a]=fi((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 pi=s,s}()),I&&(n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR)),e.dataset.renderer="webgl",$())},A=()=>!!s&&!x&&S&&!document.hidden&&!R.matches&&(!m.current.paused&&0!==m.current.speed||Math.abs(v-g)>.001),T=()=>{if(!s||x)return;const r=m.current,i=Math.round(wi(r.columns,1,1,24)),o=Math.round(wi(r.rows,1,1,24));n.viewport(0,0,e.width,e.height),n.uniform2f(l.size,k,C),n.uniform2f(l.resolution,e.width,e.height),n.uniform2f(l.grid,i,o),n.uniform1f(l.gap,wi(r.gap,0,0,Math.max(0,Math.min(k/i,C/o)-4))),n.uniform1f(l.time,p),n.uniform1f(l.hover,t?.disabled||"none"===r.hoverEffect?0:g),n.uniform1f(l.hoverEffect,Math.max(0,vi.indexOf(r.hoverEffect))),n.uniform2f(l.hoverPosition,...b),n.uniform1f(l.phase,wi(r.phase,0,-1e3,1e3)),n.uniform1f(l.feather,wi(r.feather,95,0,100));const c=wi(r.projectionScale,174,90,179.5);n.uniform1f(l.projectionScale,c),n.uniform1f(l.centerProjectionScale,wi(r.centerProjectionScale??c,c,90,179.5)),n.uniform1f(l.borderRadius,void 0===r.borderRadius?-1:wi(r.borderRadius,50,0,50)/50),n.uniform1f(l.intensity,wi(r.intensity,1.15,0,3)),n.uniform1f(l.grain,wi(r.grain,.035,0,.5)),n.uniform1f(l.spread,wi(r.colorSpread,0,0,2)),n.uniform1f(l.seed,wi(r.seed,7,0,65535)),n.uniform3fv(l.color,bi(r.color)),n.uniform1f(l.colorMode,gi.indexOf(r.colorMode)),n.uniform3fv(l.color2,bi(r.color2)),n.uniform3fv(l.color3,bi(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,A()){if(f){const t=Math.min((e-f)/1e3,.1);m.current.paused||(p+=t*wi(m.current.speed,.7,0,4)),g+=(v-g)*(1-Math.exp(14*-t)),Math.abs(v-g)<=.001&&(g=v)}f=e,T(),A()&&(h=requestAnimationFrame(N))}else f=0},P=()=>{v=t&&!t.disabled&&"none"!==m.current.hoverEffect&&(y||w)?1:0,(R.matches||"none"===m.current.hoverEffect||t?.disabled)&&(g=v)},D=()=>{P(),h||(f=0,T(),A()&&(h=requestAnimationFrame(N)))},L=e=>{"touch"!==e.pointerType&&(y=!0,D())},F=()=>{y=!1,D()},O=()=>{w=!!t?.matches(":focus-visible"),w&&(b=[0,0]),D()},q=()=>{w=!1,D()},_=e=>{if(!t||t.disabled||"touch"===e.pointerType||"spotlight"!==m.current.hoverEffect)return;const n=t.getBoundingClientRect();b=[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||T()},$=()=>{cancelAnimationFrame(h),h=0,f=0,P(),T(),A()&&(h=requestAnimationFrame(N))},z=()=>{k=Math.max(1,e.clientWidth),C=Math.max(1,e.clientHeight);const t=Math.min(devicePixelRatio||1,2,Math.sqrt(15e5/(k*C)));e.width=Math.max(1,Math.round(k*t)),e.height=Math.max(1,Math.round(C*t)),$()},H=t=>{t.preventDefault(),x=!0,cancelAnimationFrame(h),delete e.dataset.renderer},B=()=>{x=!1,j(),M(),z()};M(),t?.addEventListener("pointerenter",L),t?.addEventListener("pointerleave",F),t?.addEventListener("pointercancel",F),t?.addEventListener("pointermove",_),t?.addEventListener("focus",O),t?.addEventListener("blur",q);const U=new ResizeObserver(z);U.observe(e);const W=new IntersectionObserver(([e])=>{S=e.isIntersecting,$()});return W.observe(e),document.addEventListener("visibilitychange",$),R.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",$),R.removeEventListener("change",$),e.removeEventListener("webglcontextlost",H),e.removeEventListener("webglcontextrestored",B),delete e.dataset.renderer,j(),t?.removeEventListener("pointerenter",L),t?.removeEventListener("pointerleave",F),t?.removeEventListener("pointercancel",F),t?.removeEventListener("pointermove",_),t?.removeEventListener("focus",O),t?.removeEventListener("blur",q)}},[]),n.jsx("canvas",{ref:d,className:"chromatic-surface","aria-hidden":"true",tabIndex:-1})}const xi={...yi,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},Ii=t.forwardRef(function({children:e="Get started",className:s="",type:r="button",color:i=xi.color,colorMode:o,color2:a=xi.color2,color3:c=xi.color3,fixedColor:l,speed:d,paused:u,phase:h,feather:m=xi.feather,projectionScale:f=xi.projectionScale,intensity:p=xi.intensity,grain:g=xi.grain,borderRadius:v=xi.borderRadius,hoverEffect:y=xi.hoverEffect,entrance:w=xi.entrance,entranceSpeed:b=xi.entranceSpeed,entranceBlur:S=xi.entranceBlur,entranceDistance:x=xi.entranceDistance,entranceScale:I=xi.entranceScale,seed:k,style:C,...R},E){const j=t.useRef(null);t.useImperativeHandle(E,()=>j.current,[]),t.useEffect(()=>{const e=j.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||R.disabled)return;const e=j.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)),m=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])*m,n[t]+=s[t]*m;const f=n.every((e,t)=>Math.abs(e-r[t])<.01&&Math.abs(s[t])<.05);if(f&&(n.splice(0,2,...r),s.fill(0),r.every(e=>0===e)))return void l();const p=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*p}, ${1-.025*p})`),f?o=0:i=requestAnimationFrame(d)},u=()=>{i||(i=requestAnimationFrame(d))},h=e=>{"touch"===e.pointerType||t.matches||(a=!0)},m=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()},f=()=>{a=!1,r.fill(0),u()},p=()=>{a=!1,l()},g=()=>{document.hidden&&p()};return e.addEventListener("pointerenter",h),e.addEventListener("pointermove",m),e.addEventListener("pointerleave",f),e.addEventListener("pointercancel",f),t.addEventListener("change",p),document.addEventListener("visibilitychange",g),()=>{l(),e.removeEventListener("pointerenter",h),e.removeEventListener("pointermove",m),e.removeEventListener("pointerleave",f),e.removeEventListener("pointercancel",f),t.removeEventListener("change",p),document.removeEventListener("visibilitychange",g)}},[y,R.disabled]);const M=Math.min(50,Math.max(0,Number.isFinite(v)?v:xi.borderRadius)),A=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:xi.borderRadius)))/s(xi.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))}(f,M),T=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t));return n.jsxs("button",{...R,ref:j,type:r,"data-hover-effect":y,"data-entrance":w,className:`chromatic-button ${s}`.trim(),style:{"--chromatic-button-color":i,"--chromatic-button-radius":M/100,"--chromatic-entrance-speed":T(b,1,.1,4),"--chromatic-entrance-blur":`${T(S,10,0,40)}px`,"--chromatic-entrance-distance":`${T(x,20,0,120)}px`,"--chromatic-entrance-scale":T(I,.65,.05,1),...C},children:[n.jsx(Si,{color:i,colorMode:o,color2:a,color3:c,fixedColor:l,speed:d,paused:u,phase:h,feather:m,projectionScale:A,borderRadius:M,hoverEffect:y,centerProjectionScale:A-(xi.projectionScale-yi.projectionScale),intensity:p,grain:g,seed:k}),n.jsx("span",{className:"chromatic-button-content",children:e})]})}),ki=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),m=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(Ii,{...r,ref:m,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:m,className:`product-chromatic-action chromatic-button ${e}`,style:s,children:n.jsx("span",{className:"chromatic-button-content",children:r.children})})}),Ci={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 Ri(){const e=Ci[c(l().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=vt(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(ki,{className:"primary-button",type:"submit",children:e.connect}),i&&n.jsx("p",{role:"alert",className:"connection-guide-error",children:i})]})}const Ei="vibelet --access=quick";function ji({errorText:e,t:s}){const[r,i]=t.useState("idle"),[o,a]=t.useState(!1),d=l().language,u=Cs(d);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(Ee,{})}),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(Ri,{}),n.jsxs("div",{className:"connection-command",children:[n.jsx("code",{children:Ei}),n.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await kt(Ei),i("success")}catch{i("error")}window.setTimeout(()=>i("idle"),1800)})()},type:"button",children:["success"===r?n.jsx(_,{"aria-hidden":"true"}):n.jsx(U,{"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}),n.jsx("a",{className:"connection-guide-link",href:_r(c(d)),target:"_blank",rel:"noopener noreferrer",children:s.connectionGuideLink}),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(le,{"aria-hidden":"true"}),u.title]}),o?n.jsx("div",{className:"connection-feedback-panel",children:n.jsx(ci,{language:d,entry:"connection-guide"})}):null]})})}const Mi="vibelet:image-gallery",Ai="vibelet:close-image-gallery";function Ti(e){window.dispatchEvent(new CustomEvent(Mi,{detail:e}))}const Ni=t.lazy(()=>C(()=>import("./ImageViewer-B3zT7wZQ.js"),__vite__mapDeps([0,1,2,3,4,5])));function Pi(){const[e,s]=t.useState(null);return t.useEffect(()=>{const e=e=>s(e.detail);return window.addEventListener(Mi,e),()=>window.removeEventListener(Mi,e)},[]),t.useEffect(()=>{if(!e)return;const t=e=>{e.preventDefault(),s(null)};return window.addEventListener(Ai,t),()=>window.removeEventListener(Ai,t)},[e]),e?n.jsx(t.Suspense,{fallback:null,children:n.jsx(Ni,{request:e,onClose:()=>s(null)},e.images[e.index].src)}):null}const Di=new WeakMap;function Li(e,t,n){let s=Di.get(e);s||Di.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 Fi(e,t,n){return Li(e,t,n)}function Oi(e,t,n){const s=Li(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 qi(e,t,n,s){const r=Li(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}function _i({t:e}){const s=Ve().items.filter(e=>"browser"===e.kind&&"right"===e.location).map(e=>e.currentUrl??e.url??"").filter(e=>e&&"about:blank"!==e).join("\n"),[r,i]=t.useState("idle");t.useEffect(()=>i("idle"),[s]),t.useEffect(()=>{if("idle"===r)return;const e=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(e)},[r]);const o="浏览器"===e.browser?"复制所有页面网址":"瀏覽器"===e.browser?"複製所有頁面網址":"Copy all page URLs",a="copied"===r?e.browserUrlCopied:"failed"===r?e.browserCopyFailed:o,c="copied"===r?_:"failed"===r?Te:U;return n.jsxs("button",{type:"button",className:"dock-copy-urls","aria-label":o,title:a,disabled:!s,onClick:()=>{kt(s).then(()=>i("copied"),()=>i("failed"))},children:[n.jsx(c,{"aria-hidden":"true"}),n.jsx("span",{className:"dock-copy-status",role:"status",children:"idle"===r?"":a})]})}const $i=t.createContext(null),zi={browser:se,terminal:Ee,diff:ne};function Hi(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 Bi({location:e,kind:s,t:r,cwd:i}){const o=Ve(),a=Hi(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($i),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(F,{})}),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=zi[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(Je,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(O,{})}),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(De,{})})]},t.id)})}),"right"===e&&"browser"===s&&n.jsx(_i,{t:r}),"right"===e&&s&&n.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:ti(a.create,"newTab"),onClick:()=>o.add(s,r["browser"===s?"browser":"terminal"],i),children:n.jsx(ye,{})})]});return u?I.createPortal(h,u):h}function Ui({item:e,t}){const s=Ve(),r=Hi(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(Je,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>s.move(e.id,"center"),children:n.jsx(F,{})}),"browser"===e.kind&&n.jsx(_i,{t}),n.jsx("button",{type:"button","aria-label":r.create,title:ti(r.create,"newTab"),onClick:()=>s.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:n.jsx(ye,{})})]})}function Wi({location:e,kind:s}){const r=Ve(),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 Ki(e,t){const n=Qe();return n?{onDragOver:e=>{e.dataTransfer.types.includes(Je)&&(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(Je),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 Gi=t.lazy(()=>C(()=>import("./DiffDrawer-BOo0z8j9.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.DiffDrawer}))),Vi=t.lazy(async()=>C(()=>import("./RemoteWorkspaceSettings-tLFMGBTO.js"),__vite__mapDeps([8,1,2,9,10,11,12,13,14])).then(e=>({default:e.RemoteWorkspaceSettings}))),Qi=t.lazy(async()=>C(()=>import("./FilesControlPanel-DdgfLvcS.js"),__vite__mapDeps([15,1,2,4,16,17,18])).then(e=>({default:e.FilesControlPanel}))),Ji=t.lazy(async()=>C(()=>import("./LanguageSettingsPanel-BZOXQSpl.js"),__vite__mapDeps([19,1,2,20])).then(e=>({default:e.LanguageSettingsPanel}))),Zi=t.lazy(async()=>C(()=>import("./ThemeSettingsPanel-BKow3xYE.js"),__vite__mapDeps([21,1,2,20])).then(e=>({default:e.ThemeSettingsPanel}))),Xi=t.lazy(async()=>C(()=>import("./NotificationSettingsPanel-DNnl9a9p.js"),__vite__mapDeps([22,1,2])).then(e=>({default:e.NotificationSettingsPanel}))),Yi=t.lazy(async()=>C(()=>import("./SpeechInputSettingsPanel-Dbtr1xpS.js"),__vite__mapDeps([23,1,2,9,10,11,24])).then(e=>({default:e.SpeechInputSettingsPanel})));function eo({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 to({client:e,id:s,activeSession:r,sessions:i,t:o,close:c}){const l=Qe(),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 Oi(e,t,"unstaged");n.files[0]&&await qi(e,t,"unstaged",n.files[0].path)}(e,{sessionId:d,cwd:u}).catch(()=>{})},350);return()=>window.clearTimeout(t)},[e,d,u,h]);const m=i.find(e=>e.sessionId===s);return m&&e?n.jsx(t.Suspense,{fallback:null,children:n.jsx(Gi,{client:e,sessionId:m.sessionId,cwd:m.cwd,sessionTitle:a(m),t:o,onClose:c,dockLabel:Hi(o).center,onDock:l?({scope:e,path:t})=>{l.add("diff",a(m),m.cwd,m,e,t),c()}:void 0},m.sessionId)}):null}const no=t.lazy(()=>C(()=>import("./ChatPane-FOqiEb_l.js"),__vite__mapDeps([25,1,2,26,27,12,9,10,11,28,29,17,24,7,30,31,32])).then(e=>({default:e.ChatPane})));function so(e){return n.jsx(t.Suspense,{fallback:n.jsx(eo,{t:e.t}),children:n.jsx(no,{...e})})}function ro(e,t=!1){const n=e.trim();if(!n)return null;let s=n;if(n.startsWith("/")){if(!t||n.startsWith("//")||n.includes("\\"))return null;s=`file://${n.split("/").map(encodeURIComponent).join("/")}`}else if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[^:/\s]+:\d+(?:[/?#]|$)/.test(n)){if(!(/^https?:\/\//i.test(n)||t&&/^file:\/\//i.test(n)))return null}else s=/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i.test(n)?`http://${n}`:!/\s/.test(n)&&/^[^/]+\.[^/]+/.test(n)?`https://${n}`:`https://www.google.com/search?q=${encodeURIComponent(n)}`;try{const e=new URL(s);return!(t&&function(e){return"file:"===e.protocol&&!e.hostname&&!e.username&&!e.password}(e)||/^https?:$/.test(e.protocol))||e.username||e.password?null:e.href}catch{return null}}const io=t.lazy(()=>C(()=>import("./BrowserControlPanel-BuNWFba-.js"),__vite__mapDeps([33,1,2,34,17,35,4,3]))),oo=t.lazy(()=>C(()=>import("./SessionTerminalPanel-nTZ0CuII.js"),__vite__mapDeps([36,1,2,34,17,35]))),ao=t.lazy(()=>C(()=>import("./DiffDrawer-BOo0z8j9.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.DiffDrawer})));function co({item:e,...s}){const r=Ve(),[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=Ki(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(Ui,{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),m=r.hosts[l?`right-${e.kind}`:"center"]??r.hosts.parking,f=r.hosts.parking;t.useLayoutEffect(()=>{f&&c.parentElement!==f&&f.appendChild(c)},[c,f]),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=m?.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 m&&s.observe(m),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,m,h,e.id,e.location,e.kind,l]),t.useLayoutEffect(()=>()=>c.remove(),[c]);const p=t.useCallback(t=>r.updateBrowserUrl(e.id,t),[r.updateBrowserUrl,e.id]);return I.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(io,{initialUrl:e.url,visible:h,onUrlChange:p,onRestore:()=>r.reveal(e.id),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(oo,{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(ao,{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:Hi(s.t).center,presentation:l?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),c)}function lo(e){const r=Ve();r.openRight.current=(t,n)=>{"browser"===t&&n&&e.onOpenBrowserLink?.(),"browser"!==t&&"terminal"!==t||e.onOpenRight?.(t)},r.closeRight.current=t=>{e.controlTab===t&&e.onCloseRight?.()},t.useEffect(()=>s().subscribeCommand?.(t=>{if(!t.startsWith("open-link:"))return;const n=t.slice(10);if(!/^(?:https?|file):\/\//i.test(n))return;const i=ro(n,!!s().mountBrowser);i&&r.openBrowser(i,e.t.browser)}),[r.openBrowser,e.t.browser]);const i=t.useCallback(e=>r.register("parking",e),[r.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(Wi,{location:"right",kind:"diff"})}),r.allItems.map(t=>n.jsx(co,{item:t,...e},t.id))]})}let uo;const ho=C(()=>import("./NewSessionDialog-Cca7q4mL.js"),__vite__mapDeps([37,1,2,26,27,12,9,10,11,28,16,17,38])).then(e=>(uo=e.default,e));ho.catch(()=>{});const mo=t.lazy(()=>ho);function fo(e){const t=uo??mo;return n.jsx(t,{...e})}const po=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,go=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,vo=new Set(["","{}","[]","null","undefined",'""']);function yo(e){return e.replace(/\s+/g," ").trim()}function wo(e,t){return"string"==typeof e[t]?e[t]:""}function bo(e,t){return"number"==typeof e[t]?e[t]:void 0}function So(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function xo(e){const t=[],n=wo(e,"file_path")||wo(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=bo(e,"offset"),r=bo(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 Io(e){const t=function(e){return"string"!=typeof e?"":e.replace(/\r\n?/g,"\n").replace(po,"").replace(go,"").trim()}(e);return vo.has(t)?"":t}function ko(e){const t=Io(e);if(!t)return"";try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e)){const t="string"==typeof e.query?yo(e.query):"";if(t)return t;const n="string"==typeof e.command?yo(e.command):"";if(n)return n;const s="string"==typeof e.description?yo(e.description):"";if(s)return s}}catch{}return yo(t)}function Co(e){return"tool"===e.role||"info"===e.type&&!/^Error:/i.test(e.content.trim())}function Ro(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=>ko(e.content)).find(Boolean)??""}function Eo(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 jo({loading:e,children:t,className:s,style:r}){return n.jsx("div",{role:"status","aria-busy":e||void 0,className:s,style:r,children:t})}function Mo({title:e,actions:t}){return n.jsxs("header",{children:[n.jsx("span",{children:e}),t]})}function Ao(e){return n.jsx(To,{...e},e.source)}function To({className:e,style:s,title:r,actions:i,loading:o,loadingLabel:a,errorLabel:c,statusClassName:l,children:d}){const[u,h]=t.useState(!1);return n.jsxs("div",{className:e,style:s??(e?void 0:{display:"contents"}),children:[(null!=r||null!=i)&&n.jsx(Mo,{title:r,actions:i}),u||o?n.jsx(jo,{loading:o&&!u,className:l,children:u?c:a}):d(()=>h(!0))]})}function No({kind:e,src:t,label:s,onError:r,fillWidth:i,className:o,preload:a,mediaRef:c}){const l={ref:c,src:t,controls:!0,"aria-label":s,onError:r,preload:a,className:o};return"audio"===e?n.jsx("audio",{...l,style:{width:"100%"},children:n.jsx("track",{kind:"captions"})}):n.jsx("video",{...l,playsInline:!0,style:i?{width:"100%",height:"auto",maxHeight:"none"}:{maxWidth:"100%",maxHeight:"100%"},children:n.jsx("track",{kind:"captions"})})}function Po({id:e,children:s,anchor:r,ownerDocument:i,placement:o="top",className:a,topLayer:c,ownership:l,onDismiss:d}){const u=t.useRef(null),[h,m]=t.useState(null);return t.useLayoutEffect(()=>{const e=u.current,t=i.defaultView;if(!e||!t)return;c&&e.showPopover?.();const n=()=>{const n=r();n&&m(function(e,t,n,s){const{width:r,height:i}=t,o={right:s.width-e.right-6-8,left:e.left-6-8,top:e.top-6-8,bottom:s.height-e.bottom-6-8};let a=n.split("-")[0];const c={right:"left",left:"right",top:"bottom",bottom:"top"};o[a]<("left"===a||"right"===a?r:i)&&o[c[a]]>o[a]&&(a=c[a]);let l=e.top+(e.height-i)/2,d=e.left+(e.width-r)/2;return"left"===a&&(d=e.left-6-r),"right"===a&&(d=e.right+6),"top"!==a&&"bottom"!==a||(l="top"===a?e.top-6-i:e.bottom+6,n.endsWith("-start")&&(d=e.left),n.endsWith("-end")&&(d=e.right-r)),{top:Math.max(8,Math.min(l,s.height-i-8)),left:Math.max(8,Math.min(d,s.width-r-8))}}(n,e.getBoundingClientRect(),o,{width:t.innerWidth,height:t.innerHeight}))},s=e=>{"Escape"===e.key&&d?.()};n(),t.addEventListener("resize",n),t.addEventListener("scroll",n,!0),t.addEventListener("blur",d??n),i.addEventListener("keydown",s,!0);const a=t.ResizeObserver?new t.ResizeObserver(n):null;return a?.observe(e),()=>{a?.disconnect(),t.removeEventListener("resize",n),t.removeEventListener("scroll",n,!0),t.removeEventListener("blur",d??n),i.removeEventListener("keydown",s,!0)}},[r,i,o,c,d]),I.createPortal(n.jsx("span",{ref:u,id:e,role:"tooltip",popover:c?"manual":void 0,className:a,"data-lifeos-overlay-owners":l,style:{position:"fixed",top:h?.top??0,left:h?.left??0,visibility:h?"visible":"hidden",zIndex:99999},children:s}),i.body)}function Do({label:e,children:s,...r}){const i=t.useRef(null),o=t.useId(),[a,c]=t.useState(!1),l=t.useCallback(()=>i.current?.getBoundingClientRect(),[]),d=t.useCallback(()=>c(!1),[]);return n.jsxs(n.Fragment,{children:[n.jsx("button",{...r,ref:i,type:"button","aria-label":e,"aria-describedby":a?o:void 0,onPointerEnter:()=>c(!0),onPointerLeave:d,onFocus:()=>c(!0),onBlur:d,onClick:e=>{d(),r.onClick?.(e)},children:s}),a&&i.current&&n.jsx(Po,{id:o,ownerDocument:i.current.ownerDocument,anchor:l,className:"message-action-tooltip",onDismiss:d,children:e})]})}function Lo({position:e,onClose:s,onCopy:r,onCopyImage:i,copyImageLabel:o,onRevealFile:a,revealFileLabel:c,onRewind:l,onToggleSource:d,sourceOpen:u,t:h}){const m=t.useRef(null),f=t.useRef(s);f.current=s,t.useLayoutEffect(()=>{const t=m.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=()=>f.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 p=e=>{s(),e()};return I.createPortal(n.jsxs("div",{ref:m,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(m.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:()=>p(i),children:[n.jsx(U,{"aria-hidden":"true"}),o]}),a&&n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>p(a),children:[n.jsx(Y,{"aria-hidden":"true"}),c]}),l&&n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>p(l),children:[n.jsx(Ne,{"aria-hidden":"true"}),or().rewind]}),n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>p(r),children:[n.jsx(U,{"aria-hidden":"true"}),h.copyMessage]}),n.jsxs("button",{type:"button",role:"menuitem",onClick:()=>p(d),children:[n.jsx(B,{"aria-hidden":"true"}),u?h.hideMarkdownSource:h.viewMarkdownSource]})]}),document.body)}const Fo=new RegExp("((?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)[^\\n`<>\"')\\]},。!?;:、]*?\\.(?:png|jpg|jpeg|gif|webp|svg|heic|heif)(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?)","gi"),Oo=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],qo="\\s`<>\"')\\]},。!?;:、",_o="`<>\"')\\]},。!?;:、\\n\\r\\t",$o=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${qo}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),zo=new RegExp(`(^|[\\s([{>])((?=[^${_o}]*\\/)[^${_o}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${qo}]+)?)(?=$|[${qo}])`,"g");function Ho(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Bo(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 Uo(e){let t=Ho(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const e=t.slice(0,n);Bo(e,{allowBareFilename:!0})&&(t=e)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const e=s[1]??"";Bo(e,{allowBareFilename:!0})&&(t=e)}return Ho(t)}function Wo(e,t){return e.start<t.end&&t.start<e.end}function Ko(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 Go(e){if(Ko(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(Ko(n))return{start:e.start+t,end:e.end,rawCandidate:n}}return e}function Vo(e,t){return Bo(Uo(e),t)}function Qo(e){const t=Uo(e).toLowerCase();return Vo(t,{allowBareFilename:!0})&&Oo.some(e=>t.endsWith(e))}const Jo=/^[a-z][a-z0-9+.-]*:/i,Zo=/^[a-z]:[\\/]/i,Xo=/\.(?:md|markdown)$/i,Yo=/[/\\]$/,ea=e=>Xo.test(e)||Yo.test(e),ta="https://vibelet.local",na="/__vibelet_markdown__",sa=`${ta}${na}`;function ra(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!==ta)return null;if(t.pathname!==na)return null;const n=t.searchParams.get("path");return n&&ea(n)?n:null}(t);if(n)return n;if(Jo.test(t)&&!Zo.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return ea(s)?function(e){try{return decodeURIComponent(e)}catch{return e}}(s):null}function ia(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=oa(e,n);t+=e.slice(n,s),n=s;continue}if("["===e[n]&&"!"!==e[n-1]){const s=aa(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}(e)}).join("\n")}function oa(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 aa(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=ca(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=ca(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 ca(e){const t=ra(e);return t?`${sa}?path=${encodeURIComponent(t)}`:null}const la="https://vibelet.local/__vibelet_file__";function da(e){if(!e)return null;const t=ra(e);if(t)return t;let n=e.trim();if(n.startsWith(la))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=Uo(n),Vo(n,{allowBareFilename:!0})?n:null}const ua=e=>`${la}?path=${encodeURIComponent(e)}`;function ha(e){return e.value??e.children?.map(ha).join("")??""}function ma(){return e=>{const t=e=>{if("link"===e.type||"image"===e.type){const t=da(e.url);return void(t&&(e.url=ua(t),Qo(t)&&(e.alt=e.alt||ha(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)?(?=/))?${Fo.source}`,Fo.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($o)){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(zo)){const e=n[1]??"",s=n[2]??"",r=(n.index??0)+e.length,i=Go({start:r,end:r+s.length,rawCandidate:s}),o=t.filter(e=>Wo(e,i));if(0!==o.length){if(Ko(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=Ho(s.rawCandidate),i=Uo(r),o=s.rawCandidate.slice(r.length);Vo(r)&&!Qo(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:ua(n.target??n.value),children:[{type:"text",value:n.value}]}:{type:"text",value:n.value})};for(const i of e.matchAll(n)){const n=da(i[0]);n&&Qo(n)&&(r(e.slice(s,i.index)),t.push({type:"image",url:ua(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 fa=20971520,pa=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 ga(e,t){return pa.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"))>fa||!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>fa)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 va(e,n,s=1600){const r=da(e),i=bt(),[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(Nn(r,n));null!==s&&c.searchParams.set("w",String(s));const l=await ga(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 ya({src:e,alt:t,cwd:s,onOpen:r,gallery:i}){const o=da(e),{url:a,error:d,fail:u}=va(e,s),h=w[c(l().language)],m=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}: ${m}`,onClick:async t=>{t.preventDefault(),t.stopPropagation();const n=await(i?.())??[{src:e,alt:m,cwd:s}],a=n.findIndex(t=>t.src===e||o&&da(t.src)===o);Ti({images:a<0?[{src:e,alt:m,cwd:s}]:n,index:Math.max(0,a),onOpen:r})},children:d?n.jsxs("span",{className:"message-image-placeholder",children:[n.jsx(re,{"aria-hidden":"true"}),m," · ",h.fileOpenFailed]}):a?n.jsx("img",{src:a,alt:m,loading:"lazy",onError:u}):n.jsxs("span",{className:"message-image-placeholder",children:[n.jsx(oe,{className:"session-running-icon","aria-hidden":"true"}),m]})})}function wa({message:e,t}){return n.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function ba(e){if(!(e instanceof Element))return;const t=e.closest("[data-image-src], [data-file-path], a[href]");return t?da(t.dataset.imageSrc??t.dataset.filePath??t.getAttribute("href"))??void 0:void 0}function Sa(e){return"en"===e?"Show in file manager":"zh-TW"===e?"在檔案管理中顯示":"在文件管理中显示"}async function xa(e){const t="string"==typeof e?new Image:e;"string"==typeof e&&(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 Ia(e){const t=s().writeClipboardImage;t?await t(new Uint8Array(await(await xa(e)).arrayBuffer())):await navigator.clipboard.write([new ClipboardItem({"image/png":xa(e)})])}function ka(e){if(!(e instanceof Element))return;const t=e.closest(".message-image-preview"),n=t?.querySelector("img");return t?.dataset.imageSrc&&n?{src:t.dataset.imageSrc,cwd:t.dataset.imageCwd,preview:n}:void 0}function Ca({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 Ra({message:e,onCopy:t,t:s}){const r=function(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return xo(t);case"write":{const e=xo(t),n=wo(t,"content");return n&&e.push({label:"Content",isDiff:!0,value:"",diffNew:So(n,500)}),e}case"edit":{const e=xo(t),n=wo(t,"old_string")||wo(t,"oldString"),s=wo(t,"new_string")||wo(t,"newString");return(n||s)&&e.push({label:"Change",isDiff:!0,value:"",diffOld:So(n,300),diffNew:So(s,300)}),e}case"bash":{const e=wo(t,"command");return e?[{label:"Command",value:e,isCode:!0}]:[]}case"websearch":{const e=wo(t,"query");return e?[{label:"Query",value:e}]:[]}case"webfetch":{const e=[],n=wo(t,"url");n&&e.push({label:"URL",value:n});const s=wo(t,"prompt");return s&&e.push({label:"Prompt",value:So(s,200)}),e}case"glob":{const e=wo(t,"pattern");return e?[{label:"Pattern",value:e}]:[]}case"grep":{const e=[],n=wo(t,"pattern");n&&e.push({label:"Pattern",value:n,isCode:!0});const s=wo(t,"path");return s&&e.push({label:"In",value:s,isFilePath:!0}),e}default:{const e=[],n=wo(t,"command");if(n)return[{label:"Command",value:n,isCode:!0}];const s=wo(t,"file_path")||wo(t,"filePath");s&&e.push({label:"Path",value:s,isFilePath:!0});const r=wo(t,"description");r&&e.push({label:"Description",value:So(r,200)});const i=wo(t,"query");i&&e.push({label:"Query",value:i});const o=wo(t,"url");return o&&e.push({label:"URL",value:o}),e}}}(e.toolName,e.toolInput),i=ko(e.content),o=Io(e.content),a=function(e){return Io(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(Me,{"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(U,{"aria-hidden":"true"})})]}),r.length?n.jsx("div",{className:"tool-fields",children:r.map((e,t)=>n.jsx(Ca,{field:e},`${e.label}:${t}`))}):null,a?n.jsx("pre",{className:"json-box compact",children:o}):null]})}function Ea({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=Ro(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(U,{"aria-hidden":"true"})}),n.jsx("button",{className:"icon-button",onClick:s,type:"button",title:i.closeToolDetails,children:n.jsx(De,{"aria-hidden":"true"})})]})]}):null,n.jsx("div",{className:"tool-detail-list",children:e.map((e,t)=>n.jsx(Ra,{message:e,onCopy:r,t:i},`${e.historyKey??e.timestamp??e.toolName??"tool"}:${t}`))})]})}const ja=t.lazy(async()=>C(()=>import("./mermaid-O7DHMXV3-DcfB_Nfq.js").then(e=>e.a),__vite__mapDeps([39,1,2,40,30,41,42,43,44])).then(e=>({default:e.MessageMarkdown})));function Ma({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 Aa({activeMatch:e,baseCwd:s,message:r,onCopy:i,onRewind:o,onResend:a,onCloseTool:d,onOpenRemoteFile:u,onToggleSource:h,onToggleTool:m,sourceOpen:f,toolOpen:p,replying:g,queued:v,t:y}){const w="assistant"===r.role?en(r.content):r.content,[b,S]=t.useState(null),[x,I]=t.useState(""),k=Eo(c(l().language)),R="user"===r.role&&"info"!==r.type?o:void 0,E=function(e,t,n=!1){const s="interrupted"===e.delivery||"interrupted"===e.localDelivery?"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,y,v),j=(r.images??[]).filter(e=>Tn(e,"")||/^(?:data:image\/|https?:\/\/|blob:)/i.test(e)),M="tool"===r.role?ko(r.content):"";return n.jsxs("article",{className:`message ${r.role} ${"info"===r.type?"info":""} ${e?"match":""}`,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),S({x:e.clientX,y:e.clientY,image:ka(e.target),file:ba(e.target)})},onKeyDown:e=>{if("ContextMenu"!==e.key&&(!e.shiftKey||"F10"!==e.key))return;e.preventDefault(),e.stopPropagation();const t=e.currentTarget.getBoundingClientRect();S({x:t.left+16,y:t.top+16,image:ka(e.target),file:ba(e.target)})},children:[b&&n.jsx(Lo,{position:b,onClose:()=>S(null),onCopy:()=>i(r.content),onCopyImage:b.image?()=>{(async e=>{I("");try{await async function({src:e,cwd:t,preview:n}){const s=da(e);if(!s)return Ia(e);const r=bt();let i;try{if(!r)throw new Error("No pairing");const e=await ga(Nn(s,t),r.pairToken);i=URL.createObjectURL(e),await Ia(i)}catch(o){if(!n.complete||!n.naturalWidth)throw o;await Ia(n)}finally{i&&URL.revokeObjectURL(i)}}(e),I(k.copied)}catch{I(k.failed)}})(b.image)}:void 0,copyImageLabel:k.copy,onRevealFile:void b.file,revealFileLabel:Sa(c(l().language)),onRewind:R,onToggleSource:h,sourceOpen:f,t:y}),x&&n.jsx("div",{className:"message-image-copy-status",role:"status",children:x}),n.jsxs("div",{className:"message-meta",children:[n.jsx("span",{children:Xt(r,y)}),n.jsxs("div",{className:"message-meta-side",children:[E&&n.jsx("span",{className:"message-delivery","data-state":E.state,role:"status","aria-label":E.label,title:E.title,children:E.label}),n.jsx("time",{children:Zt(r.timestamp,Date.now(),y)})]})]}),f?n.jsx(wa,{message:r,t:y}):"tool"===r.role?n.jsxs("button",{className:"tool-inline-summary","aria-expanded":p,onClick:m,type:"button",children:[n.jsxs("span",{children:[n.jsx(Pe,{"aria-hidden":"true"}),r.toolName??y.tool]}),M?n.jsx("small",{children:M}):null]}):"assistant"===r.role||"user"===r.role?n.jsx(t.Suspense,{fallback:n.jsx("pre",{children:w}),children:n.jsx(ja,{baseCwd:s,content:Ft(w,r.images),onOpenRemoteFile:u,additionalImages:j})}):n.jsx("pre",{children:r.content}),r.images?.length?n.jsx("div",{className:"message-image-attachments",children:r.images.map(e=>j.includes(e)?n.jsx(ya,{src:e,cwd:s,onOpen:u,gallery:async()=>[...(await C(async()=>{const{collectMessageImages:e}=await import("./collectMessageImages-CLhjY1R-.js");return{collectMessageImages:e}},__vite__mapDeps([41,30,1,2]))).collectMessageImages(r.content,s),...j.map(e=>({src:e,cwd:s}))]},e):n.jsxs("button",{type:"button",className:"message-file-attachment",title:e,"data-file-path":e,onClick:()=>u(e,s),children:[n.jsx(fe,{size:16,"aria-hidden":"true"}),wn(e)]},e))}):null,"tool"===r.role&&p?n.jsx(Ea,{messages:[r],onClose:d,onCopy:i,t:y}):null,g&&n.jsx(Ma,{label:y.replyingMessage}),n.jsxs("div",{className:"message-actions","aria-label":y.messageActions,role:"group",children:[R&&n.jsx(Do,{onClick:R,label:or().rewind,children:n.jsx(Ne,{"aria-hidden":"true"})}),a&&"user"===r.role&&"info"!==r.type&&n.jsx(Do,{onClick:a,label:or().resend,children:n.jsx(Se,{"aria-hidden":"true"})}),n.jsx(Do,{label:y.copyMessage,onClick:()=>i(f?r.content:w),children:n.jsx(U,{"aria-hidden":"true"})}),n.jsx(Do,{label:f?y.hideMarkdownSource:y.viewMarkdownSource,"aria-expanded":f,onClick:h,children:n.jsx(B,{"aria-hidden":"true"})})]})]})}function Ta(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 kt(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 Na({feedback:e}){if(!e)return null;const t="success"===e.tone?_:De;return n.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[n.jsx(t,{"aria-hidden":"true"}),e.message]})}function Pa({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(De,{"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(we,{"aria-hidden":"true"}),t]})]})}function Da({label:e}){return n.jsx("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children: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 La({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.detail&&n.jsx("code",{className:"failed-send-detail",children:e.detail}),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(we,{"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(De,{"aria-hidden":"true"})})]})}function Fa({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"})})}function Oa({label:e,onClick:t,disabled:s}){return n.jsx("div",{className:"conversation-window-gate",children:n.jsx("button",{type:"button",onClick:t,disabled:s,children:e})})}function qa({label:e}){return n.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:n.jsx("div",{className:"message assistant replying-placeholder",children:n.jsx(Ma,{label:e})})})}const _a="vibelet.web.hideDeviceAddresses";function $a({activeDaemonId:e,busy:r,fallbackName:o,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:m,onRemove:f}){const{hidden:p,toggle:g}=function(){const[e,n]=t.useState(()=>{try{return"true"===i().getItem(_a)}catch{return!1}});return{hidden:e,toggle:()=>{const t=!e;n(t);try{i().setItem(_a,String(t))}catch{}}}}(),v=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,y=p?l.showDeviceAddresses:l.hideDeviceAddresses,[w,b]=t.useState(!1),[S,x]=t.useState(null),[I,k]=t.useState(""),C=t.useRef(null),R=t.useRef(null),E=t.useRef(null),j=s().isLocalDaemon??(()=>!1),M=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),A=d.find(t=>t.daemonId===e),T=v(A?.label||o||e?.slice(0,10)||"Vibelet");t.useEffect(()=>{w||x(null),S&&E.current?.select()},[w,S]);const N="desktop"===s().kind,P=N&&e?M.find(t=>t.daemonId!==e):void 0,D=r||"connecting"===a,F=t.useCallback(()=>{P&&!D&&(b(!1),u(P))},[P,D,u]),O=P?`${l.switchToRecentDevice(v(P.label))} (⌥Tab)`:"";return t.useEffect(()=>{if(!N)return;const e=e=>{"Tab"!==e.key||!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.isComposing||e.defaultPrevented||P&&(e.preventDefault(),e.stopPropagation(),e.repeat||F())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[N,P,F]),t.useEffect(()=>{if(!w)return;const e=e=>{e.target instanceof Node&&!C.current?.contains(e.target)&&b(!1)},t=e=>{"Escape"===e.key&&(b(!1),C.current?.contains(document.activeElement)&&R.current?.focus())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[w]),n.jsxs("div",{className:"device-switcher",ref:C,children:[n.jsxs("div",{className:"device-switcher-actions",children:[n.jsxs("button",{ref:R,"aria-expanded":w,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:T,type:"button",children:[n.jsx("strong",{children:T}),n.jsx($,{"aria-hidden":"true"})]}),P?n.jsx("button",{type:"button",className:"device-quick-switch","aria-label":O,"aria-keyshortcuts":"Alt+Tab",title:O,disabled:D,onClick:F,children:n.jsx(L,{"aria-hidden":"true"})}):null]}),n.jsxs("span",{className:`brand-connection ${a}`,children:[n.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),w?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":y,title:y,onClick:g,children:p?n.jsx(K,{"aria-hidden":"true"}):n.jsx(G,{"aria-hidden":"true"})})]}),M.map(t=>{const i=t.daemonId===e,o=(e=>{const t=s();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=v(t.label);return n.jsx("div",{className:"device-switcher-row"+(i?" is-active":""),children:S===t.daemonId?n.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),S&&I.trim()&&(h(S,I),x(null))},children:[n.jsx("input",{ref:E,"aria-label":l.rename,autoFocus:!0,onChange:e=>k(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),x(null))},value:I}),n.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!I.trim(),type:"submit",children:n.jsx(_,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>x(null),children:n.jsx(De,{"aria-hidden":"true"})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"device-connect-button",disabled:r||i,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":i?"true":void 0,type:"button",children:[i?n.jsx(_,{"aria-hidden":"true"}):n.jsx(ve,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsxs("strong",{className:"device-target-heading",children:[n.jsx("span",{children:a}),i?n.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?n.jsx("small",{children:v(t.displayName)}):null,j(t.daemonId)||!t.displayName?n.jsx("small",{children:j(t.daemonId)?l.currentDevice:v(t.daemonId)}):null,o?n.jsx("small",{className:"device-connection-endpoint",children:v(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(pe,{"aria-hidden":"true"})}),f&&!j(t.daemonId)&&n.jsx("button",{"aria-label":`${l.removeDevice} ${a}`,title:`${l.removeDevice} ${a}`,className:"device-rename-button device-remove-button",disabled:r,onClick:()=>{f(t),b(!1)},type:"button",children:n.jsx(Ae,{"aria-hidden":"true"})}),m&&s().canEditConnection?.(t.daemonId)&&n.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{m(t),b(!1)},type:"button",children:n.jsx(ke,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?n.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function za({undo:e,disabled:s,t:r}){const i=t.useRef(null),o=e?.expiresAt;if(t.useLayoutEffect(()=>{void 0!==o&&i.current?.style.setProperty("--archive-elapsed",o-Date.now()-1e4+"ms")},[o]),!e)return null;const a=e.session.title||e.session.sessionId;return n.jsxs("div",{className:"archive-undo-notice",children:[n.jsxs("div",{className:"archive-undo-description",role:"status",children:[n.jsx("span",{children:r.archived}),n.jsx("strong",{title:a,children:a})]}),n.jsxs("button",{type:"button",disabled:s,onClick:()=>{e.run()},"aria-label":r.undoLastArchive,children:[n.jsx(Ne,{"aria-hidden":"true"}),n.jsx("span",{children:r.undoArchive})]}),n.jsx("span",{"aria-hidden":"true",className:"archive-undo-clock",ref:i,style:{"--archive-window":"10000ms"}})]},o)}function Ha({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(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":s===e.value})]},e.value))})]})}function Ba({folder:e,initialValue:s,t:r,onClose:i,onSave:o}){const[a,c]=t.useState(s),l=t.useRef(null),d=R(i,l);return I.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(je,{})}),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(De,{"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 Ua({folderToggle:e,search:s,connected:r,filtersOpen:i,filtersActive:o,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,m]=t.useState(Boolean(s)),f=h||s.length>0,p=t.useRef(null),g=t.useRef(null),v=t.useRef(!1),y=()=>{v.current=!0,l(),c(""),m(!1),g.current?.focus(),v.current=!1};return t.useEffect(()=>{const e=()=>{m(!0),requestAnimationFrame(()=>p.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":f,className:"rail-create-button",title:ti(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{m(!0),requestAnimationFrame(()=>p.current?.focus())},children:n.jsx(Ie,{"aria-hidden":"true"})}),n.jsx(ki,{"aria-label":a.newSession,className:"rail-create-button",disabled:!r,onClick:u,title:a.newSession,type:"button",children:n.jsx(ye,{"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(te,{"aria-hidden":"true"})})]})]}),f&&n.jsxs("div",{className:"search-box rail-search-overlay",onBlur:e=>{v.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),m(Boolean(s)))},children:[n.jsx(Ie,{"aria-hidden":"true"}),n.jsx("input",{ref:p,"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(De,{"aria-hidden":"true"})})]})]})}function Wa({menu:e,pending:s,t:r,onOpen:i,onDetails:o,onRename:a,onCopyResumeCommand:c,onResumeInTerminal:l,terminalBusy:d,onTogglePinned:u,onToggleArchived:h,onDelete:m}){const f=t.useRef(null),[p,g]=t.useState(Yr);t.useEffect(()=>{const e=()=>g(Yr());return window.addEventListener(Br,e),()=>window.removeEventListener(Br,e)},[]),t.useLayoutEffect(()=>{const t=f.current;if(!t)return;const n=t.getBoundingClientRect();t.style.left=`${Math.max(10,Math.min(e.x,window.innerWidth-n.width-10))}px`,t.style.top=`${Math.max(10,Math.min(e.y,window.innerHeight-n.height-10))}px`},[e.x,e.y,p]);const v=e=>{const t=ei(e,p);return t?n.jsx("kbd",{children:Jr(t)}):null};return n.jsxs("div",{ref:f,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:i,children:[n.jsx(E,{"aria-hidden":"true"}),n.jsx("span",{children:r.open}),v("sessionOpen")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:a,children:[n.jsx(pe,{"aria-hidden":"true"}),n.jsx("span",{children:r.rename}),v("sessionRename")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:o,children:[n.jsx(ie,{"aria-hidden":"true"}),n.jsx("span",{children:r.details}),v("sessionDetails")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:c,children:[n.jsx(U,{"aria-hidden":"true"}),n.jsx("span",{children:r.copyResumeCommand}),v("sessionCopyResume")]}),l&&n.jsxs("button",{type:"button",role:"menuitem",disabled:s||d,title:d?r.resumeTerminalBusy:r.resumeInTerminal,onClick:l,children:[n.jsx(Me,{"aria-hidden":"true"}),n.jsx("span",{children:r.resumeInTerminal}),v("sessionResumeTerminal")]}),n.jsx("span",{className:"context-menu-separator"}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:u,children:[n.jsx(ge,{"aria-hidden":"true"}),n.jsx("span",{children:e.session.pinned?r.unpin:r.pin}),v("sessionPin")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:h,children:[n.jsx(P,{"aria-hidden":"true"}),n.jsx("span",{children:e.session.archived?r.unarchive:r.archive}),v("sessionArchive")]}),n.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:m,children:[n.jsx(Ae,{"aria-hidden":"true"}),n.jsx("span",{children:r.delete}),v("sessionDelete")]})]})}function Ka({title:e,t:s,onClose:r,onSave:i}){const o=t.useRef(e),a=t.useRef(!1),[c,l]=t.useState(!1),[d,u]=t.useState(!1),h=t.useRef(null),m=t.useRef(!1),f=t.useRef(!1),p=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");r(),f.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};t.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(m.current||a.current)return;const t=(h.current?.value??"").trim();if(t&&t!==e){m.current=!0,u(!0),l(!1);try{if(await i(t))return void p()}catch{}m.current=!1,u(!1),l(!0),h.current?.focus()}else p()},v=()=>{m.current=!0,f.current=!0,p()};return n.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||g()},onKeyDown:e=>{e.stopPropagation(),a.current||e.nativeEvent.isComposing||229===e.keyCode?"Enter"===e.key&&e.preventDefault():("Enter"===e.key&&(f.current=!0),"Escape"!==e.key||d||(e.preventDefault(),v()))},children:[n.jsxs("div",{className:"session-rename-controls",children:[n.jsx("input",{ref:h,"aria-label":s.rename,defaultValue:o.current,readOnly:d,onCompositionStart:()=>{a.current=!0},onCompositionEnd:e=>{a.current=!1,e.currentTarget.form?.contains(document.activeElement)||g()}}),n.jsx("button",{type:"button",disabled:d,onPointerDown:e=>{0===e.button&&e.preventDefault()},onClick:v,children:s.cancel})]}),c&&n.jsx("small",{role:"alert",children:s.renameFailed})]})}function Ga({session:e,renamingRowId:s,onRename:r,onCloseRename:i,active:o,selected:c=!1,responding:l,pending:d=!1,attentionReason:u,tagLabels:h,showFolder:m=!0,t:f,onSelect:p,onContextMenu:g,onToggleArchived:v,onTogglePinned:y}){const w=e.creationError,b=t.useId(),S=s===b,x=a(e),k=Zt(e.lastActivityAt,Date.now(),f),C=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",R=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),[E,j]=t.useState(null),M=t.useRef(null),A=t.useRef(null),T=t.useRef({x:0,y:0}),N=t.useRef(null),D=()=>{const e=A.current;if(!e)return;const{x:t,y:n}=T.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(()=>{E&&D()},[E,x]);const L=()=>{null!==M.current&&window.clearTimeout(M.current),M.current=null,null!==N.current&&window.cancelAnimationFrame(N.current),N.current=null,j(null)};return t.useEffect(()=>()=>{null!==M.current&&window.clearTimeout(M.current),null!==N.current&&window.cancelAnimationFrame(N.current)},[e.sessionId]),t.useEffect(()=>{if(!E)return;const e=()=>j(null);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[E]),n.jsxs("div",{className:"session-item","data-row-id":b,onContextMenu:e=>{L(),g?.(e)},"data-renaming":S||void 0,"data-active":o||void 0,"data-multi-selected":c||void 0,"data-statuses":Number(Boolean(e.pinned))+Number(Boolean(e.archived)),onMouseEnter:e=>{"focus"!==E&&(T.current={x:e.clientX,y:e.clientY},S||(e=>{null!==M.current&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null,e.isConnected&&e.matches(":hover")&&j("hover")},2e3)})(e.currentTarget))},onMouseMove:e=>{"focus"!==E&&(T.current={x:e.clientX,y:e.clientY},E&&null===N.current&&(N.current=window.requestAnimationFrame(()=>{N.current=null,D()})))},onMouseLeave:()=>{"focus"!==E&&L()},onKeyDown:e=>{"focus"!==E||S||"Escape"!==e.key||(e.stopPropagation(),e.preventDefault(),L())},onFocusCapture:e=>{if(!S&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==M.current&&window.clearTimeout(M.current),M.current=null;const t=e.currentTarget.getBoundingClientRect();T.current={x:t.left+t.width/2,y:t.bottom},j("focus")}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||L()},children:[n.jsxs("button",{className:`session-row ${o?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":b,disabled:S,"aria-current":o?"true":void 0,"aria-pressed":c,onClick:p,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[n.jsxs("span",{className:"session-row-head",children:[n.jsx("strong",{children:x}),n.jsx("span",{className:"session-row-metadata",children:n.jsx("span",{className:"session-row-time",title:k,children:k})}),l?n.jsx("span",{className:"session-running-indicator",role:"img","aria-label":f.agentResponding,title:f.agentResponding}):n.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),w&&n.jsxs("span",{className:"session-attention-reason",title:w,children:[f.sessionCreateFailed,": ",w]}),u&&n.jsx("span",{className:"session-attention-reason",children:u}),h?.length?n.jsx("span",{className:"directory-tag-row",title:f.directoryTags,children:h.map(e=>n.jsx("em",{children:e},e))}):null,n.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),S&&r&&i&&n.jsx(Ka,{title:x,t:f,onClose:i,onSave:t=>r(e,t)}),n.jsxs("div",{className:"session-quick-actions",children:[n.jsx("button",{"aria-label":e.pinned?f.unpin:f.pin,className:e.pinned?"is-pinned":void 0,disabled:d,onClick:y,title:e.pinned?f.unpin:f.pin,type:"button",children:n.jsx(ge,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":e.archived?f.unarchive:f.archive,className:e.archived?"is-archived":void 0,disabled:d,onClick:v,title:e.archived?f.unarchive:f.archive,type:"button",children:n.jsx(P,{"aria-hidden":"true"})})]}),n.jsxs("div",{className:"session-git-links",children:[m&&n.jsx("span",{className:"session-git-folder",title:e.cwd,children:C}),e.branch&&(R&&o?n.jsx("a",{className:"session-branch-link",href:R,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&&(o?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:f.pinned}):null,e.archived?n.jsx("span",{className:"session-row-status",children:f.archived}):null,n.jsx("span",{className:"session-row-agent",children:qs[e.agent]})]}),E&&!S&&I.createPortal(n.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:A,style:{left:0,top:0,visibility:"hidden"},children:n.jsx("span",{children:x})}),document.body)]})}function Va(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(Qa,{...e,...r})}const Qa=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:m,respondingSessionIds:f,t:p,visibleSessions:g,onEditFolderTags:v,onOpenCreateMenu:y,onOpenSessionMenu:w,onSelectSession:b,onToggleSessionArchived:S,onToggleSessionPinned:x,onToggleFolder:I}){const k=t.useId(),[C,R]=t.useState(()=>new Set),E=t.useRef(null),j=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(j);R(t=>[...t].every(t=>e.has(t))?t:new Set([...t].filter(t=>e.has(t)))),E.current&&!e.has(E.current)&&(E.current=null)},[j]),t.useEffect(()=>{0===C.size&&(E.current=e)},[e,C]);const M=(t,n)=>{if(n.shiftKey){const s=E.current??e??t,r=j.indexOf(s),i=j.indexOf(t),o=j.slice(Math.min(r<0?i:r,i),Math.max(r,i)+1);return R(e=>{const t=Gr(n)?new Set(e):new Set;for(const n of o)t.add(n);return t}),void(E.current=s)}E.current=t,Gr(n)?R(n=>{const s=n.size?new Set(n):new Set(e?[e]:[]);return s.has(t)?s.delete(t):s.add(t),s}):(R(new Set),b(t))};return l?n.jsxs(n.Fragment,{children:[d.map(t=>{const l=!!o[t.folder],d=`${k}-${encodeURIComponent(t.folder)}`,g="folder"===t.kind?a[t.folder]??t.sessions.length:t.sessions.length,b="attention"===t.kind?p.needsAttentionSessionsGroup:"running"===t.kind?p.runningSessionsGroup:"pinned"===t.kind?p.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:b,onClick:()=>I(t.folder),type:"button",children:[n.jsx(z,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===t.kind?n.jsx(ie,{"aria-hidden":"true"}):"running"===t.kind?n.jsx(N,{"aria-hidden":"true"}):"pinned"===t.kind?n.jsx(ge,{"aria-hidden":"true"}):l?n.jsx(ee,{"aria-hidden":"true"}):n.jsx(X,{"aria-hidden":"true"}),n.jsx("span",{children:"folder"===t.kind?t.folder.split(/[\\/]/).filter(Boolean).at(-1)||t.folder:b})]}),"folder"===t.kind?n.jsxs(n.Fragment,{children:[n.jsx("button",{"aria-label":c(t.folder).length?p.editDirectoryTags:p.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>v(t.folder),title:c(t.folder).length?p.editDirectoryTags:p.addDirectoryTags,type:"button",children:n.jsx(je,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":p.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>y(e,t.folder),title:p.newSession,type:"button",children:n.jsx(ye,{"aria-hidden":"true"})})]}):null,n.jsx("small",{className:"folder-session-count",title:`${g} ${p.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(Ga,{renamingRowId:s,onRename:r,onCloseRename:i,active:o.sessionId===e,selected:C.has(o.sessionId),responding:f.has(o.sessionId),attentionReason:h?.[o.sessionId],pending:m?.has(o.sessionId),session:o,showFolder:"folder"!==t.kind,tagLabels:c(o.cwd),t:p,onContextMenu:e=>w(e,o),onSelect:e=>M(o.sessionId,e),onToggleArchived:()=>S(o),onTogglePinned:()=>x(o)},o.sessionId))})]},t.folder)}),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:p.noSessionsMatch})}):null]}):n.jsxs(n.Fragment,{children:[g.map(t=>n.jsx(Ga,{renamingRowId:s,onRename:r,onCloseRename:i,active:t.sessionId===e,selected:C.has(t.sessionId),responding:f.has(t.sessionId),attentionReason:h?.[t.sessionId],pending:m?.has(t.sessionId),session:t,tagLabels:c(t.cwd),t:p,onContextMenu:e=>w(e,t),onSelect:e=>M(t.sessionId,e),onToggleArchived:()=>S(t),onTogglePinned:()=>x(t)},t.sessionId)),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:p.noSessionsMatch})}):null]})});function Ja({agentFilter:e,t,onAgentFilterChange:s,showAntigravity:r}){return n.jsx(Ha,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex},...r||"antigravity"===e?[{value:"antigravity",label:"Antigravity"}]:[]],onChange:s})}function Za({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(_,{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(_,{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(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function Xa({connectionIndicators:e,archiveUndo:r,hasDaemonUpdate:i=!1,activeSessionId:o,busy:a,collapsedFolders:c,allFoldersCollapsed:l,currentCwd:d,activeDaemonId:u,displayName:h,savedTargets:m,directoryTags:f,folderCounts:p,groupFolders:g,sessionSort:v,onSessionSortChange:y,groupedSessions:w,hideArchived:b,separatePinnedGroup:S,showNeedsAttentionGroup:x,showRunningGroup:k,inventoryVersion:C,nextCursor:R,phase:E,attentionReasons:j,pendingSessionIds:M,respondingSessionIds:A,search:T,sessionAgentFilter:N,sessionsCount:P,sinceFilter:D,statusText:L,t:F,visibleSessions:O,onLoadMore:q,onCopyResumeCommand:_,onResumeInTerminal:$,onConnectTarget:z,onRequestNewSession:H,onDeleteSession:B,onRenameSession:U,onEditFolderTags:W,onOpenSessionDetails:K,onResetFilters:G,onRenameTarget:V,onEditConnection:Q,onRemoveTarget:J,onSearchChange:Z,onSearchCommit:X,onSelectSession:Y,onToggleSessionArchived:ee,onToggleSessionPinned:te,onSessionAgentFilterChange:ne,onSinceFilterChange:se,onToggleFolder:re,onToggleAllFolders:ie,onToggleGroupFolders:ce,onToggleHideArchived:le,onToggleNeedsAttentionGroup:ue,onToggleRunningGroup:he,onToggleSeparatePinnedGroup:me}){t.useEffect(()=>(s().onDaemonUpdateChange?.(i),()=>s().onDaemonUpdateChange?.(!1)),[i]);const fe=function({activeSessionId:e,activeDaemonId:n,groupFolders:r,groupedSessions:i,collapsedFolders:o,onToggleFolder:a}){const c=t.useRef(null),l=t.useRef({key:"",revealed:!1});return t.useLayoutEffect(()=>{if("desktop"!==s().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(r){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,r,i,a]),c}({activeSessionId:o,activeDaemonId:u,groupFolders:g,groupedSessions:w,collapsedFolders:c,onToggleFolder:re}),pe=t.useRef(null),ge=r?.session.sessionId;t.useLayoutEffect(()=>{const e=fe.current;if(!e)return;if(matchMedia("(prefers-reduced-motion: reduce)").matches)return void(pe.current=null);const t=Array.from(e.querySelectorAll(".session-row[data-row-id]")),n=e.scrollTop,s=e.getBoundingClientRect().top,r=new Map(t.map(e=>[e.dataset.rowId,e.getBoundingClientRect().top-s+n])),i=pe.current;if(pe.current={id:ge,daemon:u,rows:r},i&&i.daemon===u&&i.id!==ge)for(const o of t){const e=o.dataset.rowId,t=i.rows.get(e),n=r.get(e);void 0!==t&&Math.abs(t-n)>1?o.animate([{translate:`0 ${t-n}px`},{translate:"0 0"}],{duration:210,easing:"cubic-bezier(.22, 1, .36, 1)"}):ge||void 0!==t||o.dataset.sessionId!==i.id||o.animate([{opacity:.25},{opacity:1}],{duration:160,easing:"ease-out"})}},[u,ge,w,fe,O]);const[ve,ye]=t.useState(null),[we,be]=t.useState(!1),[Se,xe]=t.useState(null);t.useEffect(()=>{if(!Se)return;const e=window.setTimeout(()=>xe(null),2400);return()=>window.clearTimeout(e)},[Se]);const[Ie,ke]=t.useState(null),[Re,Ee]=t.useState(null),je=t.useRef(null),Me=t.useRef(null),[Ae,Te]=t.useState(null),Ne="updated"!==v||"all"!==N||"30d"!==D||!g||g&&(x||k||S)||b,Pe=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}}(R,q,"updated"!==v||!b),De=!!Re&&Boolean(M?.has(Re.session.sessionId)),Le=t.useCallback(e=>f[function(e){return"string"==typeof e&&e.trim().length>0?e:void 0}(e)??"/"]??[],[f]),Fe=`${L} · ${"connected"===E?`${O.length}/${P} sessions · v${C??"-"}`:F.sameOriginAccess}`,Oe=s().toolbarTarget?.("left");t.useLayoutEffect(()=>{if(!we)return;const e=()=>{const e=je.current?.getBoundingClientRect();if(!e)return;const t=Math.min(820,window.innerWidth-24);Te({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)},[we]),t.useEffect(()=>{if(!we&&!Re)return;const e=e=>{const t=e.target;t instanceof Node&&(je.current?.contains(t)||Me.current?.contains(t))||(be(!1),Ee(null))},t=e=>{"Escape"===e.key&&(be(!1),Ee(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[Re,we]);const qe=(e,t)=>{Ee(null),be(!1),H(t)},_e=Boolean($&&u&&s().resumeInTerminal&&s().isLocalDaemon?.(u)),$e=(e,t,n)=>{if("sessionOpen"!==e&&"sessionDelete"!==e&&M?.has(t.sessionId))return!1;if("sessionRename"===e&&!n)return!1;if("sessionResumeTerminal"===e&&(!_e||A.has(t.sessionId)))return!1;switch(Ee(null),e){case"sessionOpen":Y(t.sessionId);break;case"sessionRename":ye(n);break;case"sessionDetails":fe.current?.querySelector(`.session-row[data-row-id="${CSS.escape(n)}"]`)?.focus({preventScroll:!0}),K(t);break;case"sessionCopyResume":Promise.resolve(_(t)).then(()=>xe({message:F.commandCopied,tone:"success"})).catch(()=>xe({message:F.copyResumeFailed,tone:"error"}));break;case"sessionResumeTerminal":$?.(t);break;case"sessionPin":te(t);break;case"sessionArchive":ee(t);break;case"sessionDelete":B(t)}return!0};!function({menu:e,activeSessionId:n,sessions:s,run:r}){const i=t.useRef({menu:e,activeSessionId:n,sessions:s,run:r});i.current={menu:e,activeSessionId:n,sessions:s,run:r},t.useEffect(()=>{const e=e=>{const{command:t,event:n}=e.detail,{menu:s,activeSessionId:r,sessions:o,run:a}=i.current;if(!s&&n.target instanceof Element&&(n.target.closest(".session-rename-inline")||"sessionRename"!==t&&n.target.closest('input, textarea, select, [contenteditable="true"], [role="textbox"], .xterm')))return;const c=Array.from(document.querySelectorAll(".session-rail .session-row")),l=n.target instanceof Element?n.target.closest(".session-item"):null,d=l?.querySelector(".session-row")??c.find(e=>e.dataset.sessionId===r),u=s?.session??o.find(e=>e.sessionId===d?.dataset.sessionId);u&&a(t,u,s?.rowId??d?.dataset.rowId??"")&&(n.preventDefault(),n.stopPropagation())};return window.addEventListener(zr,e),()=>window.removeEventListener(zr,e)},[])}({menu:Re,activeSessionId:o,sessions:O,run:$e});const ze=e=>{Re&&$e(e,Re.session,Re.rowId)},He=n.jsxs("div",{className:"brand-block",title:Fe,children:[n.jsx("div",{className:"brand-mark","aria-hidden":"true",children:n.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-iv8HSlJj.webp",width:"40"})}),n.jsx($a,{activeDaemonId:u,busy:a,fallbackName:h,phase:E,statusText:L,t:F,targets:m,onConnect:z,onRename:V,onEditConnection:Q,onRemove:J})]});return n.jsxs("aside",{className:"session-rail","aria-label":F.sessions,children:[Oe?I.createPortal(He,Oe):He,n.jsxs("div",{className:"search-filter-wrap",ref:je,children:[n.jsx(Ua,{folderToggle:g&&w.length>0&&n.jsx("button",{"aria-label":l?F.expandAllSessions:F.collapseAllSessions,"aria-pressed":l,className:"session-folders-toggle",onClick:ie,title:l?F.expandAllSessions:F.collapseAllSessions,type:"button",children:l?n.jsx(ae,{"aria-hidden":"true"}):n.jsx(de,{"aria-hidden":"true"})}),search:T,connected:"connected"===E,filtersOpen:we,filtersActive:Ne,t:F,onSearchChange:Z,onSearchCommit:X,onToggleFilters:()=>be(e=>!e),onCreate:qe}),we&&Ae?I.createPortal(n.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":F.sessionFilters,ref:Me,style:{top:Ae.top,left:Ae.left},children:[n.jsx(Ha,{label:F.sessionSortLabel,value:v,options:[{value:"updated",label:F.sessionSortUpdated},{value:"created",label:F.sessionSortCreated},{value:"title",label:F.sessionSortTitle},{value:"folder",label:F.sessionSortFolder}],onChange:y}),n.jsx(Ja,{showAntigravity:O.some(e=>"antigravity"===e.agent),agentFilter:N,t:F,onAgentFilterChange:ne}),n.jsx(Ha,{label:F.searchTimeRangeLabel,value:D,options:[{value:"all",label:F.searchTimeRangeAllTime},{value:"7d",label:F.searchTimeRangeLast7Days},{value:"30d",label:F.searchTimeRangeLast30Days},{value:"90d",label:F.searchTimeRangeLast90Days}],onChange:se}),n.jsx(Za,{groupFolders:g,hideArchived:b,separatePinnedGroup:S,showNeedsAttentionGroup:x,showRunningGroup:k,t:F,onToggleGroupFolders:ce,onToggleHideArchived:le,onToggleNeedsAttentionGroup:ue,onToggleRunningGroup:he,onToggleSeparatePinnedGroup:me}),Ne?n.jsx("button",{className:"filter-reset-button",onClick:G,type:"button",children:F.resetFilters}):null]}),document.body):null]}),n.jsxs("div",{className:"session-list studio-scroll-edge-fade",ref:fe,tabIndex:-1,children:[n.jsx(Va,{activeSessionId:o,renamingRowId:ve,onRenameSession:U,onCloseRename:()=>ye(null),collapsedFolders:c,folderCounts:p,getFolderTags:Le,groupFolders:g,groupedSessions:w,phase:E,attentionReasons:j,pendingSessionIds:M,respondingSessionIds:A,t:F,visibleSessions:O,onEditFolderTags:e=>{be(!1),Ee(null),ke({folder:e,value:Le(e).join(", ")})},onOpenCreateMenu:qe,onOpenSessionMenu:(e,t)=>{e.preventDefault(),Ee({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:Y,onToggleSessionArchived:ee,onToggleSessionPinned:te,onToggleFolder:re},u??"unconnected"),Pe.canLoadMore?n.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(Pe.loading?"loading":""),ref:Pe.sentinelRef,role:"status",children:Pe.loading?n.jsxs(n.Fragment,{children:[n.jsx(oe,{className:"spin","aria-hidden":"true"}),n.jsx("span",{children:F.loadingMore})]}):null}):null]}),n.jsx(za,{undo:r,disabled:a||"connected"!==E,t:F}),n.jsxs("div",{className:"session-rail-footer",children:[n.jsx("div",{className:"rail-footer-indicators",children:e}),s().openSettings&&n.jsxs("button",{"aria-label":F.settings,className:"icon-button rail-settings-button",onClick:()=>s().openSettings?.(i?"daemon":void 0),title:F.settings,type:"button",children:[n.jsx(Ce,{"aria-hidden":"true"}),s().settingsBadge?.(i)]})]}),Ie?n.jsx(Ba,{folder:Ie.folder,initialValue:Ie.value,t:F,onClose:()=>ke(null),onSave:e=>{Ie&&(W(Ie.folder,e),ke(null))}}):null,Re?n.jsx(Wa,{menu:Re,pending:De,t:F,onOpen:()=>ze("sessionOpen"),onRename:()=>ze("sessionRename"),onDetails:()=>ze("sessionDetails"),onCopyResumeCommand:()=>ze("sessionCopyResume"),onResumeInTerminal:_e?()=>ze("sessionResumeTerminal"):void 0,terminalBusy:A.has(Re.session.sessionId),onTogglePinned:()=>ze("sessionPin"),onToggleArchived:()=>ze("sessionArchive"),onDelete:()=>ze("sessionDelete")}):null,n.jsx(Na,{feedback:Se})]})}function Ya({collapsed:e,children:t,onExpand:r,onResize:i,t:o}){const a=s().toolbarTarget?.("left"),c=n.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:r,title:ti(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:n.jsx(he,{"aria-hidden":"true"})});return n.jsxs(n.Fragment,{children:[a?I.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 ec(e){const n=Ve(),r=n.items.find(e=>e.id===n.right.browser&&"right"===e.location),i=r?.currentUrl??r?.url,o=t.useRef(null);return t.useEffect(()=>{o.current!==n.scopeKey&&(o.current=n.scopeKey,"desktop"!==s().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"===s().kind&&"browser"===e.controlTab&&(!i||"about:blank"===i))&&e.setControlTab("files"),e.setRightSidebarCollapsed(e=>!e)}}const tc={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 nc({workspace:e,onSelect:r}){const[i,o]=t.useState(!1),[a,d]=t.useState(""),u=function(e,n){const r=tc["zh"===n?"zh-CN":n]??tc.en,i=ec(e),o=t.useRef(!1),[a,c]=t.useState(!1),[l,d]=t.useState(null),u="connected"===e.phase;return{commands:[{id:"resetModels",title:r.reset,meta:u?r.resetHint:r.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}),s=e=>r.done.replace("{ok}",String(e.updated)).replace("{failed}",String(e.failed));n(r.working);try{const t=await e.applyToAllSessions({models:{claude:"",codex:""}},e=>n(`${r.working} ${s(e)}`));n(s(t))}catch{n(r.error)}finally{o.current=!1,c(!1)}})()}},{id:"settings",title:r.settings,meta:"",keywords:"settings preferences 设置 設定",select:()=>s().openSettings?.()},{id:"left",title:r.left,meta:"",keywords:"left sidebar 左侧栏 左側欄",select:()=>e.setLeftSidebarCollapsed(e=>!e)},{id:"right",title:r.right,meta:"",keywords:"right sidebar 右侧栏 右側欄",select:i},...["files","terminal","browser"].map(t=>({id:t,title:r[t],meta:"",keywords:t,select:()=>e.setControlTabAndOpen(t)})),{id:"diff",title:r.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:r.commandHint}}(e,c(l().language));return t.useEffect(()=>{const e=e=>{d(e.detail?.commandMode?"> ":""),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(sc,{initialQuery:a,workspace:e,onSelect:r,onClose:()=>o(!1),commandState:u},a):null}function sc({workspace:e,onSelect:s,onClose:r,commandState:i,initialQuery:o}){const d=Ve(),[u,h]=t.useState(o),[m,f]=t.useState(0),p=u.startsWith(">"),[g,v]=t.useState([]),[y,w]=t.useState(!0),[b,S]=t.useState(!1),x=t.useRef(null),k=R(r,x),C=c(l().language),E="en"===C?{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"===C?{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 w(!1),void S(!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;v(e=>[...e,...r.sessions]),s=r.nextCursor}while(s);w(!1)})().catch(()=>{t||(S(!0),w(!1))}),()=>{t=!0}},[e.clientRef]);const j=new Map(g.map(e=>[e.sessionId,e]));for(const t of e.displaySessions)j.set(t.sessionId,{...j.get(t.sessionId),...t});const M=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,u.slice(1)):[...d.items.filter(e=>!e.emptyPlaceholder&&e.title.toLocaleLowerCase().includes(u.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?d.setCenter(t.id):(d.setRight(e=>({...e,[t.kind]:t.id})),e.setControlTabAndOpen(t.kind))}})),...[...j.values()].filter(e=>!e.archived&&function(e,t){const n=e.pullRequest,s=[a(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,u)).map(t=>({id:t.sessionId,title:a(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)}}))],A=Math.min(m,Math.max(0,M.length-1));t.useEffect(()=>{k.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:"nearest"})},[A,u]);const T=e=>{const t=M[e];t&&!t.disabled&&(t.keepOpen||r(),t.select())};return I.createPortal(n.jsx("div",{className:"quick-session-backdrop",onMouseDown:e=>{e.target===e.currentTarget&&r()},children:n.jsxs("div",{className:"quick-session-dialog",ref:k,role:"dialog","aria-modal":"true","aria-label":E.title,onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),T(A)),"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),f((A+("ArrowDown"===e.key?1:-1)+M.length)%Math.max(1,M.length))))},children:[n.jsx("input",{ref:x,role:"combobox","aria-label":E.title,"aria-expanded":"true","aria-controls":"quick-session-results","aria-activedescendant":M[A]?`quick-result-${A}`:void 0,placeholder:E.placeholder,value:u,onChange:e=>{h(e.target.value),f(0)}}),n.jsxs("div",{className:"quick-session-results",id:"quick-session-results",role:"listbox","aria-label":E.title,children:[M.map((e,t)=>n.jsxs("button",{id:`quick-result-${t}`,type:"button",role:"option",tabIndex:-1,"aria-selected":t===A,"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)),!M.length&&(p||!y)&&n.jsx("p",{children:E.empty})]}),n.jsx("footer",{"aria-live":"polite",children:p?i.status||i.hint:b?E.error:y?E.loading:E.hint})]})}),document.body)}function rc({activeSessionId:e,activeSession:s,cwd:r,directoryPath:i,visible:o,t:a}){const[c,l]=t.useState(o);t.useEffect(()=>{o&&l(!0)},[o]);const d=e?s?.sessionId===e?s.cwd:void 0:r===mn?i:r;return c&&d?n.jsxs("div",{hidden:!o,className:"terminal-tab-content",children:[n.jsx(Bi,{location:"right",kind:"terminal",t:a,cwd:d}),n.jsx(Wi,{location:"right",kind:"terminal"})]}):null}function ic(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 oc(e){return e?"success":"warning"}function ac(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function cc(e,t){if(!e)return t.quotaNotProvided;const n=new Date(e);if(!Number.isFinite(n.getTime()))return t.quotaNotProvided;const s="浏览器"===t.browser?"zh-CN":"瀏覽器"===t.browser?"zh-TW":"en-US";return n.toLocaleString(s,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"short"})}function lc({limits:e,agent:t="codex",failed:s,connected:r,t:i}){return n.jsxs(n.Fragment,{children:[!r&&n.jsx("p",{className:"quota-details-warning",children:i.latencyDisconnected}),[t].map(t=>{const r=e[t],o=r?.limits,a=[[i.quotaFiveHour,o?.fiveHour],[i.quotaWeekly,o?.weekly],["Opus",o?.weeklyOpus],["Sonnet",o?.weeklySonnet],...(o?.additional??[]).flatMap(e=>[[`${e.name} · ${i.quotaFiveHour}`,e.primary],[`${e.name} · ${i.quotaWeekly}`,e.secondary]])];return n.jsxs("section",{children:[n.jsx("strong",{children:"codex"===t?"Codex":"Claude"}),"codex"===t&&n.jsxs("div",{className:"quota-details-account",children:[n.jsx("span",{children:i.quotaAccount}),n.jsx("b",{children:r?.account?.email||("apiKey"===r?.account?.type?"API Key":i.quotaAccountUnavailable)})]}),n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:i.quotaPlan}),n.jsx("b",{children:r?.account?.planType||o?.planType||i.quotaNotProvided})]}),s[t]&&n.jsx("p",{className:"quota-details-warning",children:i.quotaUpdateFailed}),!o&&n.jsx("p",{children:i.quotaUnavailable}),a.filter(([,e])=>e&&Number.isFinite(e.usedPercent)).map(([e,t],s)=>{const r=Math.round(Math.max(0,Math.min(100,100-t.usedPercent)));return n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:e}),n.jsxs("b",{children:[i.quotaRemaining," ",r,"%"]})]}),n.jsx("meter",{min:0,max:100,value:r,"aria-label":e}),n.jsxs("small",{children:[i.quotaReset," · ",cc(t.resetsAt,i)]})]},`${e}-${s}`)}),"codex"===t&&n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:i.quotaResetCards}),n.jsx("b",{children:r?.resetCredits?`${i.quotaCardsAvailable} ${r.resetCredits.availableCount}`:i.quotaNotProvided})]}),r?.resetCredits?.cards.map((e,t)=>n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:e.title}),n.jsx("span",{children:"available"===e.status?i.quotaCardsAvailable:e.status})]}),n.jsxs("small",{children:[i.quotaCardExpires," · ",cc(e.expiresAt,i)]})]},t))]}),o?.fetchedAt?n.jsxs("small",{children:[i.quotaUpdated," · ",cc(o.fetchedAt,i)]}):null]},t)})]})}function dc({connected:e,latencyMs:s,limits:r,t:i,failed:o={},loading:a=!1,onRetry:c}){const l=t.useId(),d=t.useRef(null),u=t.useRef(null),[h,m]=t.useState(null);t.useEffect(()=>{if(!h)return;const e=e=>{e.target instanceof Node&&!d.current?.contains(e.target)&&!u.current?.contains(e.target)&&m(null)},t=e=>{"Escape"===e.key&&(m(null),d.current?.focus())},n=()=>m(null);return document.addEventListener("pointerdown",e),document.addEventListener("focusin",e),document.addEventListener("keydown",t),window.addEventListener("resize",n),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("focusin",e),document.removeEventListener("keydown",t),window.removeEventListener("resize",n)}},[Boolean(h)]);const f=function(e){const t=[],n=ic(e.codex),s=ic(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}),[p,g]=t.useState(0);t.useEffect(()=>{if(f.length<2||h)return;const e=setInterval(()=>g(e=>(e+1)%f.length),4e3);return()=>clearInterval(e)},[f.length,Boolean(h)]);const v=f[p%f.length],y=v?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())}`}(v.resetsAt):null,w=v?`${v.label} ${v.availablePercent}%`:"",b=!!v&&o[v.agent],S=b?i.quotaUpdateFailed:v?"":a?i.loading:i.quotaUnavailable,x=`${i.remainingQuota}: ${w||S}${b?` · ${S}`:""} · ${y?i.quotaResetsAt.replace("{time}",y):i.quotaResetUnavailable}${e?"":` · ${i.latencyDisconnected}`}`,k=e?null===s?i.latencyMeasuring:`${s} ms`:i.latencyDisconnected;return n.jsxs("div",{className:"connection-indicators",children:[(v||c)&&n.jsxs("span",{children:[n.jsxs("button",{ref:d,type:"button",className:"connection-quota",onClick:()=>{h?m(null):((()=>{const e=d.current?.getBoundingClientRect();e&&m({left:Math.max(12,Math.min(e.left,innerWidth-352)),bottom:innerHeight-e.top+8,maxHeight:Math.max(80,e.top-24)})})(),e&&!a&&c?.())},"aria-haspopup":"dialog","aria-expanded":Boolean(h),"aria-controls":h?l:void 0,"aria-label":`${x}${c?` · ${i.retry}`:""}`,"aria-busy":a,children:[n.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${b||!v?"warning":oc(e)})`}}),n.jsxs("span",{className:"connection-quota-text",children:[w||S,b?" ↻":""]})]}),h&&I.createPortal(n.jsx("div",{id:l,ref:u,role:"dialog","aria-label":i.remainingQuota,className:"quota-details",style:h,children:n.jsx(lc,{agent:v?.agent,limits:r,failed:o,connected:e,t:i})}),document.body)]}),n.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${ac(e,s)})`},"aria-label":`${i.connectionLatency}: ${k}`,children:[n.jsx(N,{size:11,"aria-hidden":"true"}),n.jsx("span",{className:"connection-latency-text",children:k})]})]})}function uc({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({}),[m,f]=t.useState(!1),p=t.useRef(()=>{});return t.useEffect(()=>{h({}),d({})},[i?.daemonId]),t.useEffect(()=>{const e=r.current;if(c(null),f(!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),f(!0),lr(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||e?.account)&&d(t=>{const s=t[n],r=e.account&&s?.account&&e.account.type===s.account.type&&e.account.email===s.account.email;return{...t,[n]:e.limits?e:{...e,limits:r?s.limits:null}}});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&&f(i.size>0)}))},m=()=>{u("codex"),u("claude")};return p.current=()=>{u("codex",!0),u("claude",!0)},m(),window.addEventListener("online",m),window.addEventListener("focus",m),()=>{t=!1,p.current=()=>{},n();for(const e of o.values())clearTimeout(e);window.removeEventListener("online",m),window.removeEventListener("focus",m)}},[s,r,i?.daemonId]),n.jsx(dc,{connected:"connected"===s,latencyMs:a,limits:l,failed:u,loading:m,onRetry:()=>p.current(),t:o})}function hc({value:e,t,showSession:s=!0,onChange:r}){const i=[...s?[{tab:"session",label:t.session,Icon:Re}]:[],{tab:"files",label:t.files,Icon:X},{tab:"terminal",label:t.terminal,Icon:Ee},{tab:"browser",label:t.browser,Icon:se}];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 mc(){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?I.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 fc({chinese:e}){const r=Jr("mod+n").replace(/N$/,""),[o,a]=t.useState(Yr),[c,l]=t.useState(null),[d,u]=t.useState(""),h=e=>{!function(e){i().setItem(Xr,JSON.stringify(e)),window.dispatchEvent(new Event(Br))}(e),a(e),u("")};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 取消,退格键清除。新建标签会沿用当前终端或浏览器;右侧栏隐藏时不新建标签。":"Session switching is unassigned by default; use ↑ / ↓ while the session list is focused. 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."}),Wr.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":c===t.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?t.zh:t.en}`,onClick:()=>{l(t.id),u("")},onBlur:()=>l(null),onKeyDown:n=>{if(c!==t.id)return;if(n.preventDefault(),n.stopPropagation(),"Escape"===n.key)return l(null),void u("");if("Backspace"===n.key||"Delete"===n.key)return h({...o,[t.id]:""}),void l(null);const r=Qr(n.nativeEvent);if(!r)return;const i=function(e,t,n){return"browser"===s().kind?"mod+w"===t?"reserved":Zr(e,t,{closeTab:"mod+alt+w",...n}):Zr(e,t,n)}(t.id,r,o);if(i){const t=Wr.find(e=>e.id===i);return void u("reserved"===i?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?t?.zh:t?.en}`)}h({...o,[t.id]:r}),l(null)},children:c===t.id?e?"按下快捷键…":"Press shortcut…":Jr(ei(t.id,o))||(e?"未设置":"Not set")})]},t.id)),d&&n.jsx("p",{role:"alert",children:d}),n.jsx("div",{className:"attention-actions",children:n.jsx("button",{type:"button",onClick:()=>{h({}),l(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),n.jsx("p",{className:"empty-copy",children:e?`${r}N 新建会话,${r}, 打开设置。关闭标签:${Jr(ei("closeTab",o))||"未设置"}。查找作用于当前聚焦的聊天、浏览器或终端;Enter / Shift+Enter 切换匹配,Esc 关闭查找。恢复关闭的标签也支持侧栏隐藏状态。`:`${r}N creates a session; ${r}, opens settings. Close tab: ${Jr(ei("closeTab",o))||"Not set"}. Find searches the focused chat, browser or terminal; Enter / Shift+Enter navigates matches and Escape closes find. Reopen closed tab also works when the sidebar is hidden.`})]})}function pc({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)}},[]),I.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(ii,{}),e,n.jsx(fc,{chinese:"Browser"!==s.browser})]})]}),document.body)}function gc({children:e,collapsed:r,t:i,value:o,showSession:a,onChange:c,onResize:l}){const d=Ki("right",e=>{"terminal"!==e&&"browser"!==e||c(e)}),u=s().toolbarTarget?.("controls"),[h,m]=t.useState(null),f=n.jsx("div",{className:"right-dock-toolbar",ref:m,children:n.jsx(hc,{value:o,t:i,showSession:a,onChange:c})});return"admin"===o&&"browser"===s().kind?n.jsx(pc,{t:i,onClose:()=>c("files"),children:e}):n.jsxs($i.Provider,{value:{element:h,kind:o},children:[n.jsx(mc,{}),u&&!r?I.createPortal(f,u):null,n.jsx("button",{"aria-label":i.resizeControlsSidebar,"aria-hidden":r,className:"resize-handle right-resize-handle",disabled:r,onPointerDown:l,title:i.resizeControlsSidebar,type:"button",children:n.jsx("span",{})}),n.jsx("div",{className:"workspace-control-sidebar-motion",inert:r,"aria-hidden":r,children:n.jsxs("aside",{tabIndex:-1,"aria-label":i.controls,className:"control-pane",...d,children:[!u&&n.jsx("div",{className:"control-pane-toolbar",children:f}),e]})})]})}function vc({path:e,label:t,zh:s,menu:r=!1}){const{copyText:i,feedback:o}=Ta(s?"已复制路径":"Path copied",s?"复制失败,请重试":"Copy failed. Please try again."),a=o?.message??t;return n.jsxs("button",{role:r?"menuitem":void 0,type:"button",title:a,"aria-label":a,onClick:()=>{i(e)},children:[o?"success"===o.tone?n.jsx(_,{}):n.jsx(De,{}):n.jsx(U,{}),r&&n.jsx("span",{role:o?"status":void 0,children:a})]})}function yc({file:e,daemonId:s,downloadLabel:r,copyPathLabel:i,onDownload:o}){const[a,d]=t.useState(!1),[u,h]=t.useState(!1),[m,f]=t.useState(!1),p=t.useRef(null),g=t.useRef(null),v=t.useId(),y=c(l().language),w="en"===y?"More file actions":"zh-TW"===y?"更多檔案操作":"更多文件操作",b="en"===y?"Download failed. Try again.":"zh-TW"===y?"下載失敗,請重試":"下载失败,请重试",S=()=>{d(!1),p.current?.focus()};return t.useLayoutEffect(()=>{if(!a)return;const e=g.current,t=()=>{const t=p.current.getBoundingClientRect(),n=e.getBoundingClientRect();e.style.left=`${Math.max(8,Math.min(t.right-n.width,innerWidth-n.width-8))}px`,e.style.top=`${Math.max(8,Math.min(t.bottom+6,innerHeight-n.height-8))}px`};t(),e.querySelector("button:not(:disabled)")?.focus();const n=t=>{e.contains(t.target)||p.current?.contains(t.target)||d(!1)},s=new ResizeObserver(t);return s.observe(e),document.addEventListener("pointerdown",n),document.addEventListener("focusin",n),window.addEventListener("resize",t),document.addEventListener("scroll",t,!0),()=>{s.disconnect(),document.removeEventListener("pointerdown",n),document.removeEventListener("focusin",n),window.removeEventListener("resize",t),document.removeEventListener("scroll",t,!0)}},[a]),n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p,type:"button",title:w,"aria-label":w,"aria-haspopup":"menu","aria-expanded":a,"aria-controls":a?v:void 0,onClick:()=>d(!a),onKeyDown:e=>{"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),e.stopPropagation(),d(!0))},children:n.jsx(W,{"aria-hidden":"true"})}),a&&I.createPortal(n.jsxs("div",{ref:g,id:v,role:"menu","aria-label":w,className:"session-context-menu file-actions-menu",style:{maxWidth:"calc(100vw - 16px)",maxHeight:"calc(100vh - 16px)",overflowY:"auto"},onKeyDown:e=>{const t=Array.from(e.currentTarget.querySelectorAll("button:not(:disabled)")),n=t.indexOf(document.activeElement);["Escape","ArrowDown","ArrowUp","Home","End"].includes(e.key)&&(e.preventDefault(),e.stopPropagation()),"Escape"===e.key&&S(),"Tab"===e.key&&(e.preventDefault(),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:[n.jsx(vc,{path:e.path,label:i,zh:"en"!==y,menu:!0}),n.jsx(Xe,{path:e.path,cwd:e.cwd,daemonId:s,menu:!0,onComplete:S}),n.jsx(Ze,{file:e,daemonId:s,menu:!0,onComplete:S}),n.jsx("span",{className:"context-menu-separator"}),n.jsxs("button",{type:"button",role:"menuitem",disabled:u,onClick:async()=>{h(!0),f(!1);try{await o(),S()}catch{f(!0)}finally{h(!1)}},children:[n.jsx(j,{"aria-hidden":"true"}),m?b:r]})]}),document.body)]})}function wc({label:e="Loading…"}){return n.jsxs("div",{className:"markdown-editor-loading",role:"status",children:[n.jsx("span",{className:"markdown-editor-loading-mark","aria-hidden":"true",children:n.jsx("span",{className:"markdown-editor-loading-ring"})}),n.jsx("span",{children:e})]})}function bc(){const e=c(l().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:"无法加载编辑器,请切换到源码模式。"}}const Sc={zoom:"Image controls",openViewer:"Open image viewer",zoomIn:"Zoom in",zoomOut:"Zoom out",resetZoom:"Reset to fit",actualSize:"Actual size (1:1)",rotateLeft:"Rotate left",rotateRight:"Rotate right",flipHorizontal:"Flip horizontally",flipVertical:"Flip vertically",unavailable:"Image unavailable",copyFailed:"Failed to copy image"},xc={zoom:"图片操作",openViewer:"打开图片查看器",zoomIn:"放大",zoomOut:"缩小",resetZoom:"重置为适应窗口",actualSize:"原始尺寸(1:1)",rotateLeft:"向左旋转",rotateRight:"向右旋转",flipHorizontal:"水平翻转",flipVertical:"垂直翻转",unavailable:"无法加载图片",copyFailed:"复制图片失败"},Ic={zoom:"圖片操作",openViewer:"開啟圖片檢視器",zoomIn:"放大",zoomOut:"縮小",resetZoom:"重設為適應視窗",actualSize:"原始尺寸(1:1)",rotateLeft:"向左旋轉",rotateRight:"向右旋轉",flipHorizontal:"水平翻轉",flipVertical:"垂直翻轉",unavailable:"無法載入圖片",copyFailed:"複製圖片失敗"};function kc(e="en"){return/zh[-_](TW|HK|Hant)/i.test(e)?Ic:e.startsWith("zh")?xc:Sc}const Cc={actual:!1,scale:1,offset:{x:0,y:0},rotation:0,flip:{x:1,y:1}};function Rc(e){return n.jsx(Ec,{...e},e.src)}function Ec({src:e,alt:s,labels:r=kc(),imageClassName:i="",onError:o,keyboardRoot:a,toolbarStart:c,toolbarEnd:l}){const d=t.useRef(null),u=t.useRef(null),h=t.useRef(null),[m,f]=t.useState(!1),[p,g]=t.useState(!1),[v,y]=t.useState({width:0,height:0}),[w,b]=t.useState({width:0,height:0}),S=function(e,n){const[s,r]=t.useState(Cc),i=s.rotation%180!=0,o=e.width&&e.height&&n.width&&n.height?Math.min(n.width/(i?e.height:e.width),n.height/(i?e.width:e.height)):1,a=Math.min(.1,1/o),c=Math.max(8,1/o),l=t.useCallback(()=>r(Cc),[]),d=t.useCallback((e,t={x:0,y:0})=>{r(n=>{const s=n.actual?1/o:n.scale,r=Math.min(c,Math.max(a,s*e)),i=r/s;return{...n,actual:!1,scale:r,offset:{x:t.x-(t.x-n.offset.x)*i,y:t.y-(t.y-n.offset.y)*i}}})},[c,a,o]),u=t.useCallback(()=>r(e=>({...e,actual:!0,scale:1/o,offset:{x:0,y:0}})),[o]);return{...s,scale:s.actual?1/o:s.scale,fit:o,min:a,max:c,reset:l,zoom:d,actualSize:u,rotate:e=>r(t=>({...t,rotation:(t.rotation+e+360)%360,offset:{x:0,y:0}})),toggleFlip:e=>r(t=>({...t,flip:{...t.flip,[e]:-t.flip[e]}})),pan:e=>r(t=>({...t,offset:e}))}}(v,w);t.useEffect(()=>{const e=u.current;if(!e)return;const t=new ResizeObserver(e=>{const t=e[0];t&&b({width:t.contentRect.width,height:t.contentRect.height})});return t.observe(e),()=>t.disconnect()},[]);const x=(e,t)=>{const n=u.current.getBoundingClientRect();return{x:e-n.left-n.width/2,y:t-n.top-n.height/2}};t.useEffect(()=>{const e=u.current;if(!e||!m)return;const t=t=>{t.preventDefault(),t.stopPropagation();const n=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientHeight:1);S.zoom(Math.exp(.002*-Math.max(-100,Math.min(100,n))),x(t.clientX,t.clientY))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[m,S.zoom]),t.useEffect(()=>{const e=a?.current??d.current;if(!e)return;const t=e=>{e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.target.closest('input,textarea,select,[contenteditable="true"]')||["+","=","-","_","0","1"].includes(e.key)&&(e.preventDefault(),e.stopPropagation(),"0"===e.key?S.reset():"1"===e.key?m&&S.actualSize():S.zoom("+"===e.key||"="===e.key?1.25:.8))};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[a,m,S.zoom,S.reset,S.actualSize]);const I=(e,t,s,r=!m,i,o)=>n.jsx("button",{type:"button",title:e,"aria-label":e,"aria-pressed":i,disabled:r,onClick:s,"data-testid":o,children:t});return n.jsxs("div",{className:"lifeos-image-canvas",role:"region",ref:d,tabIndex:0,"aria-label":s||r.zoom,children:[n.jsx("div",{className:"lifeos-image-viewport",ref:u,onPointerDown:e=>{m&&0===e.button&&(d.current?.focus({preventScroll:!0}),h.current={pointerId:e.pointerId,x:e.clientX,y:e.clientY,left:S.offset.x,top:S.offset.y},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{const t=h.current;t?.pointerId===e.pointerId&&S.pan({x:t.left+e.clientX-t.x,y:t.top+e.clientY-t.y})},onPointerUp:e=>{h.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onLostPointerCapture:()=>{h.current=null},onPointerCancel:()=>{h.current=null},onDoubleClick:e=>{m&&(S.scale>1?S.reset():S.zoom(2.5/S.scale,x(e.clientX,e.clientY)))},children:p?n.jsx("p",{role:"status",children:r.unavailable}):n.jsx("img",{className:i,src:e,alt:s,draggable:!1,onLoad:e=>{y({width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight}),f(!0)},onError:()=>{f(!1),g(!0),o?.()},style:{width:v.width?v.width*S.fit:void 0,height:v.height?v.height*S.fit:void 0,transform:`translate(${S.offset.x}px, ${S.offset.y}px) scale(${S.scale}) scale(${S.flip.x}, ${S.flip.y}) rotate(${S.rotation}deg)`}})}),n.jsxs("div",{className:"lifeos-image-toolbar",role:"toolbar","aria-label":r.zoom,children:[c,I(r.zoomOut,n.jsx(ue,{}),()=>S.zoom(.8),!m||S.scale<=S.min,void 0,"image-viewer-zoom-out"),n.jsxs("output",{className:"lifeos-image-zoom-value","aria-label":r.zoom,children:[Math.round(100*S.scale),"%"]}),I(r.zoomIn,n.jsx(ye,{}),()=>S.zoom(1.25),!m||S.scale>=S.max,void 0,"image-viewer-zoom-in"),n.jsx("span",{className:"lifeos-image-divider","aria-hidden":"true"}),I(r.rotateLeft,n.jsx(be,{}),()=>S.rotate(-90)),I(r.rotateRight,n.jsx(Se,{}),()=>S.rotate(90)),I(r.flipHorizontal,n.jsx(J,{}),()=>S.toggleFlip("x"),!m,-1===S.flip.x),I(r.flipVertical,n.jsx(Z,{}),()=>S.toggleFlip("y"),!m,-1===S.flip.y),n.jsx("span",{className:"lifeos-image-divider","aria-hidden":"true"}),I(r.resetZoom,n.jsx(ce,{}),S.reset,!m,void 0,"image-viewer-fit-window"),I(r.actualSize,"1:1",S.actualSize,!m,void 0,"image-viewer-actual-size"),l]})]})}function jc({className:e,...t}){return n.jsx(Rc,{...t,imageClassName:e,labels:kc(c(l().language))})}function Mc(e,t,n){const s=e.trim();if(s&&!/^(?:#|\/\/)/.test(s)&&(!/^[a-z][\w+.-]*:/i.test(s)||/^[a-z]:[\\/]/i.test(s)))try{return br(decodeURIComponent(s.split(/[?#]/)[0]),An(br(t,n))??n)}catch{return}}function Ac({file:e}){const{path:r,cwd:i,text:o}=e,a=bt(),c=a?.pairToken,l=t.useRef(null),[d,u]=t.useState();t.useEffect(()=>{const e=new AbortController;let t=0;return async function(e,t,n,s){const r=(new DOMParser).parseFromString(e,"text/html"),i=Array.from(r.querySelectorAll("img[src]")),o=new Map,a=Object.create(null);let c=0;return await Promise.all(Array.from({length:Math.min(4,i.length)},async()=>{for(;c<i.length;){const e=i[c++],r=Mc(e.getAttribute("src")||"",t,n);if(r)try{let t=o.get(r);t||(t=s(r),o.set(r,t));const n=e.getAttribute("src");a[n]=await t,e.setAttribute("src",a[n])}catch{}}})),{html:`<!doctype html>${r.documentElement.outerHTML}`,images:a}}(o,r,i,async n=>{if(!c||e.signal.aborted)throw new Error("Preview unavailable");const s=await fetch(Nn(n,i),{headers:{authorization:`Bearer ${c}`},signal:e.signal});if(!s.ok||!s.headers.get("content-type")?.startsWith("image/"))throw new Error("Image unavailable");const r=await s.blob();if(t+=r.size,e.signal.aborted||t>33554432)throw new Error("Preview image limit");return function(e){return new Promise((t,n)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=()=>n(s.error),s.readAsDataURL(e)})}(r)}).then(({html:t,images:n})=>{e.signal.aborted||u({path:r,cwd:i,text:o,token:c,html:Cr(t),images:n})}),()=>e.abort()},[r,i,o,c]);const h=d?.path===r&&d.cwd===i&&d.text===o&&d.token===c?d:void 0,m=e.dirty?void 0:s().htmlPreviewUrl?.(r,i),[f,p]=t.useState(),[g,v]=t.useState();t.useEffect(()=>{if(m||!h)return;let e,t=!1;const n=()=>{e&&fetch(e,{method:"DELETE"}).catch(()=>{})};return fetch("/web/html-draft-preview",{method:"POST",headers:{"content-type":"text/html; charset=utf-8"},body:h.html}).then(async s=>{if(!s.ok)throw new Error("Preview unavailable");const r=await s.json();if("string"!=typeof r.url||!r.url.startsWith("/web/html-draft-preview?id="))throw new Error("Invalid preview");e=r.url,t?n():p({html:h.html,url:r.url})}).catch(()=>{t||v(h.html)}),()=>{t=!0,n()}},[h,m]);const y=m??(f?.html===h?.html?f?.url:void 0),w=()=>{h&&m&&l.current?.contentWindow?.postMessage({type:"vibelet:preview-images",images:h.images},"*")};return t.useEffect(w,[h,m]),!m&&h&&g===h.html?n.jsx("p",{role:"alert",className:"empty-copy",children:or().mediaError}):n.jsx("iframe",{ref:l,className:"remote-document-preview",sandbox:"allow-scripts",title:or().htmlPreview,src:y,srcDoc:y?void 0:"",onLoad:w},y??"preparing")}function Tc({file:e}){const[r,i]=t.useState(!1),o=R(()=>i(!1),void 0,r),a=or(),d=c(l().language),u="en"===d?"Close":"zh-TW"===d?"關閉":"关闭",h=s().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(Q,{"aria-hidden":"true"}),a.pdfPreview]}),r&&I.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":a.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[n.jsx(Mo,{title:e.path.split("/").pop(),actions:n.jsx("button",{className:"icon-button",type:"button","aria-label":u,title:u,onClick:()=>i(!1),children:n.jsx(De,{"aria-hidden":"true"})})}),n.jsx("iframe",{title:a.pdfPreview,src:`${h}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function Nc({file:e,daemonId:r}){const[i,o]=t.useState(!1),[a,d]=t.useState(!1),u=s(),h=c(l().language),m="darwin"===u.platform,f="en"===h?["This file format is not supported","Open with default app",m?"Show in Finder":"Show in file manager","Unable to open the file. Please try again.","Download"]:"zh-TW"===h?["不支援此檔案格式","使用系統預設程式開啟",m?"在 Finder 中顯示":"在檔案管理員中顯示","無法開啟檔案,請重試。","下載"]:["不支持此文件格式","使用系统默认应用打开",m?"在 Finder 中显示":"在文件管理器中显示","无法打开文件,请重试。","下载"],p=async t=>{if(r&&!i){o(!0),d(!1);try{await t({path:e.path,cwd:e.cwd,daemonId:r})}catch{d(!0)}finally{o(!1)}}};return n.jsxs("div",{className:"unsupported-file-preview",children:[n.jsx(V,{className:"unsupported-file-icon","aria-hidden":"true"}),n.jsx("h2",{children:f[0]}),n.jsx("p",{className:"unsupported-file-name",children:e.path.split(/[\\/]/).pop()}),n.jsxs("div",{className:"unsupported-file-actions",children:[u.openFile&&r&&n.jsxs("button",{className:"primary-button",type:"button",disabled:i||e.dirty,onClick:()=>{p(u.openFile)},children:[n.jsx(E,{"aria-hidden":"true"}),f[1]]}),u.revealFile&&r&&n.jsxs("button",{className:"icon-text-button",type:"button",disabled:i,onClick:()=>{p(u.revealFile)},children:[n.jsx(X,{"aria-hidden":"true"}),f[2]]}),"browser"===u.kind&&e.objectUrl&&n.jsx("a",{className:"icon-text-button",href:e.objectUrl,download:e.path.split(/[\\/]/).pop(),children:f[4]})]}),a&&n.jsx("p",{role:"alert",children:f[3]})]})}function Pc({file:e,daemonId:s,onRetry:r,playback:i}){const o=function(e){return t.useCallback(t=>{if(!t||!e)return;let n=!1;const s=()=>{n||(t.currentTime=Number.isFinite(t.duration)?Math.min(e.time,t.duration):e.time,t.playbackRate=e.rate,t.volume=e.volume,t.muted=e.muted,n=!0,e.playing&&t.play().catch(()=>{}))};return t.addEventListener("loadedmetadata",s),t.readyState>=1&&s(),()=>{n&&(e.time=t.currentTime,e.playing=!t.paused&&!t.ended,e.rate=t.playbackRate,e.volume=t.volume,e.muted=t.muted),t.removeEventListener("loadedmetadata",s),t.pause()}},[e])}(i),a=or();if(e.loading||e.error){const t=w[c(l().language)];return n.jsx(jo,{loading:e.loading,className:"remote-file-status",children:e.loading?n.jsxs(n.Fragment,{children:[n.jsx(oe,{className:"remote-file-spinner","aria-hidden":"true"}),n.jsx("p",{children:t.loading})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{children:e.error}),r&&n.jsx("button",{type:"button",className:"icon-text-button",onClick:r,children:t.retry})]})})}const d=kr(e.path,e.contentType,"text"===e.kind);if("unsupported"===d)return n.jsx(Nc,{file:e,daemonId:s});if("html"===d)return n.jsx(Ac,{file:e});const u=e.mediaUrl||e.objectUrl;return u?"pdf"===d?n.jsx(Tc,{file:e}):n.jsx(Ao,{source:u,errorLabel:a.mediaError,statusClassName:"empty-copy",className:"image"===d?"remote-media-viewer remote-image-viewer":"video"===d?"remote-media-viewer remote-video-viewer":"audio"===d?"remote-media-viewer remote-audio-viewer":void 0,children:t=>"image"===d?n.jsx(jc,{className:"remote-image",src:u,alt:e.path,onError:t}):"video"===d||"audio"===d?n.jsx(No,{mediaRef:o,kind:d,src:u,label:"audio"===d?a.audioPreview:a.videoPreview,preload:"metadata",onError:t}):n.jsx("p",{className:"empty-copy",children:a.mediaError})}):null}function Dc(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function Lc(e,t){return An(br(e,t))??t??"."}function Fc(e,t,n){if(!e)return{path:br(t,n),cwd:n??Lc(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??Lc(t,n):Lc(t,n);return{path:Dc(e||t),cwd:s}}function Oc(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 qc=new Map;function _c(e,t,n){for(const[s,r]of qc)Date.now()-r.time>1e4&&qc.delete(s);n&&qc.set(br(e,t),{hash:n,time:Date.now()})}function $c(e,t){const n=br(e,t),s=qc.get(n);return qc.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const zc=t.lazy(()=>C(()=>import("./MarkdownModePanel-DMtxlov8.js"),__vite__mapDeps([45,1,2,46])).then(e=>({default:e.MarkdownModePanel}))),Hc=t.lazy(()=>C(()=>import("./file-editor-FileCodeEditor-C1eB-N6w.js"),__vite__mapDeps([47,1,2,48,49,50])).then(e=>({default:e.FileCodeEditor}))),Bc=t.lazy(()=>C(()=>import("./file-editor-ObsidianCodeEditor-CbYkHjhQ.js"),__vite__mapDeps([51,1,2,47,48,49,50,52,53,54,55,56,57,58,30,40,29,10,17,59,43,60,61,62])).then(e=>({default:e.ObsidianCodeEditor}))),Uc=t.lazy(()=>C(()=>import("./file-editor-ObsidianFileEditor-BcW1PoxX.js"),__vite__mapDeps([63,1,2,58,30,40,48,49,29,10,17,59,64,53,42,65,66,67,68])).then(e=>({default:e.ObsidianFileEditor})));function Wc({file:e,client:s,onOpenRemoteFile:r,onTextChange:i}){const o=function(e,n){return t.useMemo(()=>{let t;return async(s,r)=>{const i=Fc(s,r,n),o={path:br(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,i=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i||e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase().endsWith(`/${i}`)||e.basename.toLowerCase()===i||e.aliases?.includes(i)),c=br(Dc(s),Lc(r,n)),l=a.find(e=>br(e.relPath,n)===c)??a.find(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i)??a.sort((e,t)=>e.relPath.localeCompare(t.relPath))[0];return l?{path:br(l.relPath,n),cwd:n}:o}catch{return t=void 0,o}}},[e,n])}(s,e.cwd),a=function(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}(e.path),d=bc(),[u,h]=t.useState("preview"),m="html"===kr(e.path,e.contentType,!0),f="en"!==c(l().language);return n.jsxs(n.Fragment,{children:[m&&n.jsxs("div",{className:"segmented editor-mode-tabs",children:[n.jsx("button",{type:"button",className:"edit"===u?"selected":"",onClick:()=>h("edit"),children:f?"编辑":"Edit"}),n.jsx("button",{type:"button",className:"preview"===u?"selected":"",onClick:()=>h("preview"),children:f?"预览":"Preview"})]}),a?n.jsx(t.Suspense,{fallback:n.jsx(wc,{label:d.loading}),children:n.jsx(zc,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:d,loadingText:d.loading,renderVisual:t=>n.jsx(Uc,{client:s,resolveFile:o,path:e.path,cwd:e.cwd,text:e.text,readOnly:t,onChange:i,onOpenFile:r}),renderCode:t=>n.jsx(Bc,{client:s,cwd:e.cwd,path:e.path,resolveFile:o,onOpenFile:r,text:e.text,onChange:i,preview:t})})}):m&&"preview"===u?n.jsx(Pc,{file:e}):n.jsx(t.Suspense,{fallback:n.jsx("pre",{className:"remote-editor",children:e.text}),children:n.jsx(Hc,{path:e.path,text:e.text,onChange:i})})]})}const Kc=t.createContext(null);function Gc({workspace:e,children:r}){const i=Ve(),o=Be(e.pairing?.daemonId,e.activeSessionId),a=function(e){const{value:n,setForScope:s}=He(e,!1);return t.useEffect(()=>{const e=e=>{const t=e.detail;s(Be(t.daemonId,t.sessionId),t.removing)};return window.addEventListener(Oe,e),()=>window.removeEventListener(Oe,e)},[s]),n}(o),u=Ki("center"),{openFiles:h,setOpenFiles:m}=e,[p,g]=ze(o,null),[v,y]=ze(o,()=>[]),[w]=ze(o,()=>new Map);t.useEffect(()=>{for(const e of w.keys())h[e]||w.delete(e)},[h,w]);const[b,S]=t.useState(null),x=t.useRef(null),I=t.useRef({files:h,remoteFile:e.remoteFile,scopeKey:o});I.current={files:h,remoteFile:e.remoteFile,scopeKey:o};const k=t.useRef(new Map);t.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of[...k.current]){const e=$e(n,t);e!==n&&(k.current.delete(n),null!==e&&k.current.set(e,s))}};return window.addEventListener(Le,e),()=>window.removeEventListener(Le,e)},[]);const C="en"!==c(l().language);t.useEffect(()=>{const t=e.remoteFile?Rr(e.remoteFile):null;if(k.current.get(o)!==t&&y(e=>[...e.filter(e=>e!==t),t]),!e.remoteFile)return k.current.set(o,null),void g(null);k.current.get(o)!==t&&(g(t),i.setCenter(null)),k.current.set(o,t)},[e.remoteFile,o]);const R=t=>{i.setCenter(null),e.setRemoteFile(h[t]),g(t),rr({file:h[t].path,cwd:h[t].cwd},{replace:!0})},E=()=>{y(e=>[...e.filter(e=>null!==e),null]),g(null),e.setRemoteFile(null),i.setCenter(null),k.current.set(o,null),rr({file:void 0},{replace:!0})},j=async e=>{const t=h[e];if(!t)return;const n=d();if(t.dirty&&!(await f({title:n.discard,message:e,confirmLabel:n.discardAction,danger:!0})))return;if(I.current.scopeKey!==o||I.current.files[e]?.text!==t.text)return;m(t=>{const n={...t};return delete n[e],n});const s=v.filter(t=>t!==e&&(null===t||I.current.files[t]));if(y(s),I.current.remoteFile&&Rr(I.current.remoteFile)===e){const e=s.at(-1);e?R(e):E();const n=document.activeElement;requestAnimationFrame(()=>{if(I.current.scopeKey!==o)return;if(document.activeElement!==n&&document.activeElement!==document.body)return;const s=x.current,r=s?.closest("#vibelet-main-content"),i=s?.querySelector('[role="tab"][aria-selected="true"]'),a=[...r?.querySelectorAll('.files-explorer [role="treeitem"][data-path]')??[]].filter(e=>e.getClientRects().length>0&&!e.closest("[hidden], [inert]")),c=a.find(e=>br(e.dataset.path??"",t.cwd)===br(t.path,t.cwd)),l=a.find(e=>0===e.tabIndex);(e?i??r:c??l??i??r)?.focus()})}};t.useEffect(()=>{const e=e=>{const t=e.detail;if(!["closeTab","nextTab","previousTab"].includes(t))return;if("closeTab"===t)return void(i.center?i.close(i.center):p&&j(p));const n=[null,...Object.keys(h),...i.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(i.center||p),r=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];r?h[r]?R(r):i.setCenter(r):E()};return window.addEventListener(Ur,e),()=>window.removeEventListener(Ur,e)},[h,p,i]);const M=p?h[p]:null;let A;const T=M?.mediaUrl||M?.objectUrl;T&&p&&(A=w.get(p),A&&A.source===T||(A={source:T,time:0,playing:!1,rate:1,volume:1,muted:!1},w.set(p,A))),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"!==Qr(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)},[])}(!!M&&"text"===M.kind&&!i.center&&!a,e.busy,e.saveRemoteFile);const N=s().toolbarTarget?.("conversation"),P=M&&!i.center&&n.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":C?"文件操作":"File actions",children:["text"===M.kind&&n.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!M.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:n.jsx(xe,{})}),n.jsx(yc,{file:M,daemonId:e.pairing?.daemonId,downloadLabel:e.t.download,copyPathLabel:e.t.copyPath,onDownload:e.downloadRemoteFile},M.path)]});return n.jsx(Kc.Provider,{value:b,children:n.jsxs("div",{className:"workspace-documents",...u,ref:x,children:[!N&&n.jsx("div",{className:"chat-header document-conversation-header",ref:S}),(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":C?"工作区标签页":"Workspace tabs",children:[n.jsx("button",{role:"tab","aria-selected":!p&&!i.center,onClick:E,type:"button",children:e.t.chat}),Object.entries(h).map(([t,s])=>n.jsxs("div",{className:"document-tab","data-active":!i.center&&p===t,children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":!i.center&&p===t,title:Rr(s),onClick:()=>R(t),onDoubleClick:()=>{/^(?:https?:\/\/|data:|blob:)/i.test(s.path)},children:[n.jsx(Q,{}),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:()=>j(t),children:n.jsx(De,{})})]},t)),n.jsx(Bi,{location:"center",t:e.t})]}),P]}),n.jsx("div",{hidden:!!p||!!i.center,className:"document-chat",children:r}),n.jsx("div",{hidden:!i.center,className:"dock-center-content",children:n.jsx(Wi,{location:"center"})}),M&&!i.center&&n.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":wn(M.path),inert:a,"aria-busy":a,children:[e.errorText&&!e.remoteFileConflict&&n.jsx("div",{role:"alert",className:"inline-notice warning",children:n.jsx("span",{children:e.errorText})}),"text"===M.kind?n.jsx(Wc,{client:e.clientRef?.current,file:M,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},M.path):n.jsx(Pc,{playback:A,file:M,daemonId:e.pairing?.daemonId,onRetry:()=>{e.openRemoteFile(M.path,M.cwd,{updateRoute:!0})}},JSON.stringify([o,p])),e.remoteFileConflict&&n.jsxs("div",{role:"alert",className:"inline-notice warning",children:[n.jsx("span",{children:e.t.remoteFileConflict(M.path)}),n.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await f({message:e.t.confirmOverwrite(wn(t.path)),danger:!0})&&I.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}function Vc(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(" · ")}function Qc(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function Jc(e,t,n){return{quickReplies:M(e.quickReplies,e.quickReplyUsageCounts),onQuickRepliesChange:e=>t(t=>({...t,quickReplies:[...t.quickReplies.filter(t=>e.includes(t)),...e.filter(e=>!t.quickReplies.includes(e))],quickReplyUsageCounts:A(t.quickReplyUsageCounts,e)})),onSendQuickReply:(e,s)=>(t(e=>{const t=A(e.quickReplyUsageCounts,e.quickReplies),n=Object.hasOwn(t,s)?t[s]:0;return{...e,quickReplyUsageCounts:{...t,[s]:Math.min(Number.MAX_SAFE_INTEGER,n+1)}}}),n(e))}}const Zc=t.lazy(()=>C(()=>import("./GlobalPendingDialog-BHvNAgCA.js"),__vite__mapDeps([69,1,2,27,13,32])));function Xc({workspace:e}){const r=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,n=!0)=>{n&&i(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t),e.completionAttention?.acknowledgeOpened(t);const r=e.displaySessions.find(e=>e.sessionId===t);if(!e.pendingApprovals[t]&&!e.pendingQuestions[t]&&!r?.runtime.needsAttention)return;s(e=>e+1);const o=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===o&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:n}}(e);!function(e,n){t.useEffect(()=>{const t=t=>{try{const[s,r]=JSON.parse(t.detail);e.pairing?.daemonId===s&&e.displaySessions.some(e=>e.sessionId===r)&&n(r,!1)}catch{}};return window.addEventListener("vibelet.dock.restore-session",t),()=>window.removeEventListener("vibelet.dock.restore-session",t)},[e.pairing?.daemonId,e.displaySessions,n])}(e,r.selectSession),function(e,n){const{pendingApprovals:r,pendingQuestions:i,displaySessions:o,pairing:c,t:l}=e,d=s(),u=t.useMemo(()=>{const e=new Set([...Object.keys(r),...Object.keys(i)]),t=c?[...e].map(e=>{const t=r[e],n=i[e],s=o.find(t=>t.sessionId===e);return{daemonId:c.daemonId,sessionId:e,title:s?a(s):e,detail:[t&&`${l.interactionWaitingApproval} · ${t.description||t.toolName}`,n&&`${l.interactionWaitingAnswer} · ${n.questions[0]?.question??""}`].filter(Boolean).join(" / "),count:Number(!!t)+Number(!!n)}}):[];return{sessions:t,label:l.pendingActionCount(t.reduce((e,t)=>e+t.count,0)),emptyLabel:l.noPendingActions}},[r,i,o,c,l]),h=JSON.stringify(u);t.useEffect(()=>{d.setPendingSessions?.(JSON.parse(h)).catch(()=>{})},[d,h]),t.useEffect(()=>()=>{d.setPendingSessions?.({sessions:[],label:"",emptyLabel:""}).catch(()=>{})},[d]);const m=t.useRef({state:u,selectSession:n});m.current={state:u,selectSession:n},t.useEffect(()=>d.subscribeCommand?.(e=>{if(e.startsWith("pending-session:"))try{const t=JSON.parse(e.slice(16));if(!m.current.state.sessions.some(e=>e.daemonId===t.daemonId&&e.sessionId===t.sessionId))return;m.current.selectSession(t.sessionId),window.dispatchEvent(new Event("vibelet.pending.open"))}catch{}}),[d])}(e,r.selectSession);const[i,o]=t.useState(!0),[c,l]=t.useState(!1);(function(e){const n=Ve(),r=ec(e),[i,o]=t.useState(Yr),a=t.useRef({workspace:e,dock:n,shortcuts:i,toggleRightSidebar:r});a.current={workspace:e,dock:n,shortcuts:i,toggleRightSidebar:r},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 r=e=>{n=t(e.target)},i=(e,r,i=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat)return;const o=Qr(e);if(!o&&!r)return;const{workspace:c,dock:l,shortcuts:d}=a.current,u=r??Wr.find(e=>ei(e.id,d)===o)?.id;if(("closeTab"===u||"mod+w"===o)&&"desktop"===s().kind&&!window.dispatchEvent(new Event(Ai,{cancelable:!0})))return e.preventDefault(),void e.stopPropagation();if(!u||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;if(["searchMessages","findNext","findPrevious"].includes(u)){let n=i instanceof Element?i.closest(".embedded-browser-panel, .embedded-terminal-panel"):null;if(!n&&!c.rightSidebarCollapsed&&t(i)&&"files"!==c.controlTab){const e=l.right["terminal"===c.controlTab?"terminal":"browser"];n=Array.from(document.querySelectorAll(".dock-surface")).find(t=>t.dataset.dockId===e&&!t.hidden)?.querySelector(".embedded-browser-panel, .embedded-terminal-panel")??null}if(n&&!n.closest(".dock-surface[hidden]"))return e.preventDefault(),e.stopPropagation(),void n.dispatchEvent(new CustomEvent("vibelet.panel.find",{detail:u}));if("searchMessages"!==u){const t=document.querySelector(".message-search-bar"),n=t?.querySelectorAll("button");return void(n?.length&&(e.preventDefault(),e.stopPropagation(),n["findPrevious"===u?0:1]?.click()))}}if("searchMessages"===u&&(t(i)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;if(function(e){return Hr.some(t=>t.id===e)}(u))return void window.dispatchEvent(new CustomEvent(zr,{detail:{command:u,event:e}}));const h="terminal"===c.controlTab?"terminal":"browser",m=l.items.find(e=>e.id===l.center),f=!c.rightSidebarCollapsed&&(t(i)||i===document.body&&n),p=!f&&m?m:l.items.find(e=>e.id===l.right[h]);if("browserAddress"===u||"browserCopyUrl"===u){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:u}))}switch(e.preventDefault(),e.stopPropagation(),u){case"commandMode":window.dispatchEvent(new CustomEvent("vibelet.quick-search",{detail:{commandMode:!0}}));break;case"previousSession":case"nextSession":window.dispatchEvent(new CustomEvent(Ur,{detail:u}));break;case"quickSearch":window.dispatchEvent(new Event("vibelet.quick-search"));break;case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":c.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.current.toggleRightSidebar();break;case"files":case"terminal":case"browser":c.setControlTabAndOpen(u);break;case"searchSessions":c.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const e="terminal"===p?.kind||"browser"===p?.kind?p.kind:h;l.add(e,c.t[e],c.cwd),c.setControlTabAndOpen(e);break}case"moveTab":p&&l.move(p.id,"center"===p.location?"right":"center");break;case"reopenTab":l.reopenClosed();break;case"diff":c.activeSession&&c.setDiffSessionId(c.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(f)if("closeTab"===u)"files"===c.controlTab||!p||p.emptyPlaceholder?c.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),l.close(p.id));else{const e=l.items.filter(e=>"right"===e.location&&e.kind===h);e.length&&l.setRight(t=>({...t,[h]:e[(Math.max(0,e.findIndex(e=>e.id===p?.id))+("nextTab"===u?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(Ur,{detail:u}))}},c=e=>i(e),l=s().subscribeCommand?.(e=>{"close-tab"===e&&i(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(Br,e),window.addEventListener("focusin",r,!0),window.addEventListener("pointerdown",r,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(Br,e),window.removeEventListener("focusin",r,!0),window.removeEventListener("pointerdown",r,!0),window.removeEventListener("keydown",c,!0)}},[])})(e),function(e,n){const s=t.useRef(null);t.useLayoutEffect(()=>{const t=s.current,n=t?.row;s.current=null,n?.dataset.sessionId===e&&(n?.isConnected?n.focus({preventScroll:!0}):t?.list?.focus({preventScroll:!0}))},[e]);const r=t.useRef({activeSessionId:e,selectSession:n});r.current={activeSessionId:e,selectSession:n},t.useEffect(()=>{let e=null;const t=()=>Array.from(document.querySelectorAll(".session-list .session-row")).filter(e=>e.dataset.sessionId&&!e.disabled&&!e.closest("[hidden]")),n=n=>{if(n instanceof MouseEvent&&(n.metaKey||n.ctrlKey||n.shiftKey||n.altKey))return;const s=n.target instanceof Element?n.target.closest(".session-list .session-row"):null;s&&(e={row:s,rows:t()})},i=(n,i)=>{if(document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden], .browser-settings-page')||Array.from(document.querySelectorAll('[role="menu"]')).some(e=>e.checkVisibility({visibilityProperty:!0})))return!1;const o=t();if(!o.length)return!1;const a=r.current.activeSessionId,c=e?.row.dataset.sessionId===a?e:null,l=c?o.indexOf(c.row):o.findIndex(e=>e.dataset.sessionId===a);let d;if(c&&l<0){for(let e=c.rows.indexOf(c.row)+n;e>=0&&e<c.rows.length;e+=n)if(o.includes(c.rows[e])){d=c.rows[e];break}if(!d)return!0}else d=o[l<0?n>0?0:o.length-1:Math.max(0,Math.min(o.length-1,l+n))];for(;d.dataset.sessionId===a;){const e=o.indexOf(d)+n;if(e<0||e>=o.length)break;d=o[e]}return e={row:d,rows:o},s.current=i&&d.dataset.sessionId!==a?{row:d,list:d.closest(".session-list")}:null,i&&d.focus({preventScroll:!0}),d.scrollIntoView({block:"nearest",inline:"nearest"}),d.dataset.sessionId!==a&&(r.current.activeSessionId=d.dataset.sessionId,r.current.selectSession(d.dataset.sessionId,!i)),!0},o=e=>{if(e.defaultPrevented||e.isComposing||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;if("ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=e.target;t instanceof Element&&t.closest(".session-list")&&!t.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')&&i("ArrowDown"===e.key?1:-1,!0)&&(e.preventDefault(),e.stopPropagation())},a=e=>{const t=e.detail;"previousSession"!==t&&"nextSession"!==t||i("nextSession"===t?1:-1,!1)};return document.addEventListener("click",n,!0),document.addEventListener("focusin",n),window.addEventListener("keydown",o),window.addEventListener(Ur,a),()=>{document.removeEventListener("click",n,!0),document.removeEventListener("focusin",n),window.removeEventListener("keydown",o),window.removeEventListener(Ur,a)}},[])}(e.activeSessionId,r.selectSession);const d=ec(e),[u,h]=function(e){const[n,r]=t.useState(null);return t.useEffect(()=>{const t=()=>r(t=>t??{cwd:e}),n=s().subscribeCommand?.(e=>{"new-session"===e&&t()}),i=e=>{"browser"!==s().kind||!Gr(e)||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",i),()=>{n?.(),window.removeEventListener("keydown",i)}},[e]),[n,r]}(e.cwd);t.useEffect(()=>{"browser"===e.controlTab&&o(!0)},[e.controlTab]),t.useEffect(()=>{("session"===e.controlTab||"desktop"===s().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 m=function({clientRef:e,pairing:n,phase:r}){const i="desktop"===s().kind&&"connected"===r?n:null,o=i?e.current:null,a=i?Bn(i,window.location):null,c=t.useRef(null),[l,d]=t.useState(null),u=l?.owner.client===o&&l.owner.healthUrl===a?l:null,h=u?.rows??[],m=u?.requests,f=h.some(e=>"updating"===e.phase),p=t.useCallback(async(e,t=!1)=>{const{controller:n,client:s}=e;if(e!==c.current||e.checking||e.starting.size||!s.isConnected)return;const r=e.revision;e.checking=!0,d(t=>({owner:e,rows:t?.owner===e?t.rows:[],requests:t?.owner===e?t.requests:{},busy:!0,error:!1}));try{if(!e.supported){const t=await fetch(e.healthUrl,{cache:"no-store",signal:AbortSignal.any([n.signal,AbortSignal.timeout(8e3)])});if(!t.ok||!0!==(await t.json()).agentUpdates)throw new Error("unsupported");if(n.signal.aborted)return;e.supported=!0}const i=await s.request({action:"agent.updates",id:s.makeId("agent-update"),refresh:t},{timeoutMs:25e3});if(!Array.isArray(i)||!i.length||!i.every(e=>("codex"===e?.agent||"claude"===e?.agent)&&"boolean"==typeof e.available))throw new Error("invalid agent update response");n.signal.aborted||e.revision!==r||d(n=>n?.owner===e?{...n,rows:i,requests:t?{}:n.requests}:n)}catch{n.signal.aborted||e.revision!==r||d(t=>t?.owner===e?{...t,error:!0}:t)}finally{e.checking=!1,n.signal.aborted||d(t=>t?.owner===e?{...t,busy:!1}:t)}},[]);return t.useEffect(()=>{if(!o||!a)return;const e={client:o,healthUrl:a,controller:new AbortController,supported:!1,checking:!1,confirming:!1,revision:0,starting:new Set};c.current=e,p(e);const t=()=>{p(e)};return window.addEventListener("focus",t),()=>{window.removeEventListener("focus",t),c.current=null,e.controller.abort()}},[o,a,p]),t.useEffect(()=>{const e=u?.owner;if(!f||!e)return;const t=window.setInterval(()=>{p(e)},2e3);return()=>window.clearInterval(t)},[u?.owner,f,p]),{rows:h,requests:m,busy:Boolean(u?.busy),error:Boolean(u?.error),updating:f,check:()=>{c.current&&p(c.current,!0)},update:async(e,t)=>{const n=u?.owner;if(!n||n!==c.current||n.confirming)return;let s;n.confirming=!0;try{s=await t()}finally{n.confirming=!1}s&&n===c.current&&n.client.isConnected&&await Promise.all(e.map(e=>async function(e,t){const{client:n}=e;if(!e.starting.has(t)){e.starting.add(t),e.revision+=1,d(n=>n?.owner===e?{...n,requests:{...n.requests,[t]:"pending"}}:n);try{const s=await n.request({action:"agent.update",id:n.makeId("agent-update"),agent:t},{timeoutMs:25e3});if(s?.agent!==t||"boolean"!=typeof s.available)throw new Error("invalid agent update response");d(n=>n?.owner===e?{...n,rows:n.rows.map(e=>e.agent===t?s:e),requests:{...n.requests,[t]:void 0}}:n)}catch{d(n=>n?.owner===e?{...n,requests:{...n.requests,[t]:"failed"}}:n)}finally{e.starting.delete(t)}}}(n,e)))}}}(e),{clientRef:f,phase:p,statusText:g,errorText:v,pairing:y,sessions:w,activeSessionId:b,diffSessionId:S,setDiffSessionId:x,respondingSessions:I,questionAnswers:k,agent:C,cwd:R,approvalMode:E,model:j,setModel:M,effort:A,setEffort:N,fastMode:P,setFastMode:D,renameTitle:L,setRenameTitle:F,draft:O,webPreferences:q,setSessionSort:_,setSearch:$,setSinceFilter:z,setHideArchived:H,setGroupFolders:B,setShowNeedsAttentionGroup:U,setShowRunningGroup:W,setSeparatePinnedGroup:K,collapsedFolders:G,setCollapsedFolders:V,setSessionAgentFilter:Q,composerPreferences:J,savedTargets:Z,leftSidebarCollapsed:X,setLeftSidebarCollapsed:Y,rightSidebarCollapsed:ee,setRightSidebarCollapsed:te,workspaceClassName:ne,wideMainClassName:se,workspaceStyle:re,beginPaneResize:ie,commitSearch:oe,saveTargets:ae,setLanguagePreference:ce,setThemePreference:le,updateComposerPreferences:de,t:ue,busy:he,rewindMessage:me,rewinding:fe,controlTab:pe,setControlTab:ge,detailsOpen:ve,setDetailsOpen:ye,setControlTabAndOpen:we,skills:be,admin:Se,daemonMetadata:xe,notificationSettings:Ie,notificationPermission:ke,archiveSyncBusy:Ce,archiveSyncStatus:Re,attachments:Ee,setAttachments:je,uploadBusy:Me,directory:Ae,newDirName:Te,setNewDirName:Ne,remoteFile:Pe,uploadFiles:De,openRemoteFile:Le,listDirectory:Fe,listSessionDirectories:Oe,listFileTreeDirectory:qe,createDirectory:_e,createSessionDirectory:$e,pendingActionsCount:ze,activeQueue:He,activeModelOptions:Be,activeUsage:Ue,activeApproval:We,activeQuestion:Ke,activeSession:Ge,displaySessions:Qe,groupedSessions:Je,historyLoading:Ze,hasOlderHistory:Xe,olderHistoryLoading:et,requestHistory:tt,messages:nt,messagesSessionIdRef:st,updateDraft:rt,requestReconnectSnapshot:it,requestSessions:ot,fetchAgentResources:at,failedSend:ct,dismissFailedSend:lt,retryFailedSend:dt,stagePendingSession:ut,listSessionModels:ht,loadDirectoryGitMetadata:mt,sendDraft:ft,sendQuickReply:pt,respondApproval:gt,respondQuestion:vt,cancelQuestion:yt,setQuestionChoice:wt,requestActiveAction:bt,interruptActiveSession:St,retrySessions:xt,updateApprovalMode:It,cancelQueuedTurn:kt,setSessionPinned:Ct,setSessionArchived:Rt,deleteSession:Et,updatePinned:jt,updateArchived:Mt,renameSession:At,runArchiveSync:Tt,skipArchiveSync:Nt,runAdminAction:Pt,exportActiveSession:Dt,clearPairing:Lt,setNotificationsEnabled:Ft,connectSavedTarget:Ot,forgetSavedTarget:qt,openSessionDetails:_t,editFolderTags:$t,copyResumeCommand:zt,resumeInTerminal:Ht,notificationsBlocked:Bt,hasDaemonUpdate:Ut,archiveSynced:Wt,archiveSyncDismissed:Kt}=e,Gt=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,ue),[e.pendingApprovals,e.pendingQuestions,ue]),Vt=t.useMemo(()=>c?Object.fromEntries(Je.map(e=>[e.folder,!1!==G[e.folder]])):G,[c,G,Je]),Qt=Je.length>0&&Je.every(e=>Vt[e.folder]),Jt=R===mn?Ae.path:R,Zt=b?Ge?.sessionId===b?Ge.cwd:void 0:Jt===mn?void 0:Jt;return"missing-pair"===p?n.jsxs(n.Fragment,{children:[n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ue.skipToConversation}),n.jsx(ji,{errorText:v,t:ue})]}):n.jsxs("main",{className:ne,id:"vibelet-workspace",style:re,children:[n.jsx(Ye,{workspace:e,onSelect:r.selectSession}),n.jsx(nc,{workspace:e,onSelect:r.selectSession}),u&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(fo,{client:"connected"===p?f.current:null,onOpenRemoteFile:Le,pairing:y,onLoadGitMetadata:mt,cwd:u.cwd,agent:C,device:y?.daemonId??"disconnected",connected:"connected"===p,approvalMode:E,model:j,effort:A,fastMode:P,t:ue,onClose:()=>h(null),onCreate:ut,onListModels:ht,onListDirectories:Oe,onCreateDirectory:$e},y?.daemonId??"disconnected")}),n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ue.skipToConversation}),n.jsx(Ya,{collapsed:X,onExpand:()=>Y(e=>!e),onResize:ie("left"),t:ue,children:n.jsx(Xa,{connectionIndicators:n.jsx(uc,{workspace:e}),activeDaemonId:y?.daemonId,activeSessionId:b,busy:he,collapsedFolders:Vt,allFoldersCollapsed:Qt,currentCwd:R,directoryTags:e.directoryTags,displayName:y?.displayName,savedTargets:Z,folderCounts:e.folderCounts,groupFolders:e.groupFolders,sessionSort:e.sessionSort,onSessionSortChange:_,groupedSessions:Je,hideArchived:e.hideArchived,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup,inventoryVersion:e.inventoryVersion,nextCursor:e.nextCursor,phase:p,respondingSessionIds:I,search:e.search,sessionAgentFilter:e.sessionAgentFilter,sessionsCount:Qe.length,sinceFilter:e.sinceFilter,statusText:g,t:ue,hasDaemonUpdate:Ut||m.rows.some(e=>e.available&&e.supported),visibleSessions:e.visibleSessions,onLoadMore:e=>ot({append:!0,cursor:e}),onCopyResumeCommand:zt,onResumeInTerminal:Ht,onConnectTarget:Ot,attentionReasons:Gt,pendingSessionIds:e.pendingSessionIds,onRequestNewSession:e=>h({cwd:e??R}),onRenameSession:At,onDeleteSession:e=>{Et(e)},onEditFolderTags:$t,onOpenSessionDetails:_t,onResetFilters:()=>{_("updated"),Q("all"),z("30d"),H(!1),B(!0),U(!1),W(!1),K(!1)},onRenameTarget:(e,t)=>ae(function(e,t,n){const s=n.trim();return s?e.map(e=>e.daemonId===t?{...e,label:s}:e):e}(Z,e,t)),onRemoveTarget:T(()=>ae(qn())),onEditConnection:s().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:$,onSearchCommit:oe,onSelectSession:r.selectSession,archiveUndo:e.archiveUndo,onToggleSessionArchived:e=>{Rt(e,!e.archived)},onToggleSessionPinned:e=>{Ct(e,!e.pinned)},onSessionAgentFilterChange:Q,onSinceFilterChange:z,onToggleFolder:e=>V(t=>({...t,[e]:c?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{l(!Qt),V({})},onToggleGroupFolders:()=>B(e=>!e),onToggleHideArchived:()=>H(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>Y(!0)})}),n.jsxs("section",{className:se,"aria-label":ue.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[n.jsx(Gc,{workspace:e,children:n.jsx(so,{client:"connected"===p?f.current:null,activeSession:Ge,activeSessionId:b,activeModelOptions:Be,activeQueue:He,activeUsage:Ue,agent:C,approvalMode:E,attachments:Ee,busy:he,cwd:R,draft:O,effort:A,errorText:v,failedSend:ct,onDismissFailedSend:lt,fastMode:P,historyLoading:Ze,hasOlderHistory:Xe,olderHistoryLoading:et,onLoadOlderHistory:()=>Ge?tt(Ge,{older:!0}):Promise.resolve(),messages:nt,messagesSessionId:st.current,model:j,phase:p,...Jc(J,de,pt),quickRepliesOpen:J.quickRepliesOpen,onQuickRepliesOpenChange:e=>de(t=>({...t,quickRepliesOpen:e})),renameTitle:L,respondingSessionIds:I,sendShortcut:J.sendShortcut,skills:be,uploadBusy:Me,detailsOpen:ve,t:ue,onApprovalModeChange:e=>{It(e)},onBrowseFiles:()=>{const e=Ge?.cwd||R||mn;we("files"),Fe(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{kt(e)},onClearInterrupt:()=>{bt("session.clearInterrupt")},onDraftChange:rt,onDetailsOpenChange:ye,onEffortChange:N,onExportActiveSession:()=>{Dt()},rewinding:fe,onResendMessage:e.resendMessage,onRewindMessage:e=>{me(e)},onFastModeChange:D,onRetryFailedSend:dt,onModelChange:M,onOpenRemoteFile:(e,t)=>{Le(e,t,{updateRoute:!0})},onInterrupt:St,onDismissError:()=>e.setErrorText(null),onRetry:()=>{xt(),at(Ge?.agent??C,R)},onRenameSession:e=>{At(void 0,e)},onRenameTitleChange:F,onRemoveAttachment:e=>je(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{at(Ge?.agent??C,R)},onSubmit:ft,onToggleArchived:()=>{Mt()},onTogglePinned:()=>{jt()},onUploadFiles:De,onViewChanges:x})}),n.jsxs(gc,{collapsed:ee,t:ue,value:pe,showSession:!1,onChange:ge,onResize:ie("right"),children:[n.jsx("div",{hidden:"files"!==pe,style:{display:"files"===pe?"contents":"none"},children:n.jsx(t.Suspense,{fallback:n.jsx(eo,{t:ue}),children:n.jsx(Qi,{client:"connected"===p?f.current:null,watch:!ee&&"files"===pe,onRefreshDirectory:()=>Fe(Ae.path,{background:!0}),busy:he,cwd:R,canGoBackDirectory:e.canGoBackDirectory,onGoBackDirectory:()=>{e.goBackDirectory()},directory:Ae,onLoadChildren:qe,newDirName:Te,remoteFile:Pe,t:ue,onCreateDirectory:()=>{_e()},onListDirectory:e=>{Fe(e,{updateRoute:!0})},onNewDirNameChange:Ne,onOpenRemoteFile:(e,t)=>{Le(e,t,{updateRoute:!0})}},y?.daemonId)})}),n.jsx(rc,{activeSessionId:b,activeSession:Ge,cwd:R,directoryPath:Ae.path,visible:"terminal"===pe,t:ue}),i?n.jsxs("div",{hidden:"browser"!==pe,className:"browser-tab-content",children:[n.jsx(Bi,{location:"right",kind:"browser",t:ue}),n.jsx(Wi,{location:"right",kind:"browser"})]}):null,"admin"===pe?n.jsxs(t.Suspense,{fallback:n.jsx(eo,{t:ue}),children:[n.jsx(Ji,{language:q.language,t:ue,onLanguageChange:ce}),!s().settingsTarget&&n.jsx(Yi,{}),n.jsx(Zi,{t:ue,theme:q.theme,onThemeChange:le}),n.jsx(Xi,{notificationsBlocked:Bt,permission:ke,settings:Ie,t:ue,onToggleEnabled:Ft}),!s().settingsTarget&&n.jsx(Vi,{workspace:e})]}):null]})]}),s().settingsTarget&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(Vi,{workspace:e,portalOnly:!0,agentUpdates:m})}),n.jsx("div",{className:"workspace-header-actions",children:n.jsx(ai,{projectEditor:s().renderProjectEditor?.(Zt,y?.daemonId,"connected"===p?f.current:null),client:"connected"===p?f.current:null,activeSession:Ge,busy:he,controlsOpen:!ee,pendingCount:ze,t:ue,onOpenControls:d,onRefreshSessions:()=>{ot({force:!0})},onRestoreSnapshot:()=>{it()},onToggleArchived:()=>{Mt()},onTogglePinned:()=>{jt()},onViewChanges:x})}),n.jsx(t.Suspense,{fallback:null,children:n.jsx(Zc,{activeApproval:We,activeQuestion:Ke,pendingCount:ze,requestKey:Qc(e.pendingApprovals,e.pendingQuestions),sessions:w,busy:he,errorText:v,questionAnswers:k,t:ue,onCancelQuestion:()=>{yt()},onQuestionChoice:wt,onRespondApproval:e=>{gt(e)},onRespondQuestion:()=>{vt()},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({})}},r.revealKey)}),n.jsx(Pi,{}),n.jsx(lo,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:we,onCloseRight:()=>te(!0),client:"connected"===p?f.current:null,daemonId:y?.daemonId,pairing:y,deviceName:y?.displayName??"",controlTab:pe,rightVisible:!ee,t:ue}),n.jsx(to,{activeSession:Ge,client:f.current,close:()=>x(null),id:S,sessions:w,t:ue})]})}const Yc=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:Tt(),notifications:At(),preferences:l(),drafts:Xn(),targets:qn()})),i=t.useRef(r.permission),o=t.useRef(r.notifications),a=t.useRef(r.preferences),d=t.useRef(r.drafts),u=t.useRef(r.targets),h=t.useRef(i.current),m=t.useRef(o.current),f=t.useRef(d.current),p=t.useRef(null),b=t.useRef(null),S=t.useRef(new Set),x=t.useRef(null),I=t.useRef(new Set),k=t.useRef(null),C=t.useRef(0),R=t.useRef(new Set),E=t.useRef({}),j=t.useRef(!1),[M,A]=t.useState("connecting"),[T,N]=t.useState(()=>w[c(a.current.language)].preparingVibeletWeb),[P,D]=t.useState(null),[L,F]=t.useState(null),[O,q]=t.useState([]),[_,$]=t.useState({}),[z,H]=t.useState({}),[B,U]=t.useState(),[W,K]=t.useState({}),[G,V]=t.useState(),[Q,J]=t.useState(null),Z=Be(L?.daemonId,Q),[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 $r),s=t.useRef(e);s.current!==e&&(s.current=e,n.current=new $r);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),[me,fe]=t.useState("claude"),[pe,ge]=t.useState(mn),[ve,ye]=t.useState(fn),[we]=t.useState(!1),[be,Se]=t.useState(""),[xe,Ie]=t.useState(""),[ke,Ce]=t.useState(!1),[Re,Ee]=t.useState(""),[je,Me]=t.useState(d.current),[Ae,Te]=t.useState(()=>ts(d.current,null)),{webPreferences:Ne,sessionSort:Pe,setSessionSort:De,setRightSidebarCollapsed:Le,search:Fe,setSearch:Oe,sinceFilter:qe,setSinceFilter:_e,hideArchived:$e,setHideArchived:He,groupFolders:Ue,setGroupFolders:We,showNeedsAttentionGroup:Ke,setShowNeedsAttentionGroup:Ge,showRunningGroup:Ve,setShowRunningGroup:Qe,separatePinnedGroup:Je,setSeparatePinnedGroup:Ze,collapsedFolders:Xe,setCollapsedFolders:Ye,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:mt,beginPaneResize:ft,applyBrowserDefaultWidth:pt,commitSearch:gt,saveTargets:vt,setLanguagePreference:yt,setThemePreference:wt,updateSessionListPreferences:bt,updateComposerPreferences:St}=function(e,n,s="default"){const[r,i]=t.useState(e);t.useEffect(()=>{const e=()=>{const e=l();N(qn()),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),[c,d]=t.useState(""),[u,h]=t.useState(e.sessionList.searchHistory),[m,f]=t.useState(e.sessionList.sinceFilter),[p,y]=t.useState(e.sessionList.hideArchived),[w,b]=t.useState(e.sessionList.groupFolders),[S,x]=t.useState(e.sessionList.showNeedsAttentionGroup),[I,k]=t.useState(e.sessionList.showRunningGroup),[C,R]=t.useState(e.sessionList.separatePinnedGroup),[E,j]=t.useState(e.sessionList.collapsedFolders),[M,A]=t.useState(e.sessionList.agentFilter),[T,N]=t.useState(n),[P,D]=t.useState(e.layout.leftSidebarCollapsed),[L,F]=t.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:O,rightPaneWidth:q,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),m="number"==typeof o?o:Math.round(h/("half"===o?2:3)),f=t.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),p=t.useRef(null);t.useEffect(()=>()=>p.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:m},c-96-64),v=t.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),p.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 m();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)},m=()=>{if(r){r=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",f,!0),window.removeEventListener("pointercancel",f,!0),window.removeEventListener("blur",m),window.removeEventListener("keydown",v,!0),document.removeEventListener("visibilitychange",y),n.removeEventListener("lostpointercapture",f);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}p.current===m&&(p.current=null)}},f=e=>{e.pointerId===s&&m()},v=e=>{"Escape"===e.key&&(e.preventDefault(),m())},y=()=>{"hidden"===document.visibilityState&&m()};p.current=m,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",f,!0),window.addEventListener("pointercancel",f,!0),window.addEventListener("blur",m),window.addEventListener("keydown",v,!0),document.addEventListener("visibilitychange",y),n.addEventListener("lostpointercapture",f);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:v,applyBrowserDefaultWidth:f}}(P,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:P,rightCollapsed:L,leftPaneWidth:O,rightPaneWidth:q});t.useEffect(()=>{i(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:o,sinceFilter:m,hideArchived:p,groupFolders:w,showNeedsAttentionGroup:S,showRunningGroup:I,separatePinnedGroup:C,collapsedFolders:E,agentFilter:M},layout:{...e.layout,leftSidebarCollapsed:P,rightSidebarCollapsed:L}};return g(t),t})},[E,w,p,P,L,u,C,M,S,I,m,o]);const K=t.useCallback(()=>{h(e=>v(e,c))},[c]),G=t.useCallback(e=>{N(e),_n(e)},[]),V=t.useCallback(e=>{i(t=>{const n={...t,language:e};return g(n),n})},[]),Q=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:c,setSearch:d,sinceFilter:m,setSinceFilter:f,hideArchived:p,setHideArchived:y,groupFolders:w,setGroupFolders:b,showNeedsAttentionGroup:S,setShowNeedsAttentionGroup:x,showRunningGroup:I,setShowRunningGroup:k,separatePinnedGroup:C,setSeparatePinnedGroup:R,collapsedFolders:E,setCollapsedFolders:j,sessionAgentFilter:M,setSessionAgentFilter:A,directoryTags:z,archiveSyncedDaemonIds:H,archiveSyncCardDismissedDaemonIds:B,composerPreferences:U,savedTargets:T,setSavedTargets:N,leftSidebarCollapsed:P,setLeftSidebarCollapsed:D,rightSidebarCollapsed:L,setRightSidebarCollapsed:F,workspaceClassName:W.workspaceClassName,wideMainClassName:W.wideMainClassName,workspaceStyle:W.style,beginPaneResize:_,applyBrowserDefaultWidth:$,commitSearch:K,saveTargets:G,setLanguagePreference:V,setThemePreference:Q,updateSessionListPreferences:J,updateComposerPreferences:Z}}(a.current,u.current,Z),xt=c(Ne.language),It=w[xt],[kt,Ct]=ze(Z,!1),[Rt,Et]=ze(Z,!1),[jt,Mt]=ze(Z,"files"),[Nt,Pt]=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 Dt=t.useCallback(e=>{Mt(e),Le(!1)},[Mt,Le]),[Lt,Ft]=t.useState({}),[Ot,qt]=t.useState({}),[_t,$t]=t.useState([]),[zt,Ht]=t.useState({statusText:"",loading:!1,action:null}),[Bt,Ut]=t.useState($n),[Wt,Kt]=t.useState(o.current),[Gt,Vt]=t.useState(i.current),[Qt,Jt]=t.useState(null),[Zt,Xt]=t.useState(null);return{clientRef:e,connectWithPairingRef:n,activeSessionIdRef:s,initialNotificationPermissionRef:i,initialNotificationSettingsRef:o,initialPreferencesRef:a,initialComposerDraftsRef:d,initialSavedTargetsRef:u,notificationPermissionRef:h,notificationSettingsRef:m,composerDraftsRef:f,lastHistorySessionIdRef:p,historyCacheDaemonIdRef:b,historyPrefetchingSessionIdsRef:S,pairingRef:x,notifiedEventsRef:I,reconnectTimerRef:k,connectionAttemptIdRef:C,respondingSessionsRef:R,turnNotificationCountsRef:E,intentionalDisconnectRef:j,phase:M,setPhase:A,statusText:T,setStatusText:N,errorText:P?qr(P,It.remoteDirectConnection,It.localConnection):null,setErrorText:D,pairing:L,setPairing:F,sessions:O,setSessions:q,pendingSessions:_,setPendingSessions:$,optimisticSessions:z,setOptimisticSessions:H,nextCursor:B,setNextCursor:U,folderCounts:W,setFolderCounts:K,inventoryVersion:G,setInventoryVersion:V,activeSessionId:Q,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:me,setAgent:fe,cwd:pe,setCwd:ge,approvalMode:ve,setApprovalMode:ye,continueSession:we,model:be,setModel:Se,effort:xe,setEffort:Ie,fastMode:ke,setFastMode:Ce,renameTitle:Re,setRenameTitle:Ee,composerDrafts:je,setComposerDrafts:Me,draft:Ae,setDraft:Te,webPreferences:Ne,sessionSort:Pe,setSessionSort:De,search:Fe,setSearch:Oe,sinceFilter:qe,setSinceFilter:_e,hideArchived:$e,setHideArchived:He,groupFolders:Ue,setGroupFolders:We,showNeedsAttentionGroup:Ke,setShowNeedsAttentionGroup:Ge,showRunningGroup:Ve,setShowRunningGroup:Qe,separatePinnedGroup:Je,setSeparatePinnedGroup:Ze,collapsedFolders:Xe,setCollapsedFolders:Ye,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:mt,beginPaneResize:ft,applyBrowserDefaultWidth:pt,commitSearch:gt,saveTargets:vt,setLanguagePreference:yt,setThemePreference:wt,updateSessionListPreferences:bt,updateComposerPreferences:St,language:xt,t:It,busy:kt,setBusy:Ct,rewinding:Rt,setRewinding:Et,controlTab:jt,setControlTab:Mt,detailsOpen:Nt,setDetailsOpen:Pt,setControlTabAndOpen:Dt,modelOptions:Lt,setModelOptions:Ft,usageLimits:Ot,setUsageLimits:qt,skills:_t,setSkills:$t,admin:zt,setAdmin:Ht,daemonMetadata:Bt,setDaemonMetadata:Ut,notificationSettings:Wt,setNotificationSettings:Kt,notificationPermission:Gt,setNotificationPermission:Vt,archiveSyncBusy:Qt,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:s,activeSessionIdRef:o,notificationPermissionRef:d,notificationSettingsRef:u,composerDraftsRef:h,lastHistorySessionIdRef:m,historyPrefetchingSessionIdsRef:f,pairingRef:I,reconnectTimerRef:k,respondingSessionsRef:C,phase:R,setStatusText:E,setErrorText:j,pairing:M,setSessions:A,setOptimisticSessions:T,setNextCursor:N,setFolderCounts:P,setInventoryVersion:D,activeSessionId:L,setActiveSessionId:F,respondingSessions:O,setRespondingSessions:q,pendingApprovals:_,setPendingApprovals:$,pendingQuestions:z,setPendingQuestions:H,setQuestionAnswers:B,pendingQueues:U,setPendingQueues:W,agent:K,setAgent:G,cwd:V,setCwd:Q,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:me,notificationSettings:fe,setNotificationSettings:pe,notificationPermission:ge,setNotificationPermission:ve,sessions:ye,pendingSessions:we,optimisticSessions:be,setDraft:Se,setBusy:xe}=e,Ie=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),m=t.useRef(null),f=m.current&&Ue(m.current.key,u)?m.current:null,{value:p,set:g,setForScope:v,resolveScope:y,getAll:w}=He(u,()=>[]),b=t.useCallback((e,t)=>{v(Be(s?.daemonId,e),t)},[s?.daemonId,v]);t.useEffect(()=>gr(()=>[...w().values()].some(e=>e.length>0)),[w]);const[S,x]=t.useState(!1),I=t.useRef(new Map);t.useEffect(()=>{const e=new Set(p.map(e=>e.path));for(const[t,n]of I.current)(null===y(n.scope)||y(n.scope)===y(u)&&![...n.paths].some(t=>e.has(t)))&&(t.abort(),I.current.delete(t));x(I.current.size>0)},[p,u,y]);const[k,C]=ze(u,()=>({path:f?.directory.path||!h.current&&(sr().folder||sr().cwd)||r||mn,entries:[],loading:!1,loaded:!1})),[R,E]=ze(u,()=>f?.directoryHistory??[]),[j,M]=ze(u,""),{remoteFile:A,setRemoteFile:T,openFiles:N,setOpenFiles:P,acknowledgeSave:D,completeOpen:L}=function(e,n,s){const r=t.useRef(null),i=r.current&&Ue(r.current.scope,e)?r.current:null,{value:o,set:a,getAll:c,updateAll:l}=He(e,()=>i?.value??(s?{current:Rr(s),files:{[Rr(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===$e(n,{...t,action:"remove"})&&Object.values(s.files).some(e=>e.dirty))return void e.preventDefault()};return window.addEventListener(Fe,e),()=>window.removeEventListener(Fe,e)},[c]),t.useEffect(()=>gr(()=>[...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=Rr(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]),m=t.useCallback((e,t)=>{let n=!1;a(s=>{const r=Rr(e);return s.files[r]!==e?s:(n=!0,{...s,files:{...s.files,[r]:t}})}),t.objectUrl&&(n?d.current.add(t.objectUrl):URL.revokeObjectURL(t.objectUrl))},[a]),f=t.useCallback((e,t)=>{a(n=>{const s=Rr(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)=>Sr(Rr(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=br(i.source??i.path,i.cwd),a=e=>`${br(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(Rr(l))},n=e&&Rr(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&&Sr(d,o,c.searchParams.get("cwd")??i.cwd)&&("delete"===i.action?c.searchParams.delete("file"):c.searchParams.set("file",a(br(d,c.searchParams.get("cwd")??i.cwd))),window.history.replaceState(null,"",c.href))};return window.addEventListener(yr,i),window.addEventListener(wr,o),()=>{window.removeEventListener(yr,i),window.removeEventListener(wr,o)}},[e,n,c,l]),{remoteFile:o.current?o.files[o.current]??null:null,setRemoteFile:u,openFiles:o.files,setOpenFiles:h,acknowledgeSave:f,completeOpen:m}}(u,s?.daemonId,f?.file),[F,O]=ze(u,()=>new Set);m.current={key:u,file:A,directory:k,directoryHistory:R};const q=e=>JSON.stringify([e.cwd,e.path,e.etag]),_=!!A&&F.has(q(A)),$=t.useRef(new Map),z=t.useRef(null);t.useEffect(()=>{C(e=>({...e,loaded:!1,loading:!1}))},[u]);const H=t.useRef(0),B=t.useRef(k.path);t.useEffect(()=>()=>{if(m.current&&Ue(u,m.current.key)&&!m.current.file&&sr().file&&(h.current=!1),H.current++,C(e=>e.loading?{...e,loading:!1}:e),y(u)!==y(m.current?.key??"")){z.current?.abort();for(const e of I.current.keys())e.abort();I.current.clear(),x(!1)}},[u]),t.useEffect(()=>{B.current!==k.path&&(H.current++,B.current=k.path)},[k.path]),t.useEffect(()=>(H.current++,C(e=>({...e,loading:!1,loaded:!1})),x(!1),()=>{H.current++;for(const e of I.current.keys())e.abort();I.current.clear(),z.current?.abort();for(const e of $.current.values())e.request.abort(),e.finish()}),[s?.pairToken]),t.useEffect(()=>{k.path!==mn||sr().folder||(H.current++,C(e=>({...e,entries:[],loaded:!1,loading:!1})))},[r]);const U=t.useCallback(async e=>{if(!e?.length||!s)return;const t=new AbortController;x(!0),l(null);const n=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));I.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 Ir(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);I.current.delete(t)&&x(I.current.size>0)}},[s,l,d.uploadFailed,d.uploadPathMissing,u]),W=t.useCallback(async e=>{if(!s||!A||"text"!==A.kind||$.current.has(u))return;const t=new AbortController,n={request:t,finish:()=>{$.current.get(u)===n&&($.current.delete(u),c(!1))}};$.current.set(u,n),c(!0),l(null);try{const n=await fetch(Nn(A.path,A.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${s.pairToken}`,"content-type":"text/markdown; charset=utf-8",...A.etag&&!e?.force?{"if-match":A.etag}:{}},body:A.text});if(t.signal.aborted)return;if(!n.ok){if(409===n.status)throw O(e=>new Set(e).add(q(A))),new Error(d.remoteFileConflict(A.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);O(e=>{const t=new Set(e);return t.delete(q(A)),t}),D(A,r)}catch(r){t.signal.aborted||m.current?.key!==u||l(r instanceof Error?r.message:String(r))}finally{n.finish()}},[s,A,c,l,u,D]),K=t.useCallback(async()=>{if(s&&A)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(A.path),t=await fetch(e?A.path:Nn(A.path,A.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(A.path),r.click(),URL.revokeObjectURL(n)}catch(e){l(e instanceof Error?e.message:String(e))}},[s,A,l,u]),G=t.useCallback(async(e=k.path,t)=>{const s=n.current;if(!s?.isConnected)return;if(t?.background&&B.current!==e)return;const i=B.current;t?.background||(t?.back?E(e=>e.slice(0,-1)):br(i,r)!==br(e,r)&&E(e=>[...e.slice(-49),i])),B.current=e;const o=++H.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(o!==H.current)return;C({path:e,entries:n.entries??[],loading:!1,loaded:!0}),t?.updateRoute&&rr({folder:e},{replace:t.replaceRoute})}catch(a){if(o!==H.current)return;C(e=>({...e,loading:!1,loaded:!0,error:a instanceof Error?a.message:String(a)}))}},[n,r,k.path,u]),V=t.useCallback(async()=>{const e=R.at(-1);e&&!k.loading&&(a("files"),await G(e,{updateRoute:!0,back:!0}))},[R,k.loading,G,a]),Q=t.useCallback(async(e,t,n)=>{if(!s)return;z.current?.abort();const i=new AbortController;if(z.current=i,l(null),/[\\/]$/.test(e)&&!/^[a-z][a-z\d+.-]*:\/\//i.test(e)){const s=t||r,i=/^(?:[/\\]|~[/\\]|[a-z]:[/\\])/i.test(e)||!s?e:Mn(s,e);return a("files"),void(await G(i,n))}let o;const c=kr(e,"",!1),u="video"===c||"audio"===c;if(u){o={path:e,cwd:t,kind:"binary",contentType:"",text:"",dirty:!1,loading:!0};const s=N[Rr(o)];if(s?.dirty)return void T(s);T(o),n?.updateRoute&&rr({file:e,...t?{cwd:t}:{}},{replace:n.replaceRoute})}const h=e=>o?L(o,e):T(e);try{const r=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),a=await fetch(r?e:Nn(e,t),{headers:r?{}:{authorization:`Bearer ${s.pairToken}`},method:u&&!r?"HEAD":"GET",signal:i.signal});if(!a.ok)throw new Error(404===a.status?d.fileNotFound(e):d.fileOpenFailed);const c=a.headers.get("content-type")??"application/octet-stream";if(r&&!c.startsWith("image/"))throw new Error(d.fileOpenFailed);const l=kr(e,c,!1);if("video"===l||"audio"===l){if(await(a.body?.cancel()),i.signal.aborted)return;const n=new URL(Nn(e,t));n.searchParams.set("token",s.pairToken),h({path:e,cwd:t,kind:"binary",contentType:c,text:"",mediaUrl:n.toString(),size:Number(a.headers.get("content-length"))||void 0,dirty:!1})}else{const n=await async function(e,t,n,s,r){const i=kr(t,s,!1),o=await e.blob();let a;if("html"===i||"unsupported"===i&&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)}(t,s)?a=await o.text():"unsupported"===i&&(a=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 o.arrayBuffer())),r.aborted)return;const c={path:t,cwd:n,contentType:s,etag:Pn(e.headers,"etag"),lastModified:Pn(e.headers,"last-modified"),dirty:!1};if(void 0!==a)return{...c,kind:"text",text:a,size:Number(e.headers.get("content-length"))||void 0};const l="pdf"===i?new Blob([o],{type:"application/pdf"}):o;return{...c,kind:Tn(t,s)?"image":"binary",text:"",objectUrl:URL.createObjectURL(l),size:o.size}}(a,e,t,c,i.signal);if(!n)return;h(n)}n?.updateRoute&&!o&&rr({file:e,...t?{cwd:t}:{}},{replace:n.replaceRoute})}catch(m){o?L(o,{...o,loading:!1,error:m instanceof Error?m.message:String(m)}):i.signal.aborted||l(m instanceof Error?m.message:String(m))}finally{o&&i.signal.aborted&&L(o,{...o,loading:!1,error:d.fileOpenFailed})}},[s,l,u,r,G,a,d,N,L,T]),J=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]),Z=t.useCallback(async e=>(await J(e)).filter(e=>e.isDirectory),[J]);t.useEffect(()=>{!h.current||"files"!==o||"connected"!==i||k.loading||k.loaded||G(k.path||r||mn)},[o,r,k.loaded,k.loading,k.path,G,i]),t.useEffect(()=>{if("connected"!==i||h.current)return;const e=sr();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void G(e.folder,{updateRoute:!1});e.file&&(e.cwd&&C(t=>({...t,path:e.cwd,loaded:!1})),Q(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[G,Q,i,a]);const X=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:Mn(k.path,j),cwd:r||void 0}),M(""),await G(k.path)}catch(t){l(t instanceof Error?t.message:String(t))}finally{c(!1)}}},[n,r,k.path,G,j,c,l,u]),Y=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:p,setAttachments:g,setSessionAttachments:b,uploadBusy:S,directory:k,canGoBackDirectory:R.length>0,goBackDirectory:V,setDirectory:C,newDirName:j,setNewDirName:M,remoteFile:A,setRemoteFile:T,openFiles:N,setOpenFiles:P,remoteFileConflict:_,uploadFiles:U,openRemoteFile:Q,saveRemoteFile:W,downloadRemoteFile:K,listDirectory:G,listSessionDirectories:Z,listFileTreeDirectory:J,createDirectory:X,createSessionDirectory:Y}}({scopeKey:Be(M?.daemonId,L),clientRef:s,pairing:M,cwd:V,phase:R,controlTab:ie,setControlTab:ae,setBusy:xe,setErrorText:j,t:re}),ke=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),Re=ce[K]??[],Ee=de[K],{completionAttention:je,reviewSessionIds:Me}=function(e,n,s){const r=t.useMemo(()=>{let t;try{t=window.localStorage}catch{}const n=`vibelet:completion-attention:${e??"disconnected"}`;if(!t)return new ur(void 0,n,hr);let s=mr.get(t);s||(s=new Map,mr.set(t,s));let r=s.get(n);return r||(r=new ur(t,n,hr),s.set(n,r)),r},[e]);t.useEffect(()=>{const e=()=>r.synchronizeRead();return window.addEventListener("storage",e),e(),()=>window.removeEventListener("storage",e)},[r]);const 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),e.lastActivityAt)},[r,n]),t.useEffect(()=>{for(const e of s)o.current.has(e)||r.observe(e,"responding-set");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,O),{historyCacheRef:Ae,historyPageStartRef:Te,hydrateVisibleHistory:Ne,messagesSessionIdRef:Pe,remapCachedHistory:De,appendCachedDelta:Le,appendCachedHistory:Oe,appendInfoMessage:_e,clearHistoryLoading:We,ensureCachedHistoryEntry:Ke,setCachedMessageDelivery:Ge,removeCachedMessage:Ve,resolveCachedMessageSession:Qe,historyLoading:Je,hasOlderHistory:Ze,olderHistoryLoading:Xe,messages:Ye,mergeCachedHistoryPage:et,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)Dr(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 Pr().find(n=>n.daemonId===e&&n.sessionId===t)?.messages.map(e=>{const t=Lt(e);return"sending"===t.localDelivery?{...t,localDelivery:"failed",localInterruptedSend:!0}:t})}(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),[m,f]=t.useState(!1),[p,g]=t.useState([]),v=t.useCallback(e=>!(e&&o.current&&o.current!==e||(o.current=null,f(!1),0)),[]),y=t.useCallback(t=>(i.current.restore(t)&&(delete a.current[t],delete c.current[t]),!!Er(n.current,t)&&(t===e.activeSessionIdRef.current&&(h.current=t,e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),g(n.current[t]??[])),!0)),[e.activeSessionIdRef,e.onDeliveryHistoryChanged]),w=t.useCallback((t,r,o)=>{n.current=function(e,t,n){return t?{...e,[t]:Ar(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]),b=t.useCallback((t,s,r,i)=>{const o=e=>w(t,function(e,t){return Wt(e.map(e=>({...e})),t)}(e,i)),d=l.current.get(t);d?.client===e.clientRef.current&&(void 0===d.before||r&&r.start<d.before)&&(d.received=!0),t===e.activeSessionIdRef.current&&e.setErrorText(t=>t===e.historyTimeoutMessage?null:t);const u=Er(n.current,t)?c.current[t]:void 0;if(c.current[t]=r,!r)return a.current[t]=void 0,o(s);const h=(n.current[t]??[]).filter(e=>!Mr(e));if("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(Tr).filter(Boolean));return[...t,...e.filter(e=>{const t=Tr(e);return!t||!n.has(t)})]}const r=t[0],i=r?e.findIndex(e=>r.historyKey&&e.historyKey?r.historyKey===e.historyKey:r.rewindPoint&&e.rewindPoint?r.role===e.role&&Pt(r.rewindPoint)===Pt(e.rewindPoint):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]}(h,s,u,r);return"byte"===u?.cursorMode&&e.length>s.length&&r.start>=u.start&&(c.current[t]={...r,start:u.start,hasMore:u.hasMore}),a.current[t]=c.current[t]?.start,o(e)}const m=a.current[t],f=r.start+s.length;if(void 0===m||f<m||r.start>m+h.length)return a.current[t]=r.start,o(s);a.current[t]=Math.min(m,r.start),c.current[t]={...r,start:Math.min(m,r.start),hasMore:Math.min(m,r.start)>0};const p=h.slice(0,Math.max(0,r.start-m)),g=h.slice(Math.max(0,f-m),Math.max(0,r.total-m));return o([...p,...s,...g])},[w,e.clientRef,e.activeSessionIdRef,e.setErrorText,e.historyTimeoutMessage]),S=t.useCallback((e,t)=>{delete c.current[e],a.current[e]=0;const n=w(e,t,{renderActive:!1});h.current=e,g(n)},[w]),x=t.useCallback((t,r)=>{n.current=jr(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]),I=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:jr(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]),k=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=k(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,localInterruptedSend:void 0,localDelivery:"interrupted"===s.localDelivery?"interrupted":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]),R=t.useCallback((t,r)=>{t=k(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,k,s]),E=t.useCallback((t,s)=>{n.current=function(e,t,n){return t&&n?{...e,[t]:Ut(vn(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]),j=t.useCallback((e,t)=>{x(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[x]),M=t.useCallback(e=>{n.current=function(e,t){if(!Er(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]},[]),A=t.useCallback((e,t)=>{s.remap(e,t),n.current=function(e,t,n){if(!t||!n||t===n||!Er(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]),T=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 m={client:r,received:!1,before:n?d?.start:void 0,settled:new Promise(e=>{h=e})};l.current.set(t.sessionId,m),n&&u(t.sessionId);const p=()=>e.clientRef.current===r,g=y(t.sessionId);g||delete a.current[t.sessionId],t.sessionId===e.activeSessionIdRef.current&&(g?v(t.sessionId):(o.current=t.sessionId,f(!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(!p())return;const s=n.snapshot.activeSession;return void(s?.sessionId===t.sessionId&&(e.setPendingQueues(e=>({...e,[t.sessionId]:s.pendingQueue??[]})),Fs(s,C)))}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}),!p())return}catch(w){!p()||e.activeSessionIdRef.current!==t.sessionId||w instanceof ln&&m.received||e.setErrorText(w instanceof Error?w.message:String(w))}finally{l.current.get(t.sessionId)===m&&l.current.delete(t.sessionId),h(),p()&&(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:k,setCachedMessageDelivery:C,removeCachedMessage:R,appendCachedDelta:E,appendCachedHistory:x,appendInfoMessage:j,clearHistoryLoading:v,ensureCachedHistoryEntry:I,historyCacheRef:n,historyLoading:m,historyPageStartRef:a,hydrateVisibleHistory:S,messages:p,messagesSessionIdRef:h,mergeCachedHistoryPage:b,remapCachedHistory:A,removeCachedHistory:M,renderCachedHistory:y,replaceCachedHistory:w,requestHistory:T,setMessages:g}}({onDeliveryChanged:je.deliveryChanged,onDeliveryHistoryChanged:je.reconcileDeliveries,onDeliveryRemoved:je.deliveryRemoved,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:o,clientRef:s,historyTimeoutMessage:re.historyRequestTimedOut,setPendingQueues:W,setErrorText:j});!function(e,n,s,r){t.useEffect(()=>{const t=e.current;if(t?.isConnected)for(const e of s)!e.runtime.isResponding&&n.takeHistoryRefresh(e.sessionId,e.lastActivityAt)&&fr(t,e).catch(()=>{})},[e,n,s,r])}(s,je,ye,Me);const ot=t.useMemo(()=>new Set(Object.entries(Ae.current).filter(([,e])=>Ls(e)).map(([e])=>e)),[Ae.current]),{activeSession:at,activeApproval:ct,activeQuestion:lt,displaySessions:dt,groupedSessions:ut,pendingSessionIds:ht,visibleSessions:mt}=function(e){const n=t.useRef({protectedSessionIds:[]}),s=t.useMemo(()=>kn(kn(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),i=t.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),o=t.useRef({scope:"",session:null}),c=JSON.stringify([e.daemonId??null,e.activeSessionId]),l=s.find(t=>t.sessionId===e.activeSessionId)??(o.current.scope===c?o.current.session:null);o.current={scope:c,session:l};const d=(e.activeSessionId?e.pendingApprovals[e.activeSessionId]:null)??Object.values(e.pendingApprovals)[0]??null,u=(e.activeSessionId?e.pendingQuestions[e.activeSessionId]:null)??Object.values(e.pendingQuestions)[0]??null,h=t.useMemo(()=>r(function(e,t){const n=e.filter(e=>("all"===t.agentFilter||e.agent===t.agentFilter)&&function(e,t){const n=t.trim().toLowerCase();return!n||[a(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(e=>e.toLowerCase().includes(n))}(e,t.search));if(!t.hideArchived)return n;const s=n.filter(e=>!e.archived);return t.search.trim()&&!s.length?n:s}(s,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated",!1),[s,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),m=t.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions),...e.reviewSessionIds??[],...e.failedSessionIds??[]]),[e.pendingApprovals,e.pendingQuestions,e.reviewSessionIds,e.failedSessionIds]),f=t.useMemo(()=>{if(e.search.trim()||"updated"!==(e.sessionSort??"updated"))return h;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:Jt(e,o,s),state:c?{protectedSessionIds:o}:n}}(h,Object.fromEntries([...e.respondingSessionIds].map(e=>[e,!0])),n.current);return n.current=t.state,t.sessions},[h,e.respondingSessionIds,e.search,e.sessionSort]),g=t.useMemo(()=>Object.fromEntries(f.map((e,t)=>[e.sessionId,t])),[f]),v=t.useMemo(()=>[...r(f.filter(e=>e.pinned&&!e.archived),"updated"),...f.filter(e=>!e.pinned||e.archived)],[f]),y=t.useMemo(()=>p(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=Kt(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&&Gt(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:Vt(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:Vt(a,s.regularSessionOrderById)}),i.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?Qt(i):Vt(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}(v,{needsAttentionSessionIds:m,regularSessionOrderById:g,respondingSessionIds:e.respondingSessionIds,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[m,g,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,v]);return{activeApproval:d,activeQuestion:u,activeSession:l,displaySessions:s,groupedSessions:y,pendingSessionIds:i,visibleSessions:v}}({daemonId:M?.daemonId,activeSessionId:L,reviewSessionIds:Me,failedSessionIds:ot,hideArchived:te,optimisticSessions:be,pendingApprovals:_,pendingQuestions:z,pendingSessions:we,respondingSessionIds:O,search:Y,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ye,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});cr(o,L),cr(I,M),cr(C,O),cr(u,fe),cr(d,ge),cr(h,Z);const{updateNewSessionDraft:ft,updateDraft:pt,updateSessionDraft:gt}=function({activeSessionIdRef:e,composerDraftsRef:n,setComposerDrafts:s,setDraft:r}){const i=t.useRef(null),o=t.useRef(null),a=t.useRef(!1);t.useEffect(()=>gr(()=>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{Yn(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(vr,c),window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener(vr,c),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]);const d=t.useCallback((t,i)=>{const o=es(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:o,composerDraftsRef:h,setComposerDrafts:X,setDraft:Se});t.useEffect(()=>{b();const e=S();e&&(ft(e),oe("session"),x())},[ft]),t.useEffect(()=>{const e=()=>{pe(At()),ve(Tt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&ve(Tt())},[ie]),t.useEffect(()=>()=>{k.current&&window.clearTimeout(k.current)},[]);const vt=t.useCallback((e,t=!1)=>{A(n=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return kn(n?e:e.filter(e=>s.has(e.sessionId)),t)}(n,e.sessions,t)),T(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),D(e.inventoryVersion),e.folderCounts&&P(e.folderCounts),t||function(e,t,n=i(),s=(new Date).toISOString()){if(!e)return;const r=[{daemonId:e,page:{...t,sessions:t.sessions.slice(0,120)},cachedAt:s},...Kn(n).filter(t=>t.daemonId!==e)].slice(0,8);try{n.setItem(Un,JSON.stringify(r))}catch{}}(I.current?.daemonId,e),E(e.inventoryBackfillInFlight?re.connectedIndexing:re.connected)},[re.connected,re.connectedIndexing]),yt=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,gitSync:t.syncStatuses?t.syncStatuses[s.cwd]??void 0:void 0,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:s,sessions:ye,setSessions:A,activeSessionIdRef:o}),wt=t.useCallback((e,t=C.current)=>{const n=s.current;if(!n?.isConnected||0===e.length)return;const r=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)&&(Er(t,o.sessionId)||s.has(o.sessionId)||i.push(o))}return i}(e.filter(e=>e.sessionId!==o.current),Ae.current,t,f.current);for(const s of r)f.current.add(s.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:s.sessionId,agent:s.agent},{timeoutMessage:re.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{f.current.delete(s.sessionId)})},[re.historyPrefetchTimedOut]),bt=t.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},r={},i={};for(const m of e.sessions)m.runtime.isResponding&&n.add(m.sessionId);for(const m of e.pendingApprovals??[])s[m.sessionId]={type:"approval.request",...m};for(const m of e.pendingQuestions??[])r[m.sessionId]={type:"question.request",...m};let o,a,c,l,d,u,h=null;if(e.activeSession){const m=e.activeSession,f=e.sessions.find(e=>e.sessionId===m.sessionId);if(h=m.sessionId,o=m.agent,a=f?.cwd||t.currentCwd||mn,c=m.approvalMode??f?.approvalMode??fn,l=m.approvalMode??null,d=Wt(m.messages??[],m.partialReplyText),(m.isResponding||m.externallyResponding)&&n.add(m.sessionId),m.pendingApproval&&(s[m.sessionId]={type:"approval.request",sessionId:m.sessionId,...m.pendingApproval}),m.pendingQuestion){const e={type:"question.request",sessionId:m.sessionId,...m.pendingQuestion};r[m.sessionId]=e,u=Sn(e)}m.pendingQueue?.length&&(i[m.sessionId]=m.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||mn,c=s.approvalMode??fn)}return{page:{sessions:e.sessions,nextCursor:hn(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:o.current,currentCwd:V});vt(t.page,!1),N(t.page.nextCursor),D(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&Ne(t.activeSessionId,t.messages),e.activeSession&&Fs(e.activeSession,Ge),e.activeSession&&void 0===e.activeSession.messages&&rt(e.activeSession,{refresh:!0}),o.current=t.activeSessionId,F(t.activeSessionId),t.activeAgent&&G(t.activeAgent),t.activeCwd&&Q(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&B(t.questionAnswers),C.current=new Set(t.respondingSessionIds),q(C.current),$(t.pendingApprovals),H(t.pendingQuestions),W(t.pendingQueues),yt(e.sessions),wt(e.sessions,new Set(t.respondingSessionIds))},[V,yt,Ne,wt,rt,vt,Ge]),St=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:s,activeSessionIdRef:o,activeAgent:at?.agent??K,sessionAgentFilter:ne,search:Y,sinceFilter:ee,hideArchived:te,apply:bt}),xt=function(e){const{clientRef:n,search:s,sinceFilter:r,hideArchived:i,sessionAgentFilter:o,viewKey:a}=e,c=t.useMemo(()=>({refresh:0,includeArchived:!1}),[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={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&&!(e?.append&&c.includeArchived),skipGitMetadata:!0,force:e?.force};let a=await t.request(n);if(!d())return;if(!e?.append&&(c.includeArchived=!1,s.trim()&&i&&!a.sessions.length&&!a.nextCursor)){if(a=await t.request({...n,id:t.makeId("sessions_archived"),hideArchived:!1,force:!1}),!d())return;c.includeArchived=!0}if(!d())return;const u=yn(a),h=l.current.options;h.setSessionsFromPage(u,e?.append),h.setActiveSessionId(e=>e??u.sessions[0]?.sessionId??null),h.hydrateGitMetadata(u.sessions),h.prefetchActiveHistories(u.sessions)}catch(h){if(d())throw h}},[n,c,s,r,i,o])}({clientRef:s,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:vt,setActiveSessionId:F,hydrateGitMetadata:yt,prefetchActiveHistories:wt}),It=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,m=qs[t],f=[],p=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:t},{timeoutMs:Ps}).then(e=>{h()&&n(n=>({...n,[t]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);f.push(/timeout|timed out/i.test(n)?o.resourceLoadTimedOut(e):o.resourceLoadFailed(e,n)),i(f.join("\n"))})(`${m} · ${o.model}`)),lr(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:t}),h).then(e=>{e&&h()&&s(n=>({...n,[t]:e}))}),lr(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:p},p},[e,n,s,r,i,o])}({t:re,clientRef:s,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:j}),kt=t.useCallback((e,t,n="info")=>{const r=s.current;r?.isConnected&&r.request({action:"log.report",id:r.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))Lr.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:Fr(e.error)},"error")},r=e=>{n("web.telemetry.unhandled_rejection",{errorKind:Fr(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])}(kt);const Ct=t.useCallback(async(e=I.current)=>{if(e){me(e=>({...e,loading:!0,error:null}));try{const t=await fetch(Bn(e,window.location,{sameOrigin:!1}),{cache:"no-store",signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);if(I.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));me({...n,loading:!1,error:null})}catch{if(I.current?.daemonId!==e.daemonId)return;me(e=>({...e,loading:!1,error:re.connectorVersionFailed}))}}else me($n)},[re.connectorVersionFailed]);t.useEffect(()=>{const e=()=>{pe(At()),ve(Tt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&"connected"===R&&Ct()},[ie,R,Ct]),t.useEffect(()=>{if("connected"!==R)return;const e=()=>{Ct()},t=window.setInterval(e,3e4);return window.addEventListener("focus",e),()=>{window.clearInterval(t),window.removeEventListener("focus",e)}},[R,Ct]);const Rt=t.useCallback(e=>{pe(t=>{const n={...t,...e};return u.current=n,function(e,t=i()){t.setItem(jt,JSON.stringify(e))}(n),n})},[]),Et=t.useCallback((t,n)=>{t&&n&&t!==n&&(qe({action:"remap",daemonId:I.current?.daemonId??null,sessionId:t,nextSessionId:n}),o.current===t&&(o.current=n),F(e=>e===t?n:e),m.current===t&&(m.current=n),Pe.current===t&&(Pe.current=n),je.remap(t,n),De(t,n),C.current=jn(C.current,t,n),q(e=>jn(e,t,n)),$(e=>En(e,t,n)),H(e=>En(e,t,n)),e.remapPendingQueue(t,n),W(e=>En(e,t,n)),T(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{Yn(s)}catch{}}return s}))},[je]);return{completionAttention:je,...e,...n,...Ie,pendingActionsCount:ke,activeQueue:Ce,activeModelOptions:Re,activeUsage:Ee,activeApproval:ct,activeQuestion:lt,activeSession:at,displaySessions:dt,groupedSessions:ut,pendingSessionIds:ht,visibleSessions:mt,appendCachedDelta:Le,appendCachedHistory:Oe,appendInfoMessage:_e,clearHistoryLoading:We,ensureCachedHistoryEntry:Ke,setCachedMessageDelivery:Ge,removeCachedMessage:Ve,resolveCachedMessageSession:Qe,historyCacheRef:Ae,historyLoading:Je,hasOlderHistory:Ze,olderHistoryLoading:Xe,historyPageStartRef:Te,hydrateVisibleHistory:Ne,messages:Ye,messagesSessionIdRef:Pe,mergeCachedHistoryPage:et,remapCachedHistory:De,removeCachedHistory:tt,renderCachedHistory:nt,replaceCachedHistory:st,requestHistory:rt,setMessages:it,updateDraft:pt,updateNewSessionDraft:ft,updateSessionDraft:gt,setSessionsFromPage:vt,hydrateGitMetadata:yt,prefetchActiveHistories:wt,applyReconnectSnapshot:bt,requestReconnectSnapshot:St,requestSessions:xt,fetchAgentResources:It,reportLog:kt,refreshDaemonMetadata:Ct,updateNotificationSettings:Rt,remapLocalSessionState:Et}}();!function(e){const n=e.admin.pendingUpdate,s=e.pairing?.daemonId,r=e.daemonMetadata.version,{phase:i,setAdmin:o,t:a}=e;t.useEffect(()=>{n&&(s!==n.daemonId?o(e=>({...e,pendingUpdate:void 0,statusText:""})):"connected"===i&&r&&r!==n.version?o(e=>({...e,pendingUpdate:void 0,statusText:a.daemonUpdateCompleted.replace("{version}",r)})):"connected"!==i&&o(e=>({...e,statusText:a.daemonUpdateReconnecting})))},[n,s,r,i,o,a])}(e),function(e){const n=t.useRef({daemonId:"",pending:!0,initial:!0});t.useLayoutEffect(()=>{const t=e.pairing?.daemonId;if("desktop"!==s().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 i=r(e.visibleSessions,"updated",!1)[0];i&&(n.current.initial&&e.activeSessionId||e.setActiveSessionId(i.sessionId),n.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e),function(e,n,s){const r=Be(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=sr();s(e=>function(e,t,n,s,r){if(t===n)return e;const i=!t&&r?r:s||mn;return i===e.path?e:{path:i,entries:[],loading:!1,loaded:!1}}(e,t,r,n.cwd||mn,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=or();if(!r.supportsSessionRewindByPoint)return void e.setErrorText(i.rewindUpdateRequired);const o=e.historyCacheRef.current[s.sessionId]??[],a=o[Dt(o,t)];if(!a||"user"!==a.role||"info"===a.type||Nt(t)||Nt(a))return void e.setErrorText(i.unavailable);n.current=!0;let c=!1;try{c=await f({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 Ks("sessionRewind");if(e.clientRef.current!==r||!r.isConnected)return;let o=a.rewindPoint;if(!o){if(await e.requestHistory(s,{refresh:!0}),e.clientRef.current!==r||!r.isConnected)return;const t=e.historyCacheRef.current[s.sessionId]??[];o=t[Dt(t,a)]?.rewindPoint}if(!o||o.provider!==s.agent)throw new Error(i.unavailable);const c=await r.request({action:"session.rewind",id:r.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetRewindPoint:o,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,Ft(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:o,composerDraftsRef:I,lastHistorySessionIdRef:k,respondingSessionsRef:C,phase:R,setErrorText:E,pairing:j,setSessions:M,pendingSessions:A,activeSessionId:T,setActiveSessionId:N,setRespondingSessions:P,setPendingApprovals:D,setPendingQuestions:L,setPendingQueues:F,setLivePendingQueue:O,agent:q,setAgent:_,cwd:$,setCwd:z,setApprovalMode:H,setEffort:B,setFastMode:U,setRenameTitle:W,setDraft:K,archiveSyncedDaemonIds:G,archiveSyncCardDismissedDaemonIds:V,setControlTabAndOpen:Q,daemonMetadata:J,notificationPermission:Z,displaySessions:X,appendInfoMessage:Y,clearHistoryLoading:ee,messagesSessionIdRef:te,renderCachedHistory:ne,replaceCachedHistory:se,requestHistory:re,setMessages:ie,requestSessions:oe,remapLocalSessionState:ae,attachments:ce,setAttachments:le,listDirectory:de,activeApproval:ue,activeQuestion:he,activeSession:me,appendCachedDelta:fe,appendCachedHistory:pe,ensureCachedHistoryEntry:ge,setCachedMessageDelivery:ve,resolveCachedMessageSession:ye,historyCacheRef:we,messages:be,mergeCachedHistoryPage:Se,removeCachedHistory:xe,updateDraft:Ie,setSessionsFromPage:ke,requestReconnectSnapshot:Ce,fetchAgentResources:Re,reportLog:Ee,refreshDaemonMetadata:je,updateNotificationSettings:Me,clientRef:Ae,connectWithPairingRef:Te,activeSessionIdRef:Ne,notificationPermissionRef:Pe,notificationSettingsRef:De,historyCacheDaemonIdRef:Le,pairingRef:Oe,notifiedEventsRef:We,reconnectTimerRef:Ke,connectionAttemptIdRef:Ge,turnNotificationCountsRef:Ve,intentionalDisconnectRef:Qe,setPhase:Je,setStatusText:Ze,setPairing:Xe,setPendingSessions:Ye,setOptimisticSessions:et,questionAnswers:tt,setQuestionAnswers:nt,approvalMode:ot,continueSession:at,model:lt,effort:dt,fastMode:ut,renameTitle:ht,setComposerDrafts:mt,draft:ft,search:pt,sinceFilter:gt,savedTargets:yt,setSavedTargets:wt,saveTargets:Ct,updateSessionListPreferences:Rt,t:Mt,busy:Ot,setBusy:qt,setDetailsOpen:_t,setAdmin:$t,setDaemonMetadata:zt,setNotificationPermission:Ht,archiveSyncBusy:Bt,setArchiveSyncBusy:Zt,setArchiveSyncStatus:Xt}=e,Yt=function(e){const{appendInfoMessage:n,remapLocalSessionState:s,renderCachedHistory:r,replaceCachedHistory:i,requestSessions:o,setPendingQueues:a,setPendingApprovals:c,setPendingQuestions:l,setActiveSessionId:d,messagesSessionIdRef:u,lastHistorySessionIdRef:h,setMessages:m,setSessions:f,respondingSessionsRef:p,setRespondingSessions:g,activeSessionIdRef:v}=e;return t.useCallback(async(e,t,y)=>{const w="string"==typeof y.sessionId?y.sessionId:e,b="string"==typeof y.oldSessionId?y.oldSessionId:"new"===t.name?"":e,S=[e,b,w].includes(v.current??"");b&&w&&b!==w&&s(b,w),"clear"===t.name?(i(w,[]),a(e=>{const t={...e};return delete t[w],delete t[b],t}),c(e=>{const t={...e};return delete t[w],delete t[b],t}),l(e=>{const t={...e};return delete t[w],delete t[b],t}),S&&(v.current=w,d(w))):"new"===t.name?S&&(v.current=w,d(w),u.current=w,r(w)||m([])):"exit"===t.name?(f(e=>e.map(e=>e.sessionId===w?{...e,archived:!0}:e)),S&&(v.current=null,d(null),u.current=null,h.current=null,m([]))):"goal"===t.name&&"goal"in y&&n(w,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."}(y.goal)),y.turnStarted&&!y.queued&&(p.current=new Set(p.current).add(w),g(e=>new Set(e).add(w))),await o({force:!0})},[n,s,r,i,o])}(e),nn=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})},r=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,r,i,o)=>{const a=e.notificationSettingsRef.current;if(!a[i]||e.notifiedEventsRef.current.has(t))return;const c=e.pairingRef.current?.daemonId;(function(e,t,n={}){const r=n.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!r&&!s().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??Tt(),n.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(s().notifications)return s().notifications.show(e,t,n.onClick),!0;const i=new r(e,{body:t,tag:n.tag});return n.onClick&&(i.onclick=n.onClick),!0})(n,r,{onClick:()=>{e.pairingRef.current?.daemonId===c&&(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.progress":return void e.setDaemonUpdateStatus?.(e.t.daemonUpdateAlreadyRunning);case"daemon.update.failed":{const n="timeout"===t.reason?e.t.daemonUpdateTimedOut:t.message;return e.setDaemonUpdateStatus?.(n,!0),void e.setErrorText(n)}case"response":pn(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":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,t.messages,t.historyPage,t.partialReplyText),e.completionAttention?.reconcileTurn(t.sessionId,e.historyCacheRef.current[t.sessionId]??t.messages,t.type),t.isResponding||t.externallyResponding?e.completionAttention?.observe(t.sessionId,t.type):e.completionAttention?.complete(t.sessionId,t.type),Fs(t,e.setCachedMessageDelivery),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=Os(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),e.completionAttention?.reconcileTurn(t.sessionId,e.historyCacheRef.current[t.sessionId]??t.messages,t.type),t.messages.some(e=>"user"===e.role&&e.timestamp&&"info"!==e.type)&&e.completionAttention?.observe(t.sessionId,t.type);break;case"text.delta":r(t.sessionId),e.completionAttention?.observe(t.sessionId,t.type),n(t.sessionId),e.appendCachedDelta(t.sessionId,t.content),e.respondingSessionsRef.current=Os(e.respondingSessionsRef.current,t.sessionId,!0),e.setRespondingSessions(e=>Os(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":r(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${bn(t.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":r(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,t.type),e.completionAttention?.complete(t.sessionId,t.type),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,function(e,t){for(let n=e.length-1;n>=0;n--){const t=e[n];if("user"===t.role)break;if("assistant"!==t.role||"info"===t.type)continue;const s=t.content.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(?:#{1,6}\s+|>\s*|[-*+]\s+)/gm,"").replace(/(\*\*|__|~~)(.+?)\1/g,"$2").replace(/`([^`]+)`/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/\s+/g," ").trim();if(!s)continue;const r=Array.from(s);return r.length>240?`${r.slice(0,239).join("")}…`:s}return t}(e.historyCacheRef.current[t.sessionId]??[],e.t.notificationReplyBody),"replies",t.sessionId)}e.respondingSessionsRef.current=Os(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Os(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=Os(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Os(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=Os(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Os(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])}({pairingRef:Oe,setDaemonUpdateStatus:(e,t)=>$t(n=>({...n,statusText:e,...t?{pendingUpdate:void 0}:{}})),historyCacheRef:we,refreshInterruptedHistory:e=>{if(e!==Ne.current)return;const t=X.find(t=>t.sessionId===e);t&&re(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:De,notifiedEventsRef:We,notificationPermissionRef:Pe,activeSessionIdRef:Ne,respondingSessionsRef:C,turnNotificationCountsRef:Ve,t:Mt,setActiveSessionId:N,setErrorText:E,setPendingQueues:F,setLivePendingQueue:O,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:nt,setRespondingSessions:P,setSessions:M,remapLocalSessionState:ae,requestSessions:oe,clearHistoryLoading:ee,replaceCachedHistory:se,setCachedMessageDelivery:ve,mergeCachedHistoryPage:Se,appendCachedHistory:pe,appendCachedDelta:fe});(function(e){const n=t.useRef(null),r=t.useRef(null),o=()=>{null!==r.current&&window.clearTimeout(r.current),r.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 un,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 m=!1;a.onClose(()=>{h()&&m&&(n.clientRef.current=null,o(),n.intentionalDisconnectRef.current||(n.setPhase("connecting"),n.setStatusText(n.t.reconnectingToDaemon),n.setErrorText(n.t.webSocketClosedRetrying),l(e)))});const f=!!n.pairingRef.current&&n.pairingRef.current.daemonId!==e.daemonId;f&&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 p=function(e,t=i()){return e?Kn(t).find(t=>t.daemonId===e)?.page??null:null}(e.daemonId);p&&n.setSessionsFromPage(p,!1),n.setStatusText(t?n.t.reconnectingToDaemon:n.t.connectingToDaemon);try{const i=await(s().prepareConnection?.(e))??e;if(!h())return;let o,l=i;try{o=await a.connect(i)}catch(g){if(!h()||!i.webSocketUrl||Gn(g))throw g;l={...i,webSocketUrl:void 0},n.setStatusText(n.t.reconnectingToDaemon),o=await a.connect(l)}if(!h())return;m=!0;const d={...l,displayName:o.displayName??l.displayName};n.setPairing(d),n.pairingRef.current=d,St(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 _n(t),t}),n.setPhase("connected"),n.setStatusText(n.t.connectedTo(o.displayName??e.displayName??"Vibelet Daemon")),n.refreshDaemonMetadata(d);let u=null;const p=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),r.current=window.setTimeout(()=>{r.current=null,p()},1600)}};p();const v=c.current;v.fetchAgentResources(v.agent,f?mn: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(),Gn(g)&&bt()?.pairToken===e.pairToken&&xt(),n.setPhase("error"),n.setStatusText(n.t.connectionFailed),n.setErrorText(Gn(g)?n.t.pairingAuthFailed:g instanceof Error?g.message:String(g)),Gn(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=vt(),s=bt()??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:It(n,s)});const r=n?await(a.current?.promise):s;if(!r||t)return;n&&(St(r),a.current=null,function(){if(!window.location.hash.includes(`${it}=`))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 ct&&"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().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:Te,pairingRef:Oe,reconnectTimerRef:Ke,connectionAttemptIdRef:Ge,intentionalDisconnectRef:Qe,historyCacheRef:we,historyCacheDaemonIdRef:Le,messagesSessionIdRef:te,lastHistorySessionIdRef:k,rememberedTarget:o.current[0]??null,agent:q,cwd:$,phase:R,search:pt,sinceFilter:gt,t:Mt,handleServerMessage:nn,setPhase:Je,setStatusText:Ze,setErrorText:E,setMessages:ie,setPairing:Xe,setSavedTargets:wt,setSessionsFromPage:ke,resetDeviceWorkspace:()=>{Ne.current=null,N(null),z(mn),M([]),Ye({}),et({}),e.setDiffSessionId(null),D({}),L({}),F({}),C.current=new Set,P(new Set),rr({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:je,requestReconnectSnapshot:Ce,fetchAgentResources:Re,reportLog:Ee,requestSessions:oe}),t.useLayoutEffect(()=>{K(ts(I.current,T))},[T,j?.daemonId]),t.useEffect(()=>{const e=me;if(!e)return k.current=null,te.current=null,ee(),void ie([]);if(_(e.agent),z(e.cwd||mn),W(e.customTitle??e.title??""),A[e.sessionId]){if(k.current=e.sessionId,ee(),ne(e.sessionId))return;te.current!==e.sessionId&&(te.current=e.sessionId,ie([]))}else{if(ne(e.sessionId)){const t=k.current!==e.sessionId;return k.current=e.sessionId,ee(e.sessionId),void(t&&re(e,{refresh:!0}))}k.current!==e.sessionId&&(k.current=e.sessionId,te.current!==e.sessionId&&(te.current=e.sessionId,ie([])),re(e,{refresh:!0}))}},[me,T,ee,A,ne,re]);const rn=function(e){const n=t.useRef(e);n.current=e;const s=t.useRef(!0),r=t.useRef(new Map),[i,o]=t.useState(null),a=JSON.stringify([e.pairing?.daemonId,e.activeSession?.sessionId]),c=t.useRef(a);return c.current=a,t.useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]),t.useLayoutEffect(()=>{e.activeSession&&e.setModel(e.activeSession.model??"")},[a,e.activeSession?.model]),{setModel:t=>{const i=e.activeSession;if(!i)return void e.setModel(t);if(e.pendingSessions[i.sessionId])return e.setPendingSessions(e=>e[i.sessionId]?{...e,[i.sessionId]:{...e[i.sessionId],model:t||void 0}}:e),void e.setModel(t);const l=e.clientRef.current;if(!l?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);if(r.current.has(a))return;const d=()=>s.current&&n.current.clientRef.current===l&&l.isConnected&&n.current.pairing?.daemonId===e.pairing?.daemonId;e.setErrorText(null),o(a);const u=(async()=>{try{const n=await l.request({action:"session.configure",id:l.makeId("model"),sessionId:i.sessionId,model:t,expectedModel:i.model??""},{timeoutMs:15e3});if(!d())return!1;const s=n.model;return e.setSessions(e=>e.map(e=>e.sessionId===i.sessionId?{...e,model:s}:e)),e.setOptimisticSessions(e=>e[i.sessionId]?{...e,[i.sessionId]:{...e[i.sessionId],model:s}}:e),c.current===a&&e.setModel(s??""),!0}catch(u){return d()&&c.current===a&&e.setErrorText(u instanceof Error&&"session_model_conflict"===u.message?e.t.modelChangedRemotely:e.t.modelSaveFailed),!1}finally{r.current.delete(a),s.current&&o(e=>e===a?null:e),d()&&n.current.requestSessions({force:!0,preserveLoaded:!0}).catch(()=>{})}})();r.current.set(a,u)},saving:i===a,waitForSave:()=>r.current.get(a)??Promise.resolve(!0)}}(e),an=function({daemonId:e,session:n,setEffort:s,setFastMode:r,setApprovalMode:o,setPendingSessions:a}){const c=t.useRef(null);c.current||(c.current=function(){try{const e=JSON.parse(i().getItem(ar)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};for(const t of Object.values(e))t&&"object"==typeof t&&delete t.model;return e}catch{return{}}}());const l=JSON.stringify([e??"",n?.sessionId??""]),d={effort:n?.effort??"",fastMode:n?.fastMode??!1,approvalMode:n?.approvalMode??fn},u=()=>{try{i().setItem(ar,JSON.stringify(c.current))}catch{}},h=e=>{const t=c.current[l]?.[e];return void 0===t?d[e]:(d[e]===t&&delete c.current[l][e],t)};t.useLayoutEffect(()=>{n&&(s(h("effort")),r(h("fastMode")),o(h("approvalMode")),u())},[l,d.effort,d.fastMode,d.approvalMode]);const m=(e,t)=>{n&&(c.current[l]={...c.current[l],[e]:t},u(),a(s=>{const r=s[n.sessionId];if(!r)return s;const i="effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...r,[e]:i}}})),"effort"===e&&s(t),"fastMode"===e&&r(t),"approvalMode"===e&&o(t)};return{applyConfirmedSettings:(t,s)=>{const i=JSON.stringify([e??"",t]),o=c.current[i];o&&(void 0!==s.fastMode&&delete o.fastMode,u()),n?.sessionId===t&&void 0!==s.fastMode&&r(s.fastMode)},setEffort:e=>m("effort",e),setFastMode:e=>m("fastMode",e),setApprovalMode:e=>m("approvalMode",e)}}({daemonId:j?.daemonId,session:me,setEffort:B,setFastMode:U,setApprovalMode:H,setPendingSessions:Ye}),{stagePendingSession:dn,failedSend:gn,dismissFailedSend:An,retryFailedSend:Ln,sendDraft:Fn,sendQuickReply:On}=function(e){const[n]=t.useState(Qs),[s,r]=function(e,t,n){const s=He(Be(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=Be(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),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]);!function(e,n,s,r){const i=t.useRef(new Set);t.useEffect(()=>{const t=t=>JSON.stringify([e.daemonId,t]);if(n&&i.current.add(t(n.clientMessageId)),!n){const n=Ls(e.messages),o=e.activeSessionId;if(!o||e.messagesSessionIdRef.current!==o||!n?.localClientMessageId)return;if("accepted"===n.delivery||n.historyKey&&!n.historyKey.startsWith("client:"))return;const a=t(n.localClientMessageId);if(i.current.has(a))return;return i.current.add(a),r(o),void s({sessionId:o,clientMessageId:n.localClientMessageId,historyKey:`client:${n.localClientMessageId}`,message:n.content,images:n.images,agent:e.activeSession?.agent??e.agent,model:e.activeSession?.model,effort:e.activeSession?.effort,fastMode:e.activeSession?.fastMode??!1,skillInvocation:Zs(n.content),kind:n.localInterruptedSend?"network":"unknown",retrying:!1})}const o=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);if(e.messagesSessionIdRef.current!==o)return;const a=e.messages.find(e=>e.localClientMessageId===n.clientMessageId||e.historyKey===n.historyKey);a&&("accepted"===a.delivery||"delivered"===a.localDelivery||a.historyKey&&!a.historyKey.startsWith("client:")?s(null):n.retrying||"sending"!==a.localDelivery||(e.setCachedMessageDelivery(o,n.clientMessageId,"failed"),r(o)))},[e,n,s,r])}(e,s,r,a);const c=t.useCallback((t,n,s)=>{const r=[t,e.cwd].find(e=>"string"==typeof e&&e.trim())??mn,i=n??e.agent,a=function(e=Date.now()){return Cn=(Cn+1)%1e4,`pending_local_${e}_${Cn}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||mn,...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:xn(s?.model??e.model),effort:(s?.effort??e.effort)||void 0,fastMode:s?.fastMode??e.fastMode,title:e.t.newAgentSession(qs[i])});Object.assign(c,{preparationId:s?.preparationId});const l=s?.draft??(e.activeSessionIdRef.current?"":ts(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.revealCreatedSession(r),e.setComposerDrafts(t=>{let n=es(t,a,l);return e.activeSessionIdRef.current||(n=es(n,null,"")),e.composerDraftsRef.current=n,Yn(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),{sessionId:null,error:e.t.webSocketNotConnected};const i=s?e.pendingSessions[s]:void 0,o=er(t)??er(i?.cwd)??er(e.cwd)??mn,a=n??i?.agent??e.agent,c=i?.approvalMode??e.approvalMode,l=i?i.model:xn(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{sessionId: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=pn(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}),{sessionId:n}}catch(h){if(e.clientRef.current!==r)return{sessionId: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),{sessionId:null,error:t}}},[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=>{const n=e.sessions.find(e=>e.sessionId===t)??(e.activeSession?.sessionId===t?e.activeSession:null);if(!n?.archived)return;const s=e.clientRef.current;if(!s?.isConnected)throw new Error(e.t.webSocketNotConnected);await s.request({action:"session.setArchived",id:s.makeId("unarchive"),sessionId:t,archived:!1}),e.clientRef.current===s&&(e.setSessions(e=>e.map(e=>e.sessionId===t?{...e,archived:!1}:e)),e.setOptimisticSessions(e=>({...e,[t]:{...n,...e[t],archived:!1}})),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 m=n.start(e.activeSessionId);try{if(e.waitForModelSave&&!(await e.waitForModelSave()))return;const t=Zs(o)?"agentSkills":0===u.length&&Us(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await Ks(t)}catch(f){if(e.clientRef.current!==h)return;return void e.setErrorText(f instanceof Error?f.message:String(f))}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,p=e.pendingSessions[c]?.agent??e.activeSession?.agent??e.agent;const g=c?e.pendingSessions[c]:void 0,v=g?.fastMode??e.fastMode,y=void 0,w=g?g.effort:e.effort||void 0;if(c&&e.pendingSessions[c]&&0===s.length&&Us(o,p)){const{sessionId: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&&Ys(e,o,s));c=t,p=e.pendingSessions[e.activeSessionId??""]?.agent??p}if(!c)return void(void 0===i&&Ys(e,o,s));m.remap(c);const b=0===s.length?Us(o,p):null;if(b){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"}(b.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:p,command:b.command,...s?{clientMessageId:s}:{},featureEntitlements:n});if(e.clientRef.current!==h)return;await e.handleSessionCommandResponse(c,b.command,r)}catch(f){if(e.clientRef.current!==h)return;const t=f instanceof Error?f.message:String(f);e.appendInfoMessage(c,Ws(t)),e.activeSessionIdRef.current===c&&e.setErrorText(Ws(t))}return}const S=function(e){return e.startsWith("//")?e.slice(1):e}(o),x=s.map(e=>e.path),I=h.makeId("msg"),k=`client:${I}`;e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.setCachedMessageDelivery(c,I,"sending",{content:S,...x.length?{images:x}:{}}),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=Zs(S)??void 0,R=C?n:void 0,E={sessionId:c,agent:p,message:S,clientMessageId:I,historyKey:k,kind:"network",retrying:!1,images:x.length?x:void 0,model:y,effort:w,fastMode:v,skillInvocation:C,featureEntitlements:R};try{if(g){const t=await l(g.cwd,g.agent,c);if(e.clientRef.current!==h)return;if(null===t.sessionId)throw new Error(t.error??e.t.sessionCreateFailed);c=t.sessionId,m.remap(c)}if(await d(c),e.clientRef.current!==h)return;const t=await Vs(h,{action:"session.send",id:h.makeId("send"),sessionId:c,agent:p,message:S,clientMessageId:I,images:x.length?x:void 0,model:y,effort:w,fastMode:v,skillInvocation:C,featureEntitlements:R},{timeoutMs:Ps,timeoutMessage:tr},t=>e.appendInfoMessage(c,t));if(e.clientRef.current!==h)return;pn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(m.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId));const n=pn(t)&&!0===t.interrupted;e.setCachedMessageDelivery(pn(t)&&"string"==typeof t.sessionId?t.sessionId:c,I,n?"interrupted":"delivered"),n||e.reportLog("web.telemetry.send_accepted",{attachmentCount:x.length}),r(e=>e?.historyKey===k?null:e)}catch(f){if(e.clientRef.current!==h)return;c=e.resolveCachedMessageSession(c,I);const t=f instanceof Error?f.message:String(f),n=Ns(Dn(t,Boolean(C)));if("delivered"===e.setCachedMessageDelivery(c,I,"failed"))return;e.activeSessionIdRef.current===c&&e.setErrorText(null),r({sessionId:c,agent:p,message:S,clientMessageId:I,historyKey:k,kind:n,detail:Ds(t),retrying:!1,...x.length?{images:x}:{},model:y,effort:w,fastMode:v,skillInvocation:C,featureEntitlements:R}),e.reportLog("web.telemetry.send_failed",{attachmentCount:x.length,failureKind:n},"warn"),a(c)}finally{e.clientRef.current!==h&&r({...E,sessionId:c})}}finally{m.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",detail:void 0}:null);if(e.waitForModelSave&&!(await e.waitForModelSave()))return;if(e.clientRef.current!==t)return;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{const n=e.pendingSessions[i];if(n){const s=await l(n.cwd,n.agent,i);if(e.clientRef.current!==t)return;if(null===s.sessionId)throw new Error(s.error??e.t.sessionCreateFailed);i=s.sessionId,o.remap(i)}await d(i);const a=s.skillInvocation?await Ks("agentSkills"):void 0;if(e.clientRef.current!==t)return;const c=await Vs(t,{action:"session.send",id:t.makeId("retry_send"),sessionId:i,agent:s.agent,message:s.message,clientMessageId:s.clientMessageId,images:s.images,model:void 0,effort:s.effort,fastMode:s.fastMode,skillInvocation:s.skillInvocation??void 0,featureEntitlements:a},{timeoutMs:Ps,timeoutMessage:tr},t=>e.appendInfoMessage(i,t));if(e.clientRef.current!==t)return;pn(c)&&"string"==typeof c.oldSessionId&&"string"==typeof c.sessionId&&(o.remap(c.sessionId),e.remapLocalSessionState(c.oldSessionId,c.sessionId));const u=pn(c)&&!0===c.interrupted;e.setCachedMessageDelivery(pn(c)&&"string"==typeof c.sessionId?c.sessionId:i,s.clientMessageId,u?"interrupted":"delivered"),u||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=c instanceof Error?c.message:String(c),o=Ns(Dn(n,Boolean(s.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(i,s.clientMessageId,"failed"))return void r(null);r(e=>e?{...e,sessionId:i,kind:o,detail:Ds(n),retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:s.images?.length??0,failureKind:o},"warn"),a(i)}finally{r(e=>e?.clientMessageId===s.clientMessageId&&e.retrying?{...e,retrying:!1}:e),o.finish()}},[a,l,s,e,n,d]);return function(e,n,s,r,i,o){const a=t.useRef({failure:n,retry:o});a.current={failure:n,retry:o};const c=t.useRef(new WeakMap),l=n?.clientMessageId,d=n?.kind,u=n?.retrying;t.useEffect(()=>{if(!s||!r||i||!l||u||!d||!["network","timeout","reconnect"].includes(d))return;let t=c.current.get(s);t||c.current.set(s,t=new Map);const n=JSON.stringify([e,l]),o=t.get(n)??0;if(o>=3)return;const h=window.setTimeout(()=>{s.isConnected&&a.current.failure?.clientMessageId===l&&!a.current.failure.retrying&&(t.set(n,o+1),a.current.retry())},1e3*2**o);return()=>window.clearTimeout(h)},[e,l,d,u,s,r,i])}(e.daemonId,s,e.clientRef.current,e.connectionReady??Boolean(e.clientRef.current?.isConnected),e.busy,h),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)}}({waitForModelSave:rn.waitForSave,connectionReady:"connected"===R,daemonId:j?.daemonId,revealCreatedSession:t=>{e.setSearch(""),e.setSessionAgentFilter("all"),e.setCollapsedFolders(e=>({...e,[t]:!1}))},messages:be,sessions:X,setSessions:M,clientRef:Ae,activeSessionIdRef:Ne,composerDraftsRef:I,lastHistorySessionIdRef:k,messagesSessionIdRef:te,respondingSessionsRef:C,agent:q,cwd:$,approvalMode:ot,continueSession:at,model:lt,effort:dt,fastMode:ut,activeSessionId:T,activeSession:me,pendingSessions:A,draft:ft,busy:Ot,attachments:ce,t:Mt,setPendingSessions:Ye,setOptimisticSessions:et,setComposerDrafts:mt,setCwd:z,setAgent:_,setActiveSessionId:N,setMessages:ie,setDraft:K,setErrorText:E,setBusy:qt,setAttachments:le,setRespondingSessions:P,clearHistoryLoading:ee,reportLog:Ee,remapLocalSessionState:ae,requestSessions:oe,updateDraft:Ie,appendCachedHistory:pe,ensureCachedHistoryEntry:ge,setCachedMessageDelivery:ve,resolveCachedMessageSession:ye,renderCachedHistory:ne,handleSessionCommandResponse:Yt,appendInfoMessage:Y}),{respondApproval:zn,respondQuestion:Wn,cancelQuestion:Vn,setQuestionChoice:Qn,requestActiveAction:Jn,interruptActiveSession:Zn,retrySessions:ss,updateApprovalMode:rs,setSessionPinned:is,setSessionArchived:os,archiveUndo:as,deleteSession:cs,updatePinned:ls,updateArchived:ds,renameSession:us}=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},o=()=>r&&(e.isSessionSubmitting(n)||e.pendingSessions[n]?.creationPending)?(f({message:d().sessionStarting,notice:!0}),!1):!!function(e){return window.dispatchEvent(new CustomEvent(Fe,{cancelable:!0,detail:e}))}(i)||(f({message:d().saveSessionFiles,notice:!0}),!1);if(!o())return!1;if(!(await u(d().deleteSession(a(t)))))return!1;if(e.clientRef.current!==s||!r&&!s?.isConnected||!o())return!1;e.setBusy(!0),e.setErrorText(null),_e(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(ts(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)),r||await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(c){return e.clientRef.current!==s||f({message:c instanceof Error?c.message:String(c),notice:!0}),!1}finally{_e(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]),o=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]),{setSessionArchived:m,archiveUndo:p}=function(e){const[n,s]=t.useState(null),r=t.useRef(!1),i=t.useRef(e.daemonId);async function o(t,n){const o=e.clientRef.current;if(r.current||e.pendingSessions[t.sessionId]||!o?.isConnected)return;const a=e.daemonId,c=()=>e.clientRef.current===o&&i.current===a;r.current=!0,e.setBusy(!0),e.setErrorText(null);try{if(await o.request({action:"session.setArchived",id:o.makeId("archive"),sessionId:t.sessionId,archived:n}),!c())return;const r=Date.now()+1e4;s(e=>n?{session:{...t,archived:!0},daemonId:a,expiresAt:r}:e?.session.sessionId===t.sessionId?null:e),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(l){c()&&e.setErrorText(l instanceof Error?l.message:String(l))}finally{r.current=!1,e.setBusy(!1)}}i.current=e.daemonId,t.useEffect(()=>s(null),[e.daemonId]),t.useEffect(()=>{if(!n)return;const e=window.setTimeout(()=>s(null),Math.max(0,n.expiresAt-Date.now()));return()=>window.clearTimeout(e)},[n]);const a=n&&n.daemonId===e.daemonId?{session:n.session,expiresAt:n.expiresAt,run:()=>o(n.session,!1)}:void 0;return{setSessionArchived:o,archiveUndo:a}}(e),g=t.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.pinned)},[e.activeSession,h]),v=t.useCallback(async()=>{e.activeSession&&await m(e.activeSession,!e.activeSession.archived)},[e.activeSession,m]),y=t.useCallback(()=>{c("session.interrupt")},[c]),w=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:o,requestActiveAction:c,interruptActiveSession:y,retrySessions:w,updateApprovalMode:l,setSessionPinned:h,setSessionArchived:m,archiveUndo:p,deleteSession:n,updatePinned:g,updateArchived:v,renameSession:b}}({daemonId:j?.daemonId??null,isSessionSubmitting:Fn.submission.has,updateSessionDraft:e.updateSessionDraft,clientRef:Ae,activeSessionIdRef:Ne,composerDraftsRef:I,lastHistorySessionIdRef:k,messagesSessionIdRef:te,respondingSessionsRef:C,activeApproval:ue,activeQuestion:he,activeSession:me,activeSessionId:T,questionAnswers:tt,pendingSessions:A,phase:R,renameTitle:ht,setBusy:qt,setErrorText:E,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:nt,setPendingQueues:F,setActiveSessionId:N,setMessages:ie,setApprovalMode:H,setSessions:M,setPendingSessions:Ye,setComposerDrafts:mt,setDraft:K,setAttachments:le,setDetailsOpen:_t,setRespondingSessions:P,setOptimisticSessions:et,removeCachedHistory:xe,requestSessions:oe,removeCachedMessage:e.removeCachedMessage}),{runArchiveSync:hs,skipArchiveSync:ms,runAdminAction:fs,exportActiveSession:ps,clearPairing:gs,setNotificationsEnabled:vs,connectSavedTarget:ys,forgetSavedTarget:ws,openSessionDetails:bs,editFolderTags:Ss,browseFolder:xs,copyResumeCommand:Is,resumeInTerminal:ks}=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]),r=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));r(t,n),e.setArchiveSyncBusy(null)},[r,e]),o=t.useCallback(()=>{e.pairing?.daemonId&&(n(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[n,e]),f=t.useCallback(async t=>{const n=e.clientRef.current;if(n?.isConnected){if("update"===t){const{version:t,latestVersion:n}=e.daemonMetadata,s=t.includes("-")&&st(t,n)?rt(c(l().language)).description(t,n):d().update;if(!(await u(s)))return}if(("restart"!==t||await u(d().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=st(e.daemonMetadata.version,e.daemonMetadata.latestVersion)?"latest":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,pendingUpdate:{daemonId:e.pairing?.daemonId??"",version:e.daemonMetadata.version}}))}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]),p=t.useCallback(async()=>{if(!e.activeSession)return;const t=function(e,t){return function(e,t){const n=a(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=on(a,s);e&&i.push(`## ${"user"===a.type?s.userMessage:s.assistantMessage}\n\n${e}`)}const o=[`# ${tn(e)||t.sessionId}`,"",`- ${s.agent}: ${sn(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?en(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`}(a(e.activeSession),e.activeSession.sessionId),t),await(navigator.clipboard?.writeText(t).catch(()=>{}))},[e.activeSession,e.messages]),g=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]),v=t.useCallback(async()=>{const t=e.pairingRef.current;await u(d().forget)&&e.pairingRef.current===t&&(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,xt(),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($n),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),y=t.useCallback(t=>{t&&"default"===e.notificationPermission?g():e.updateNotificationSettings({enabled:t})},[e,g]),w=t.useCallback(t=>{e.connectWithPairingRef.current(t,!0)},[e]),b=t.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),S=t.useCallback(t=>{e.setActiveSessionId(t.sessionId),e.setRenameTitle(t.customTitle??t.title??""),e.setDetailsOpen(!0)},[e]),x=t.useCallback((t,n)=>{const s=h(n);e.updateSessionListPreferences(e=>({...e,directoryTags:m(e.directoryTags,t,s)}))},[e]),I=t.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),k=t.useCallback(async t=>{try{const n=Et(t);if(!n)return;await kt(n),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),C=t.useRef(!1);return{runArchiveSync:i,skipArchiveSync:o,runAdminAction:f,exportActiveSession:p,clearPairing:v,setNotificationsEnabled:y,connectSavedTarget:w,forgetSavedTarget:b,openSessionDetails:S,editFolderTags:x,browseFolder:I,copyResumeCommand:k,resumeInTerminal:t.useCallback(async t=>{if(C.current)return;const n=s(),r=e.pairingRef.current?.daemonId;if(r&&n.resumeInTerminal&&n.isLocalDaemon?.(r)){C.current=!0;try{const s=e.clientRef.current;if(!s)throw new Error("Not connected");await s.request({action:"session.release",id:s.makeId("release"),sessionId:t.sessionId,agent:t.agent}),await n.resumeInTerminal({...t,daemonId:r,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(i){e.setErrorText(String(i).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{C.current=!1}}},[e])}}({clientRef:Ae,pairingRef:Oe,connectWithPairingRef:Te,notificationPermissionRef:Pe,intentionalDisconnectRef:Qe,connectionAttemptIdRef:Ge,historyCacheRef:we,historyCacheDaemonIdRef:Le,messagesSessionIdRef:te,lastHistorySessionIdRef:k,displaySessions:X,pairing:j,t:Mt,archiveSyncBusy:Bt,daemonMetadata:J,activeSession:me,messages:be,notificationPermission:Z,savedTargets:yt,setArchiveSyncBusy:Zt,setArchiveSyncStatus:Xt,setSessions:M,setAdmin:$t,setErrorText:E,setNotificationPermission:Ht,setStatusText:Ze,setMessages:ie,setPairing:Xe,setDaemonMetadata:zt,setPhase:Je,setActiveSessionId:N,setRenameTitle:W,setDetailsOpen:_t,setControlTab:Q,updateSessionListPreferences:Rt,requestSessions:oe,refreshDaemonMetadata:je,updateNotificationSettings:Me,saveTargets:Ct,listDirectory:de}),{listSessionModels:Cs,applyToAllSessions:Rs}=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];if("antigravity"===o.agent&&void 0===n)continue;const s={...void 0!==n?{model:n}:{},..."antigravity"!==o.agent&&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,an.applyConfirmedSettings),Es=t.useCallback(async e=>{const t=Ae.current;if(!t?.isConnected)throw new Error(Mt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[Ae,Mt.webSocketNotConnected]),js="denied"===Z||"unsupported"===Z,Ms=Boolean(J.version&&J.latestVersion&&Hn(J.version,J.latestVersion)),As=j?.daemonId,Ts=Boolean(As&&G[As]),_s=Boolean(As&&V[As]),$s=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(ns(s)){case"server-restarting":return e.queueServiceRestarting;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 cn?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),m=!o||Boolean(e.pendingApprovals[o]||e.pendingQuestions[o]),p=!m&&!0===r?.supportsSessionSteer&&!!o&&e.respondingSessions.has(o)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),g=!m&&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:Ps});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&&f({message:e.t.queueSelectionChanged,notice:!0}));if(r?.interrupted?e.setCachedMessageDelivery(s,t.clientMessageId,"interrupted"):e.removeCachedMessage(s,t.clientMessageId),e.updateSessionDraft(s,[ts(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&&f({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:p,canSendNow:g,onAction:async(t,n)=>{if(!o||!r?.isConnected||!("guide"===n?p: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 m=new Set;for(const s of u)e.setCachedMessageDelivery(o,s.clientMessageId,"sending",s);const f=t=>{m.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:Ps}),!l())return;u.forEach(f)}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:Ps}),!l())return;f(e)}}catch(v){if(!l())return;const t=ns(v);let r=!1;for(const n of u)m.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&&"server-restarting"!==t&&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=>!m.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:Ps});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(ts(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;ns(u)&&await d(),l()&&e.activeSessionIdRef.current===o&&e.setErrorText(i(e.t.queueCollectAll,s,u))}finally{a()}}},onCancel:v}}(e);return{...e,setModel:rn.setModel,busy:e.busy||rn.saving,setEffort:an.setEffort,setFastMode:an.setFastMode,queueControls:$s,listSessionModels:Cs,applyToAllSessions:Rs,loadDirectoryGitMetadata:Es,resendMessage:e=>Fn(void 0,(e.images??[]).map(e=>({path:e,name:e.split("/").pop()??e,type:"application/octet-stream",size:0})),Ft(e.content,e.images)),rewindMessage:n,handleSessionCommandResponse:Yt,handleServerMessage:nn,failedSend:gn,dismissFailedSend:An,retryFailedSend:Ln,stagePendingSession:dn,sendDraft:Fn,sendQuickReply:On,respondApproval:zn,respondQuestion:Wn,cancelQuestion:Vn,setQuestionChoice:Qn,requestActiveAction:Jn,interruptActiveSession:Zn,retrySessions:ss,updateApprovalMode:async e=>{an.setApprovalMode(e),me&&!A[me.sessionId]&&await rs(e)},cancelQueuedTurn:$s.onCancel,setSessionPinned:is,setSessionArchived:os,archiveUndo:as,deleteSession:cs,updatePinned:ls,updateArchived:ds,renameSession:us,runArchiveSync:hs,skipArchiveSync:ms,runAdminAction:fs,exportActiveSession:ps,clearPairing:gs,setNotificationsEnabled:vs,connectSavedTarget:ys,forgetSavedTarget:ws,openSessionDetails:bs,editFolderTags:Ss,browseFolder:xs,copyResumeCommand:Is,resumeInTerminal:ks,notificationsBlocked:js,hasDaemonUpdate:Ms,activeDaemonId:As,archiveSynced:Ts,archiveSyncDismissed:_s}}();return n.jsx(Ge,{scopeKey:Be(e.pairing?.daemonId,e.activeSessionId),children:n.jsx(nt,{workspace:e,children:n.jsx(Xc,{workspace:e})})})}},Symbol.toStringTag,{value:"Module"}));export{An as $,D as A,q as B,_ as C,X as D,wc as E,ci as F,se as G,qs as H,re as I,Ir as J,Mn as K,oe as L,Xe as M,tt as N,Jr as O,ye as P,pe as Q,Se as R,Ee as S,Ae as T,Qe as U,un as V,ze as W,De as X,br as Y,jc as Z,bt as _,ma as a,Gr as a0,Kr as a1,xr as a2,Qo as a3,ya as a4,gn as a5,fe as a6,Re as a7,Hs as a8,$s as a9,Lc as aA,bc as aB,Fc as aC,Nn as aD,Oc as aE,_c as aF,$c as aG,Ti as aH,ke as aI,ue as aJ,ae as aK,Yc as aL,Xs as aa,et as ab,Me as ac,Co as ad,Vc as ae,Ro as af,Ea as ag,Aa as ah,Nt as ai,La as aj,or as ak,Pa as al,ne as am,Ie as an,Kc as ao,Ta as ap,Et as aq,le as ar,Xt as as,Na as at,ge as au,P as av,Da as aw,Oa as ax,qa as ay,Fa as az,da as b,U as c,bn as d,kt as e,wn as f,ro as g,$ as h,Eo as i,z as j,ee as k,Oi as l,qi as m,F as n,Q as o,Fi as p,st as q,ia as r,ti as s,rt as t,va as u,we as v,Ia as w,Zt as x,ve as y,Hn as z};