@pi-chamber/web 1.0.7 → 1.0.8-rc.1

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 (212) hide show
  1. package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
  2. package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
  3. package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
  4. package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-C70pbgk-.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
  6. package/dist/assets/FilesView-nFJYEdRw.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
  10. package/dist/assets/{GitView-DD33ngnM.js → GitView-MIDG5RYW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-uNlozeu0.js} +2 -2
  12. package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-CSLsTriz.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
  14. package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
  15. package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
  16. package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
  19. package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
  20. package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
  21. package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-Cb4st5y5.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
  29. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
  33. package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CnzR7kxA.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
  35. package/dist/assets/githubLink-QvaLfNNT.js +10 -0
  36. package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
  37. package/dist/assets/index-D3F4JrPN.css +1 -0
  38. package/dist/assets/{index-ComwtfT4.js → index-DMX9wT1Z.js} +1 -1
  39. package/dist/assets/{main-DoiadX0a.js → main-BW9J3Y72.js} +2 -2
  40. package/dist/assets/main-BirYxac2.js +137 -0
  41. package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-CxmcPur8.js} +2 -2
  42. package/dist/assets/miniChat-BRB11eEs.js +2 -0
  43. package/dist/assets/{mobile-BucKVm1P.js → mobile-DJZYYCuB.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
  49. package/dist/assets/{renderMobileApp-Bp74b_Lo.js → renderMobileApp-B7cT7m5b.js} +3 -3
  50. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
  51. package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
  52. package/dist/assets/selection-BTEdLRVK.js +1 -0
  53. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
  54. package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
  55. package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-CGDpzixf.js → web-components-C_DsTJis.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/registry.json +7 -0
  108. package/plugins/subagents/LICENSE +25 -0
  109. package/plugins/subagents/agents/planner.md +36 -0
  110. package/plugins/subagents/agents/reviewer.md +34 -0
  111. package/plugins/subagents/agents/scout.md +49 -0
  112. package/plugins/subagents/agents/worker.md +23 -0
  113. package/plugins/subagents/extension.js +631 -0
  114. package/plugins/subagents/extension.test.js +295 -0
  115. package/plugins/subagents/package.json +41 -0
  116. package/plugins/visuals/choices.js +168 -0
  117. package/plugins/visuals/extension.js +87 -0
  118. package/plugins/visuals/files.js +74 -0
  119. package/plugins/visuals/package.json +32 -0
  120. package/server/index.js +20 -0
  121. package/server/lib/github/DOCUMENTATION.md +4 -2
  122. package/server/lib/github/gh-cli.js +35 -9
  123. package/server/lib/github/gh-cli.test.js +122 -0
  124. package/server/lib/notifications/pi-notification-watcher.js +3 -0
  125. package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
  126. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  127. package/server/lib/pi/extension-protocol.js +54 -0
  128. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  129. package/server/lib/pi/routes-extension-events.test.js +115 -0
  130. package/server/lib/pi/routes.js +307 -5
  131. package/server/lib/pi/routes.test.js +296 -1
  132. package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
  133. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  134. package/server/lib/pi/session-daemon/extension-config.js +719 -0
  135. package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
  136. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  137. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  138. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  139. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  140. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  141. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  142. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  143. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  144. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  145. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  146. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  147. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  148. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  149. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  150. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  151. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  152. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  153. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  154. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  155. package/server/lib/pi/session-daemon/session-daemon.js +568 -61
  156. package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
  157. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  158. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  159. package/server/lib/pi/session-daemon/supervisor.js +22 -3
  160. package/server/lib/pi/settings-store.js +14 -0
  161. package/server/lib/pi/settings-store.test.js +11 -0
  162. package/server/lib/plugins/DOCUMENTATION.md +186 -0
  163. package/server/lib/plugins/daemon-sync.js +78 -0
  164. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  165. package/server/lib/plugins/daemon-sync.test.js +96 -0
  166. package/server/lib/plugins/impact.js +139 -0
  167. package/server/lib/plugins/impact.test.js +82 -0
  168. package/server/lib/plugins/manifest.js +195 -0
  169. package/server/lib/plugins/manifest.test.js +118 -0
  170. package/server/lib/plugins/registry.js +59 -0
  171. package/server/lib/plugins/routes.js +92 -0
  172. package/server/lib/plugins/routes.test.js +219 -0
  173. package/server/lib/plugins/service.js +161 -0
  174. package/server/lib/plugins/store.js +261 -0
  175. package/server/lib/plugins/store.test.js +188 -0
  176. package/server/lib/plugins/visuals-extension.test.js +237 -0
  177. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  178. package/server/lib/server-browser/browser-tab.js +4 -1
  179. package/server/lib/server-browser/downloads.js +261 -34
  180. package/server/lib/server-browser/downloads.test.js +171 -0
  181. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  182. package/server/lib/server-browser/runtime.js +16 -0
  183. package/server/lib/server-browser/server-browser.js +25 -6
  184. package/server/lib/tunnels/executable-search.js +5 -1
  185. package/server/lib/tunnels/executable-search.test.js +26 -0
  186. package/dist/assets/DiagramView-BB-aZobi.js +0 -1
  187. package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
  188. package/dist/assets/FilesView-DECxN8Z0.js +0 -6
  189. package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
  190. package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
  191. package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
  192. package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
  193. package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
  194. package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
  195. package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
  196. package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
  197. package/dist/assets/SettingsView-DcF-At5E.js +0 -6
  198. package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
  199. package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
  200. package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
  201. package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
  202. package/dist/assets/githubLink-ByPAyFjh.js +0 -10
  203. package/dist/assets/index-BaLCg7tL.css +0 -1
  204. package/dist/assets/main-DyFfbllq.js +0 -137
  205. package/dist/assets/miniChat-Ck6MEZ9Q.js +0 -2
  206. package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
  207. package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
  209. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  210. package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
  211. package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
  212. package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
@@ -1,213 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-sztndhZI.js","assets/vendor-react-Bz1tRBxM.js","assets/document-attachments-CZl9rK1z.js","assets/vendor-fflate-C7GOKjkv.js","assets/vendor-capacitor-status-bar-CWt0OF5t.js","assets/vendor-boot-3SaHYVb1.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-capacitor-app-NbQ-WiPS.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-keyboard-CgrHt8iN.js","assets/permissionStore-zIpxq9Pq.js","assets/vendor-zustand-CXhN0IMY.js","assets/MarkdownRendererImpl-Cn63lAmn.js","assets/vendor-morphdom-B7dS_VPB.js","assets/vendor-beautiful-mermaid-b48gT2g0.js","assets/vendor-elkjs-D1S1RCAO.js","assets/vendor-entities-C3BA0AJP.js","assets/index-I2QYqABE.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-BaLCg7tL.css","assets/markdownCore-DczkEluO.js","assets/vendor-marked-Be78pDn1.js","assets/vendor-dompurify-BGCr_sdL.js","assets/vendor-remend-DcBOpbSu.js","assets/registerCustomTheme-C-h6lsYW.js","assets/themeResolver-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/nativeFileSave-Cp9i5QGd.js","assets/runtimeSurface-CFwnvks_.js","assets/vendor-codemirror-lang-javascript-Bx_FIyZF.js","assets/vendor-lezer-javascript-BH2Etgoy.js","assets/vendor-lezer-lr-HY6Yc0Vr.js","assets/vendor-codemirror-autocomplete-WThuuUAz.js","assets/vendor-codemirror-lang-json-DIvqf9Pb.js","assets/vendor-lezer-json-CE-QUCwM.js","assets/vendor-codemirror-lang-css-D1wpUg3Z.js","assets/vendor-lezer-css-Cb8vp67u.js","assets/vendor-codemirror-lang-html-DbL8oT9H.js","assets/vendor-lezer-html-UQMsUwj-.js","assets/vendor-codemirror-lang-markdown-v3yG2sbf.js","assets/vendor-lezer-markdown-xFL3Evwf.js","assets/vendor-codemirror-lang-python-b-JqEwQy.js","assets/vendor-lezer-python-BNRFWCb0.js","assets/GitHubLinkPicker-BVYdg_e8.js","assets/GitHubListPrimitives-Dlv3tC4d.js","assets/GitHubDetailScaffold-CWsWycRd.js","assets/githubLink-ByPAyFjh.js","assets/ToolOutputDialog-DdMIfrnK.js","assets/JsonTreeView-DpXbUrAl.js","assets/web-components-CGDpzixf.js","assets/computeVirtualFileMetrics-G4csGiKs.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/Virtualizer-okhy9Aq3.js","assets/renderFileWithHighlighter-CYgfbA4F.js","assets/PatchDiff-BklyOEHs.js","assets/VirtualizedFileDiff-BrbPymTL.js","assets/renderDiffWithHighlighter-PL82AR81.js","assets/vendor-diff-C3JhlQdm.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/ToolPartDiffPreview-C6Sm4eVf.js"])))=>i.map(i=>d[i]);
2
- import{av as Vr,a as xt,a1 as lr,aw as wS,ax as SS,ay as Kl,az as Dh,aA as Gl,aB as E5,aC as _5,x as Ie,aD as at,aE as j5,e as Gt,n as de,u as nt,z as Rt,aF as mm,w as T5,V as $r,k as qd,aG as CS,v as zr,b as Y,aH as gm,aI as Wd,h as re,aJ as Xo,J as A5,aK as ym,aL as ft,p as Zt,aa as Yr,aM as Kd,aN as Oh,r as Rr,aO as kS,aP as MS,aQ as IS,S as ES,aR as _S,aS as Wg,aT as jS,aU as TS,aV as AS,A as NS,aW as LS,t as RS,aX as PS,aY as Zu,aZ as Kg,a_ as DS,f as R,ai as OS,a$ as Pr,aj as HS,al as gn,ah as vm,b0 as Zl,b1 as FS,b2 as Gg,am as qn,b3 as BS,b4 as ml,s as gl,b5 as Yu,b6 as Xu,b7 as Zg,b8 as VS,b9 as $S,ak as zS,ba as US,bb as qS,bc as WS,bd as KS,m as GS,be as Yg,bf as ZS,bg as Xg,bh as YS,i as cr,bi as xm,d as XS,bj as JS,bk as QS,bl as eC,bm as Yl,bn as tC,P as nC,bo as Jg,bp as Qg,j as ys,bq as N5,br as Ji,bs as rC,ao as Tt,a0 as sC,bt as oC,X as iC,bu as aC,bv as e0,bw as cC,bx as lC,by as dC,bz as L5,bA as uC,bB as R5,bC as fC,bD as hC,bE as pC,bF as mC,bG as Ju,bH as Qu,bI as Mc,bJ as gC,bK as Hh,bL as Ic,bM as yo,au as yC,as as vC,bN as xC,bO as t0,M as bC,N as wC,O as SC,L as CC,bP as P5,W as kC,Q as js,bQ as MC,bR as IC,bS as EC,bT as Da,bU as yl,U as _C,bV as Fh,a7 as Bh,bW as jC,a8 as TC}from"./index-I2QYqABE.js";import{j as c,aS as AC,aV as NC,aY as LC,aW as RC,aX as PC,aT as DC,aU as OC,bm as HC,bn as D5,bo as FC,bp as BC,b7 as O5,bq as H5,b9 as F5,ba as VC,bb as $C,br as zC,bs as UC,bt as qC,bj as WC,bk as KC,bu as ui,bv as GC,bw as ZC,bx as YC,by as XC,bz as JC,bA as QC,bB as e8,aP as ba,bC as t8,bD as n8,bE as r8,bF as s8,bG as o8,bH as i8,bI as a8,bJ as c8,Q as bn,bK as l8,bL as d8,bM as u8,bN as f8,bO as h8,bP as p8,bQ as m8,bR as g8,bS as y8,bT as v8,bU as x8,bV as b8,aZ as bm,a_ as wa,be as B5,bf as V5,b0 as wm,b1 as Sm,bc as Cm,bd as $5,bg as km,bh as Mm,a$ as w8,bW as z5,bX as U5,bY as q5,bZ as W5,b_ as K5,b$ as Os,c0 as S8,c1 as C8,c2 as k8,b4 as M8,aj as I8,c3 as E8,c4 as _8,E as Pe,S as G5,O as Z5,ap as j8,aq as T8,M as A8,af as N8,c5 as L8,c6 as R8,R as P8,U as n0,c7 as D8,c8 as O8,c9 as Y5,ca as r0,cb as H8,aQ as Ec,cc as X5,bl as F8,cd as B8}from"./vendor-boot-3SaHYVb1.js";import{a as H,R as p}from"./vendor-react-Bz1tRBxM.js";import{c as Et,d as gr,p as Gd}from"./vendor-zustand-CXhN0IMY.js";import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{i as dn}from"./runtimeSurface-CFwnvks_.js";import{saveOrShareFile as V8}from"./nativeFileSave-Cp9i5QGd.js";const AX=()=>{if(!Vr())return!1;const e=wS();return e==="win32"||e==="linux"},NX=async()=>{if(!xt())return!1;try{return await lr("desktop_start_window_drag"),!0}catch{return!1}},$8=24;class vs{constructor(t,n,r){this.parent=t,this.overlay=n,this.depth=r}parent;overlay;depth;static empty(){return new vs(null,new Map,0)}static from(t){return new vs(null,new Map(t),0)}get(t){return this.overlay.has(t)?this.overlay.get(t):this.parent?.get(t)}has(t){return this.overlay.has(t)?!0:this.parent?.has(t)??!1}set(t,n){return this.overlay.set(t,n),this}fork(){return this.depth>=$8?this.compact().fork():new vs(this,new Map,this.depth+1)}compact(){if(!this.parent)return this;const t=new Map;return this.collect(t),new vs(null,t,0)}get size(){return this.parent?[...this.entries()].length:this.overlay.size}*entries(){const t=new Set;yield*this.walk(t)}*values(){for(const[,t]of this.entries())yield t}*keys(){for(const[t]of this.entries())yield t}[Symbol.iterator](){return this.entries()}*walk(t){for(const[n,r]of this.overlay)t.has(n)||(t.add(n),yield[n,r]);this.parent&&(yield*this.parent.walk(t))}collect(t){this.parent?.collect(t);for(const[n,r]of this.overlay)t.set(n,r)}}const Xl=e=>e?vs.from(e):vs.empty(),Jl=()=>({bySession:new Map,lastSequence:new Map}),J5=()=>Xl(),z8=10,U8=50;let q8=0;const Q5=()=>`ext-${Date.now().toString(36)}-${q8+=1}`,eb=(e,t,n=z8)=>{const r=[...e,t];return r.length>n?r.slice(r.length-n):r},zn=(e,t,n)=>{t&&(e.lastMutatedMessageId=e.messages.get(t)?.id??t,e.lastMutationKind=n)},os=e=>{e.parts=e.parts.fork()},W8=(e,t,n)=>{const r=e.bySession.get(t);if(r)return r;const s={sessionId:t,directory:n,lastSequence:-1,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:J5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};return e.bySession.set(t,s),s},Zd=(e,t)=>e.startsWith(`user-${t}-`),K8=250,s0=new WeakMap,G8=(e,t)=>{if(e.size!==t.size)return!1;for(const n of e.list)if(t.get(n.id)!==n)return!1;return!0},Oa=e=>{const t=s0.get(e.messages);if(t&&G8(t,e.messages))return t.list;const n=new Set,r=[];for(const s of e.messages.values())n.has(s.id)||(n.add(s.id),r.push(s));for(let s=1;s<r.length;s+=1){const o=r[s-1],i=r[s];if(!(!o||!i||i.createdAt>=o.createdAt)){r.sort((a,l)=>a.createdAt-l.createdAt);break}}return s0.set(e.messages,{size:e.messages.size,list:r}),r},tb=(e,t,n)=>{if(!t)return;let r,s=Number.POSITIVE_INFINITY;for(const o of Oa(e)){if(o.role!=="user"||o.text!==t||Zd(o.id,e.sessionId))continue;const i=Math.abs(o.createdAt-n);i<=K8&&i<s&&(r=o,s=i)}return r},Z8=(e,t,n)=>{if(n.role==="user"&&Zd(t,e.sessionId)){const r=tb(e,n.text,n.createdAt);if(r){e.messages.set(t,r);return}}e.messages.set(t,n)},Yd=(e,t)=>{if(!t)return;const n=e.messages.get(t)?.id;if(n)return n;if(Zd(t,e.sessionId)){const r=Oa(e);for(let s=r.length-1;s>=0;s-=1){const o=r[s];if(o?.role==="user")return o.id}}return t},Y8=(e,t,n)=>{const r=e.messages.get(t.messageId);if(r)return r;if(t.role==="user"&&Zd(t.messageId,e.sessionId)){const i=tb(e,t.text??"",t.startedAt);if(i)return e.messages.set(t.messageId,i),i}const s=Yd(e,t.parentId),o={id:t.messageId,sessionId:e.sessionId,directory:n,role:t.role,...s?{parentId:s}:{},createdAt:t.startedAt,text:t.role==="user"?t.text??"":"",thinking:"",streaming:t.role==="assistant",...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}};if(e.messages.set(t.messageId,o),t.role==="user"&&t.files?.length){const i=[];for(const a of t.files){const l={id:a.id,index:a.index,type:"file",text:"",streaming:!1,file:{...a.mime?{mime:a.mime}:{},...a.filename?{filename:a.filename}:{},...a.url?{url:a.url}:{}}};e.parts.set(l.id,l),i.push(l.id)}e.partOrder.set(o.id,i)}return o},nb=(e,t,n,r)=>{const s=r??`${t.id}:${n}`,o=e.parts.get(s);if(o)return o;const i={id:s,index:(e.partOrder.get(t.id)??[]).length,type:n,text:"",streaming:!0};e.parts.set(s,i);const a=[...e.partOrder.get(t.id)??[]];return a.includes(i.id)||a.push(i.id),e.partOrder.set(t.id,a),i},X8=(e,t)=>{if(!e.messages.get(t))return{text:"",thinking:""};const r=e.partOrder.get(t)??[];let s="",o="";for(const i of r){const a=e.parts.get(i);a&&(a.type==="text"?s+=a.text:a.type==="thinking"&&(o+=a.text))}return{text:s,thinking:o}},o0=(e,t,n,r)=>{const o=(e.partOrder.get(t)??[]).map(l=>e.parts.get(l)).filter(l=>l?.type===n);if(o.length===0){if(!r)return;const l=e.messages.get(t);if(!l)return;const d=nb(e,l,n);e.parts.set(d.id,{...d,text:r,streaming:!1});return}const[i,...a]=o;if(i){e.parts.set(i.id,{...i,text:r,streaming:!1});for(const l of a)e.parts.set(l.id,{...l,text:"",streaming:!1})}},Im=(e,t)=>{const n=e.messages.get(t);if(n&&n.role==="assistant")return n;const r=Oa(e);for(let o=r.length-1;o>=0;o-=1){const i=r[o];if(i.role==="assistant"&&(i.streaming||i.durationMs===void 0))return e.messages.set(t,i),!e.partOrder.has(t)&&e.partOrder.has(i.id)&&e.partOrder.set(t,e.partOrder.get(i.id)),i}const s=r[r.length-1];if(s&&s.role==="assistant")return e.messages.set(t,s),!e.partOrder.has(t)&&e.partOrder.has(s.id)&&e.partOrder.set(t,e.partOrder.get(s.id)),s},J8=(e,t,n)=>{const r=new Set(e.partOrder.get(t)??[]);if(r.size!==0)for(const[s,o]of e.parts)!o.streaming||!n(o)||!r.has(o.id)&&!r.has(s)||e.parts.set(s,{...o,streaming:!1})},rb=(e,t)=>{J8(e,t,n=>n.type==="thinking")},Q8=256,sb=(e,t)=>{if(!t)return e;if(!e)return t;if(t===e)return e;if(t.startsWith(e))return t;if(e.startsWith(t))return e;const n=Math.min(Q8,e.length,t.length);for(let r=n;r>0;r-=1)if(e.endsWith(t.slice(0,r)))return e+t.slice(r);return e+t},Fo=(e,t,n=Date.now())=>{if(!(typeof e!="number"||!Number.isFinite(e)))return typeof t!="number"||!Number.isFinite(t)?e:e-(t-n)},e6=(e,t)=>{if(t.state==="busy"&&typeof t.command=="string"?e.runningCommand=t.command:delete e.runningCommand,t.state==="retry"){e.lifecycle="retry",e.retry={...t.attempt!==void 0?{attempt:t.attempt}:{},...t.next!==void 0?{next:t.next}:{},...t.message!==void 0?{message:t.message}:{}};return}if(t.state==="busy"&&e.retry){e.lifecycle="retry";return}if(e.lifecycle=t.state,e.retry=void 0,t.state!=="busy"){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[n,r]of e.messages)r.streaming&&e.messages.set(n,{...r,streaming:!1})}},t6=(e,t,n)=>{Y8(e,n,t)},i0=(e,t,n)=>{const r=Im(e,t.messageId);if(!r)return!1;r.streaming=!0,e.streamingMessages.add(r.id),e.streamingMessages.add(t.messageId),n==="text"&&rb(e,r.id);const s=t.partId??`${r.id}:${n}`;let o=e.parts.get(s);if(!o){const a=t.contentIndex;if(typeof a=="number"){const l=[`${r.id}:${n}:${a}`,`${r.id}:${a}`,`${r.id}:${n}`];for(const d of l){const f=e.parts.get(d);if(f&&f.type===n){o=f;break}}if(!o){const d=e.partOrder.get(r.id)??[];for(const f of d){const u=e.parts.get(f);if(u&&u.type===n&&u.index===a){o=u;break}}}}}if(o){if(o.type!==n)return!1;const a={...o,text:sb(o.text,t.delta),streaming:!0};return e.parts.set(o.id,a),s!==o.id&&e.parts.set(s,a),!0}const i=nb(e,r,n,s);return e.parts.set(i.id,{...i,text:t.delta,streaming:!0}),!0},n6=(e,t)=>{const n=Im(e,t.messageId);if(!n)return;const{text:r,thinking:s}=X8(e,n.id);n.text=typeof t.text=="string"?t.text:r,n.thinking=typeof t.thinking=="string"?t.thinking:s,o0(e,n.id,"text",n.text),o0(e,n.id,"thinking",n.thinking),t.continuing===!0&&!t.error?(n.streaming=!0,e.streamingMessages.add(n.id),e.streamingMessages.add(t.messageId)):n.streaming=!1,typeof t.durationMs=="number"?n.durationMs=t.durationMs:typeof n.createdAt=="number"&&n.createdAt>0&&(n.durationMs=Math.max(100,Date.now()-n.createdAt)),t.thinkingLevel&&(n.thinkingLevel=t.thinkingLevel),t.error&&(n.error=t.error),t.usage&&(n.usage=t.usage),t.continuing!==!0&&!t.error&&(e.streamingMessages.delete(n.id),e.streamingMessages.delete(t.messageId))},ef=(e,t,n)=>{const r=e.toolsByCallId.get(n.toolCallId)??n.messageId,s=Im(e,r);if(!s)return!1;rb(e,s.id);const o=Date.now(),i=Fo(n.startedAt,n.serverNow,o),a=Fo(n.endedAt,n.serverNow,o);t!=="end"&&(s.streaming=!0,e.streamingMessages.add(s.id));const l=e.parts.get(n.partId)??Array.from(e.parts.values()).find(h=>h.type==="tool"&&h.tool?.toolCallId===n.toolCallId);if(t==="start"&&!l){const h={id:n.partId,index:(e.partOrder.get(s.id)??[]).length,type:"tool",text:"",streaming:!1,tool:{toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:{},...n.render!==void 0?{render:n.render}:{},state:n.state,...i!==void 0?{startedAt:i}:{}}};e.parts.set(h.id,h);const m=[...e.partOrder.get(s.id)??[]];return m.push(h.id),e.partOrder.set(s.id,m),e.toolsByCallId.set(n.toolCallId,s.id),!0}if(!l||l.type!=="tool")return!1;const d={...l},f=l.tool,u=n.render!==void 0?{...f?.render??{},...n.render}:f?.render;return d.tool={toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:f?.input!==void 0?{input:f.input}:{},...n.output!==void 0?{output:n.output}:f?.output!==void 0?{output:f.output}:{},...u!==void 0?{render:u}:{},...n.error!==void 0?{error:n.error}:f?.error!==void 0?{error:f.error}:{},...n.metadata!==void 0?{metadata:n.metadata}:f?.metadata!==void 0?{metadata:f.metadata}:{},...n.isError!==void 0?{isError:n.isError}:f?.isError!==void 0?{isError:f.isError}:{},state:n.state,...i!==void 0?{startedAt:i}:f?.startedAt!==void 0?{startedAt:f.startedAt}:{},...a!==void 0?{endedAt:a}:f?.endedAt!==void 0?{endedAt:f.endedAt}:{}},t==="end"&&(d.streaming=!1),e.parts.set(d.id,d),!0},r6=(e,t)=>{if(e.lifecycle="interrupted",e.retry=void 0,!!t){for(const n of e.streamingMessages){const r=e.messages.get(n);r&&(r.streaming=!1,r.error={code:"SESSION_INTERRUPTED"})}e.streamingMessages.clear()}},s6=(e,t,n)=>{e.lifecycle="error",e.retry=void 0;const r=Date.now();e.parts=e.parts.fork(),e.partOrder=new Map(e.partOrder);const s=[...e.streamingMessages].map(i=>e.messages.get(i)).filter((i,a,l)=>!!i&&l.indexOf(i)===a),o=s.reduce((i,a)=>!i||a.createdAt>=i.createdAt?a:i,void 0);for(const i of s){i.streaming=!1,i.error=i===o?{code:t,...n?{message:n}:{}}:void 0,i.durationMs===void 0&&i.createdAt>0&&(i.durationMs=Math.max(100,r-i.createdAt));for(const a of e.partOrder.get(i.id)??[]){const l=e.parts.get(a);if(!l)continue;const d=l.tool?.state==="running"||l.tool?.state==="pending";if(!l.streaming&&!d)continue;const f={...l,streaming:!1};d&&f.tool&&(f.tool={...f.tool,state:"error",...n?{error:n}:{},endedAt:f.tool.endedAt??r}),e.parts.set(a,f)}}e.streamingMessages.clear()},o6="pichamber.ui",i6="pichamber.",a6="pichamber-extension-ui",c6=1,l6=new Set(["info","success","warning","error","neutral"]),Wn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,tt=e=>typeof e=="string"?e:void 0,Vh=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ob=e=>{const t=tt(e);return t&&l6.has(t)?t:"neutral"},a0=e=>{if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Wn(n);if(!r)continue;const s=tt(r.label);s!==void 0&&t.push({label:s,value:tt(r.value)??"",...r.tone!==void 0?{tone:ob(r.tone)}:{}})}return t},d6=128,fi=(e,t)=>e.length>t?e.slice(0,t):e,u6=e=>SS(e),c0=e=>{if(!Array.isArray(e))return;const t=[];for(const n of e.slice(0,8)){const r=Wn(n);if(!r)continue;const s=tt(r.label),o=tt(r.command);if(!s||!o||o.includes("/")||o.startsWith("."))continue;const i=Wn(r.promptForArgs),a=i?tt(i.label):void 0,l=i?tt(i.placeholder):void 0;t.push({label:fi(s,d6),command:o,...tt(r.args)!==void 0?{args:u6(tt(r.args))}:{},...r.variant==="outline"||r.variant==="ghost"?{variant:r.variant}:{},...tt(r.icon)!==void 0?{icon:fi(tt(r.icon)??"",64)}:{},...r.disabled===!0?{disabled:!0}:{},...r.loading===!0?{loading:!0}:{},...tt(r.confirm)!==void 0?{confirm:fi(tt(r.confirm)??"",500)}:{},...i?{promptForArgs:{...a!==void 0?{label:fi(a,256)}:{},...l!==void 0?{placeholder:fi(l,256)}:{}}}:{}})}return t.length>0?t:void 0},f6=(e,t)=>{switch(e){case"markdown":{const n=tt(t.body)??tt(t.text);return n!==void 0?{component:"markdown",body:n}:null}case"kv":{const n=a0(t.rows);return n&&n.length>0?{component:"kv",rows:n}:null}case"list":{const n=a0(t.items??t.rows);return n&&n.length>0?{component:"list",items:n}:null}case"table":{if(!Array.isArray(t.columns)||!Array.isArray(t.rows))return null;const n=t.columns.map(s=>tt(s)??"").filter(s=>s.length>0);if(n.length===0)return null;const r=[];for(const s of t.rows.slice(0,200))Array.isArray(s)&&r.push(s.map(o=>tt(o)??"").slice(0,n.length));return r.length>0?{component:"table",columns:n,rows:r}:null}case"progress":{const n=Vh(t.value);if(n===void 0)return null;const r=Vh(t.max)??100;return{component:"progress",value:n,max:r>0?r:100,...tt(t.label)!==void 0?{label:tt(t.label)}:{}}}case"badges":{if(!Array.isArray(t.items))return null;const n=t.items.map(r=>{const s=Wn(r);if(s){const i=tt(s.label);return i?{label:i,tone:ob(s.tone)}:null}const o=tt(r);return o?{label:o,tone:"neutral"}:null}).filter(r=>r!==null).slice(0,24);return n.length>0?{component:"badges",items:n}:null}case"code":{const n=tt(t.code);return n!==void 0?{component:"code",code:n,...tt(t.language)!==void 0?{language:tt(t.language)}:{}}:null}default:return null}},l0=(e,t=2e3)=>e.length>t?`${e.slice(0,t)}…`:e,d0=e=>{if(!Array.isArray(e)||e.length===0)return;const t=[];for(const n of e){if(typeof n!="string")return;t.push(n)}return t},ib=e=>{const t=Wn(e);if(!t)return;const n=d0(t.message);if(!n)return;if(t.messageExpanded===void 0)return{message:n};const r=d0(t.messageExpanded);return r?{message:n,messageExpanded:r}:{message:n}},ab=e=>{const n=e.customType===o6||(e.customType?.startsWith(i6)??!1)?Wn(Wn(e.data)?.ui??null)??Wn(e.data)??Wn(e.details):null;if(n){const s=tt(n.protocol),o=Vh(n.version);if(!(s&&s!==a6)){if(!(o!==void 0&&o!==c6)){const i=tt(n.component)??tt(n.type);if(i){const a=Wn(n.props)??{},l=f6(i,a),d=c0(n.actions);if(l||d){const f=tt(n.title);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...f!==void 0?{title:f.slice(0,256)}:{},component:l??{component:"markdown",body:""},...d?{actions:d}:{}}}}}if(tt(n.title)||tt(n.text)||tt(n.body)){const a=tt(n.text)??tt(n.body)??"";if(a){const l=c0(n.actions);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...tt(n.title)!==void 0?{title:tt(n.title)?.slice(0,256)}:{},component:{component:"markdown",body:a.slice(0,5e3)},...l?{actions:l}:{}}}}}}}}const r=[];if(typeof e.text=="string"&&e.text.trim().length>0&&r.push(e.text.trim()),e.data!==void 0)try{r.push(l0(JSON.stringify(e.data,null,2)))}catch{r.push("[unserializable data]")}else if(e.details!==void 0)try{r.push(l0(JSON.stringify(e.details,null,2)))}catch{r.push("[unserializable details]")}return{kind:"fallback",title:e.customType??"Extension",body:r.join(`
3
-
4
- `)}},h6=(e,t,n,r)=>{if(!r.customType)return;const s={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.data!==void 0?{data:r.data}:{},createdAt:r.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(s.id,s),zn(e,s.id,"structure")},p6=(e,t,n,r)=>{if(!r.customType)return;const s=ib(r.render),o={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.details!==void 0?{details:r.details}:{},...s?{render:s}:{},createdAt:r.createdAt,text:r.text??"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),zn(e,o.id,"structure")},m6=(e,t)=>{e.extensionStatuses=new Map(e.extensionStatuses),typeof t.text=="string"&&t.text.length>0?e.extensionStatuses.set(t.key,t.text):e.extensionStatuses.delete(t.key)},g6=(e,t)=>{e.extensionWidgets=new Map(e.extensionWidgets),Array.isArray(t.lines)&&t.lines.length>0?e.extensionWidgets.set(t.key,{lines:t.lines,placement:t.placement==="belowEditor"?"belowEditor":"aboveEditor"}):e.extensionWidgets.delete(t.key)},y6=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)||(e.extensionDialogs=[...e.extensionDialogs,t])},v6=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)&&(e.extensionDialogs=e.extensionDialogs.filter(n=>n.requestId!==t.requestId))},x6=(e,t)=>{const n=typeof t.id=="string"&&t.id.length>0?t.id:Q5();e.extensionNotices.some(r=>r.id===n)||(e.extensionNotices=eb(e.extensionNotices,{id:n,message:t.message,level:t.level,createdAt:typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)?t.createdAt:Date.now()},U8))},b6=(e,t)=>{t.commands===!0&&(e.extensionCatalogRevision=(e.extensionCatalogRevision??0)+1)},w6=(e,t,n)=>{const r=t.mode==="paste"?"paste":"set",s={text:t.text,mode:r,sequence:n};if(r==="set")e.extensionEditorOps=[s];else{const i=[...e.extensionEditorOps??(e.extensionEditor?[e.extensionEditor]:[]),s];i.length>32&&i.splice(0,i.length-32),e.extensionEditorOps=i}e.extensionEditor=s},S6=(e,t)=>{e.extensionTitle=t.title},C6=(e,t)=>{e.extensionPanels=new Map(e.extensionPanels);const n=t.component!==void 0||t.title!==void 0||t.actions!==void 0;t.removed===!0||!n?e.extensionPanels.delete(t.id):e.extensionPanels.set(t.id,t)},k6=(e,t)=>{e.extensionApps=new Map(e.extensionApps),t.removed===!0||typeof t.html!="string"||t.html.length===0?e.extensionApps.delete(t.appId):e.extensionApps.set(t.appId,t)},M6=(e,t)=>{e.extensionErrors=eb(e.extensionErrors,{id:Q5(),source:t.source,...t.event!==void 0?{event:t.event}:{},message:t.message,createdAt:Date.now()})},I6=(e,t)=>{const n=t.message||void 0,r=t.visible;n===void 0&&r===void 0?delete e.extensionWorking:e.extensionWorking={...n!==void 0?{message:n}:{},...r!==void 0?{visible:r}:{}}},E6=(e,t,n)=>{const r=e.bySession.get(t);if(!r||r.extensionDialogs.findIndex(i=>i.requestId===n)===-1)return e;const o={...r,extensionDialogs:r.extensionDialogs.filter(i=>i.requestId!==n)};return{bySession:new Map(e.bySession).set(t,o),lastSequence:new Map(e.lastSequence)}},cb=e=>({surfaceId:e.surfaceId,...e.parentId?{parentId:e.parentId}:{},title:e.title,mode:e.mode,capturing:e.capturing,hidden:e.hidden,focused:e.focused,z:e.z,...e.blocked?{blocked:{...e.blocked}}:{}}),lb=e=>({version:e.version,lines:e.lines,cells:e.lines.map((t,n)=>e.cells?.[n]),cursor:e.cursor,layout:e.layout,visible:e.visible,columns:e.columns,screenColumns:e.screenColumns,rows:e.rows}),db=e=>Array.isArray(e.lines),ub=e=>{if(!Array.isArray(e)||e.length===0)return;const t=new Map;for(const n of e){if(typeof n?.surfaceId!="string"||n.surfaceId.length===0)continue;const r=n.frame&&n.frame.surfaceId===n.surfaceId&&db(n.frame)?lb(n.frame):null;t.set(n.surfaceId,{...cb(n),frame:r})}return t.size>0?t:void 0},vl=(e,t)=>{const n=new Map(e.extensionSurfaces??[]);n.set(t.surfaceId,t),e.extensionSurfaces=n},_6=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);vl(e,{...cb(t),frame:n?.frame??null,...n?.stale?{stale:!0}:{}})},j6=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);if(!n||n.frame&&t.version<=n.frame.version)return;if(db(t)){vl(e,{...n,frame:lb(t),stale:!1});return}if(!n.frame||n.frame.version!==t.base){n.stale||vl(e,{...n,stale:!0});return}const r=n.frame.lines.slice(0,t.length),s=n.frame.cells.slice(0,t.length);for(;r.length<t.length;)r.push(""),s.push(void 0);for(const o of t.changes)r[o.index]=o.line,s[o.index]=o.cells;vl(e,{...n,frame:{version:t.version,lines:r,cells:s,cursor:t.cursor,layout:t.layout,visible:t.visible,columns:t.columns,screenColumns:t.screenColumns,rows:t.rows},stale:!1})},fb=(e,t)=>{if(!e.extensionSurfaces?.has(t.surfaceId))return;const n=new Map(e.extensionSurfaces);n.delete(t.surfaceId),n.size===0?delete e.extensionSurfaces:e.extensionSurfaces=n},T6=(e,t,n)=>{const r=e.bySession.get(t);if(!r?.extensionSurfaces?.has(n))return e;const s={...r};return fb(s,{surfaceId:n}),{bySession:new Map(e.bySession).set(t,s),lastSequence:new Map(e.lastSequence)}},A6=new Set(["running","completed","cancelled","failed"]),Ql=e=>e.length>Dh?e.slice(-Dh):e,hb=e=>{const t=e;return!!t&&typeof t.id=="string"&&t.id.length>0&&typeof t.command=="string"&&A6.has(t.phase)&&typeof t.startedAt=="number"},N6=e=>{if(Array.isArray(e))return e.filter(hb).map(t=>typeof t.output=="string"&&t.output.length>Dh?{...t,output:Ql(t.output)}:t)},pb=(e,t)=>{const n=N6(t);if(n){if(n.length===0){e.bashExecutions?.length&&delete e.bashExecutions;return}e.bashExecutions=n}},L6=(e,t)=>{if(!hb(t))return;const n=e.bashExecutions??[],r=n.findIndex(l=>l.id===t.id),s=r>=0?n[r]:void 0,o=typeof t.output=="string"?Ql(t.output):s?.output,i={...t,...o?{output:o}:{}};o||delete i.output;const a=[...n];r>=0?a[r]=i:a.push(i),e.bashExecutions=a},R6=(e,t)=>{const n=e.bashExecutions;if(!n)return;const r=n.findIndex(a=>a.id===t.id);if(r<0)return;const s=n[r],o=t.reset===!0?Ql(t.output):Ql(`${s.output??""}${t.delta}`);if(o===(s.output??""))return;const i=[...n];i[r]={...s,output:o},e.bashExecutions=i},P6=(e,t,n,r)=>{if(r.id&&e.bashExecutions?.some(i=>i.id===r.id)){const i=e.bashExecutions.filter(a=>a.id!==r.id);i.length>0?e.bashExecutions=i:delete e.bashExecutions}const{message:s}=r;if(!s||typeof s.id!="string"||s.customType!==Kl)return;const o={id:s.id,sessionId:n,directory:t,role:"extension",customType:Kl,details:s.details,createdAt:s.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),zn(e,o.id,"structure")},jr=["off","minimal","low","medium","high","xhigh","max"],D6={off:"Off",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},Ht=e=>e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",ln=e=>Ht(e)?e:null,O6=(e,t)=>{const n=e.filter(Ht),r=n.length>0?n:["off"];if(t&&r.includes(t))return t;const s=jr.indexOf(t);if(s===-1)return r[0];for(let o=s+1;o<jr.length;o+=1)if(r.includes(jr[o]))return jr[o];for(let o=s-1;o>=0;o-=1)if(r.includes(jr[o]))return jr[o];return r[0]},Em=e=>{if(Array.isArray(e?.thinkingLevels)&&e.thinkingLevels.length>0){const t=e.thinkingLevels,n=jr.filter(r=>t.includes(r));return n.length>0?n:["off"]}return e?.reasoning===!0||e?.supportsThinking===!0?jr.filter(t=>t!=="xhigh"&&t!=="max"):["off"]},Xd=e=>e.some(t=>t!=="off"&&Ht(t)),_m=e=>{const t=Em(e);return Xd(t)?t:[]},Ur=e=>e?Ht(e)?D6[e]:`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Default",H6=(e,t)=>t<=1||!Number.isFinite(e)?0:Math.min(t-1,Math.max(0,Math.round(e*(t-1)))),jm=(e,t,n)=>{const r=e.filter(Ht);if(!Xd(r))return;const s=[void 0,...r],o=Ht(t)&&r.includes(t)?t:void 0,i=s.indexOf(o);return s[(i+n+s.length)%s.length]},mb=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return`${t}/${n}`},gb=(e,t)=>{if(!(!t||!e))return ln(e[t])??void 0},u0=e=>{if(e.thinking)return e.thinking;const t=mb(e.model);return gb(e.defaultThinkingByModel,t)??ln(e.defaultThinking)??void 0},_c=e=>{const t=Em(e);if(!Xd(t))return;const n=mb({providerId:e.providerId,modelId:e.modelId}),r=gb(e.defaultThinkingByModel,n)??(Ht(e.previousThinking)?e.previousThinking:void 0)??ln(e.defaultThinking)??void 0;if(r)return O6(t,r)},f0=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return{providerId:t,modelId:n}},F6=e=>{let t;if(e.messages)for(const s of e.messages){if(s.role!=="assistant")continue;const o=f0(s.model),i=ln(s.thinkingLevel)??void 0;if(!o&&!i)continue;const a=typeof s.createdAt=="number"&&Number.isFinite(s.createdAt)?s.createdAt:0;(!t||a>=t.createdAt)&&(t={createdAt:a,...o?{model:o}:{},...i?{thinkingLevel:i}:{}})}const n=t?.model??f0(e.model),r=t?.thinkingLevel??ln(e.thinking)??void 0;return{...n?{model:n}:{},...r?{thinking:r}:{}}},h0=new WeakMap,B6=e=>{const t=h0.get(e);if(t)return t;const n={id:e.id,type:e.type,text:e.text,streaming:e.streaming,...e.tool?{tool:e.tool}:{},...e.attachment?{attachment:e.attachment}:{},...e.file?{file:e.file}:{}};return h0.set(e,n),n},V6=(e,t)=>{const n=new Set,r=new Set;for(let s=t.length-1;s>=0;s-=1){const o=t[s];if(!o||o.role!=="assistant")continue;const i=Yd(e,o.parentId);if(!i)continue;const a=!!(o.text||o.thinking||(e.partOrder.get(o.id)?.length??0)>0);if(o.error&&!a&&n.has(i)){r.add(o.id);continue}o.error||n.add(i)}return r},$6=(e,t,n,r)=>n.id===t.id&&n.role===t.role&&n.parentId===Yd(e,t.parentId)&&n.text===t.text&&n.thinking===t.thinking&&n.render===t.render&&n.streaming===t.streaming&&n.createdAt===t.createdAt&&n.durationMs===t.durationMs&&n.error===t.error&&n.model===t.model&&n.thinkingLevel===t.thinkingLevel&&n.usage===t.usage&&n.parts.length===r.length&&n.parts.every((s,o)=>s===r[o]),z6=(e,t,n)=>{const r=e.partOrder.get(t.id)??[],s=[];for(const i of r){const a=e.parts.get(i);a&&s.push(B6(a))}if(n&&$6(e,t,n,s))return n;const o=Yd(e,t.parentId);return{id:t.id,role:t.role,...o?{parentId:o}:{},...t.customType!==void 0?{customType:t.customType}:{},...t.data!==void 0?{data:t.data}:{},...t.details!==void 0?{details:t.details}:{},...t.render!==void 0?{render:t.render}:{},text:t.text,thinking:t.thinking,streaming:t.streaming,createdAt:t.createdAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.error?{error:t.error}:{},...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{},...t.usage?{usage:t.usage}:{},parts:s}},yb=(e,t)=>{const n=Oa(e),r=V6(e,n),s=t?new Map(t.projection.messages.map(i=>[i.id,i])):null,o=[];for(const i of n)r.has(i.id)||o.push(z6(e,i,s?.get(i.id)));return t&&t.projection.sessionId===e.sessionId&&t.projection.directory===e.directory&&t.projection.lifecycle===e.lifecycle&&t.projection.model===e.model&&t.projection.thinking===e.thinking&&t.projection.queue.steering===e.queue.steering&&t.projection.queue.followUp===e.queue.followUp&&t.projection.messages.length===o.length&&t.projection.messages.every((i,a)=>i===o[a])?t.projection:{sessionId:e.sessionId,directory:e.directory,lifecycle:e.lifecycle,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},queue:{...e.queue},messages:o}},vb=(e,t)=>{if(delete e.runningCommand,t?.lifecycle==="busy"&&t.command&&t.isStreaming!==!0){if(e.lifecycle="busy",e.retry=void 0,e.runningCommand=t.command,t.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}const n=[],r=[];for(const[a,l]of e.parts){const d=l.tool?.state;if(l.type!=="tool"||d!=="running"&&d!=="pending")continue;r.push(a);const f=l.tool?.toolCallId?e.toolsByCallId.get(l.tool.toolCallId):void 0;f&&n.push(f)}if(!(t?.isStreaming===!0||t?.lifecycle==="busy"||t?.lifecycle==="retry"||t?.inferFromRunningTools===!0&&n.length>0)){if(e.retry=void 0,t?.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}e.lifecycle=t?.lifecycle==="retry"?"retry":"busy",e.retry=e.lifecycle==="retry"?t?.retry:void 0,e.streamingMessages=new Set(e.streamingMessages);for(const a of r){const l=e.parts.get(a);l&&e.parts.set(a,{...l,streaming:!0})}let o=n[n.length-1];if(!o){const a=Oa(e);for(let l=a.length-1;l>=0;l-=1){const d=a[l];if(d?.role==="assistant"){o=d.id;break}}}if(!o)return;const i=e.messages.get(o);!i||i.role!=="assistant"||(e.messages.set(o,{...i,streaming:!0}),e.streamingMessages.add(o))},ed=e=>{const t=Jl(),n=Date.now(),r=W8(t,e.session.id,e.session.directory);r.lastSequence=e.lastSequence,r.hasMoreBefore=e.hasMoreBefore===!0,r.beforeCursor=e.hasMoreBefore===!0&&typeof e.beforeCursor=="string"?e.beforeCursor:void 0,Array.isArray(e.extensionStatuses)&&(r.extensionStatuses=new Map(e.extensionStatuses.map(i=>[i.key,i.text]))),Array.isArray(e.extensionWidgets)&&(r.extensionWidgets=new Map(e.extensionWidgets.map(i=>[i.key,{lines:i.lines,placement:i.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(e.extensionDialogs)&&(r.extensionDialogs=e.extensionDialogs.filter(i=>typeof i.requestId=="string"&&typeof i.method=="string"&&typeof i.title=="string")),Array.isArray(e.extensionPanels)&&(r.extensionPanels=new Map(e.extensionPanels.filter(i=>typeof i?.id=="string"&&i.id.length>0).map(i=>[i.id,i]))),Array.isArray(e.extensionApps)&&(r.extensionApps=new Map(e.extensionApps.filter(i=>typeof i?.appId=="string"&&i.appId.length>0).map(i=>[i.appId,i]))),r.extensionTitle=e.extensionTitle,e.extensionWorking&&(r.extensionWorking={...e.extensionWorking}),e.extensionDraftTracked===!0&&(r.extensionDraftTracked=!0);const s=ub(e.extensionSurfaces);s&&(r.extensionSurfaces=s),pb(r,e.bashExecutions);for(const{message:i,parts:a}of e.messages??[]){const l=i.role==="extension",d=l?ib(i.render):void 0,f={id:i.id,sessionId:e.session.id,directory:e.session.directory,role:i.role,...l&&i.customType?{customType:i.customType}:{},...l&&i.data!==void 0?{data:i.data}:{},...l&&i.details!==void 0?{details:i.details}:{},...d?{render:d}:{},...i.parentId?{parentId:i.parentId}:{},createdAt:i.createdAt,text:i.text??"",thinking:i.role==="assistant"?i.thinking??"":"",streaming:!1,...i.role==="assistant"&&i.durationMs!==void 0?{durationMs:i.durationMs}:{},...i.role==="assistant"&&i.error?{error:i.error}:{},...i.role==="assistant"&&i.model?{model:i.model}:{},...i.role==="assistant"&&i.thinkingLevel?{thinkingLevel:i.thinkingLevel}:{},...i.role==="assistant"&&i.usage?{usage:i.usage}:{}};r.messages.set(i.id,f);const u=[];for(const h of a){const m=h.type==="tool"?Fo(h.startedAt,e.serverNow,n):void 0,g=h.type==="tool"?Fo(h.endedAt,e.serverNow,n):void 0,x={id:h.id,index:h.index,type:h.type,text:h.text??"",streaming:!1,...h.type==="tool"?{tool:{toolCallId:h.toolCallId??h.id,name:h.name??"unknown",...h.input!==void 0?{input:h.input}:{},...h.output!==void 0?{output:h.output}:{},...h.render!==void 0?{render:h.render}:{},...typeof h.error=="string"?{error:h.error}:{},...h.metadata!==void 0?{metadata:h.metadata}:{},...h.isError!==void 0?{isError:h.isError}:{},state:h.state??"completed",...m!==void 0?{startedAt:m}:{},...g!==void 0?{endedAt:g}:{}}}:{},...h.type==="attachment"&&h.attachment?{attachment:h.attachment}:{},...h.type==="file"?{file:{...typeof h.mime=="string"?{mime:h.mime}:{},...typeof h.filename=="string"?{filename:h.filename}:{},...typeof h.url=="string"?{url:h.url}:{}}}:{}};r.parts.set(h.id,x),u.push(h.id),h.type==="tool"&&h.toolCallId&&r.toolsByCallId.set(h.toolCallId,i.id)}r.partOrder.set(i.id,u)}const o=F6({model:e.session.model,thinking:e.session.thinking,messages:r.messages.values()});return o.model&&(r.model=o.model),o.thinking&&(r.thinking=o.thinking),r.compaction=e.compaction,vb(r,{...e.isStreaming!==void 0?{isStreaming:e.isStreaming}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.command?{command:e.command}:{},...e.retry?{retry:e.retry}:{},inferFromRunningTools:!0}),t.lastSequence.set(e.session.id,e.lastSequence),{state:t,session:r}},tf=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.sequence<=n)return{state:e,didApply:!1};if(t.name==="session.deleted"){const i=new Map(e.bySession);i.delete(t.sessionId);const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:i,lastSequence:a},didApply:!0,sessionId:t.sessionId}}if(t.name==="session.openUrl"||t.name==="session.archive"){const i=new Map(e.lastSequence);return i.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:i},didApply:!0,sessionId:t.sessionId}}const r=e.bySession.get(t.sessionId),s=r?{...r,lastSequence:t.sequence,...t.name==="session.lifecycle"?{lifecycle:t.payload.state}:{},...t.name==="session.queue"?{queue:{...t.payload}}:{},...t.name==="session.model"?{model:t.payload.model}:{},...t.name==="session.thinking"?{thinking:t.payload.thinking}:{}}:{sessionId:t.sessionId,directory:t.directory,lastSequence:t.sequence,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:J5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};switch(t.name){case"session.snapshot":if(t.payload?.snapshot){if(s.lifecycle=t.payload.snapshot.lifecycle??(t.payload.snapshot.isStreaming?"busy":"idle"),s.retry=s.lifecycle==="retry"?t.payload.snapshot.retry:void 0,s.compaction=t.payload.snapshot.compaction,t.payload.snapshot.model&&(s.model=t.payload.snapshot.model),t.payload.snapshot.thinking&&(s.thinking=t.payload.snapshot.thinking),t.payload.snapshot.queue&&(s.queue={...t.payload.snapshot.queue}),Array.isArray(t.payload.snapshot.extensionStatuses)&&(s.extensionStatuses=new Map(t.payload.snapshot.extensionStatuses.map(a=>[a.key,a.text]))),Array.isArray(t.payload.snapshot.extensionWidgets)&&(s.extensionWidgets=new Map(t.payload.snapshot.extensionWidgets.map(a=>[a.key,{lines:a.lines,placement:a.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(t.payload.snapshot.extensionDialogs)&&(s.extensionDialogs=t.payload.snapshot.extensionDialogs.filter(a=>typeof a.requestId=="string"&&typeof a.method=="string"&&typeof a.title=="string")),Array.isArray(t.payload.snapshot.extensionPanels)){const a=new Map;for(const l of t.payload.snapshot.extensionPanels)typeof l?.id=="string"&&l.id.length>0&&a.set(l.id,l);s.extensionPanels=a}if(Array.isArray(t.payload.snapshot.extensionApps)){const a=new Map;for(const l of t.payload.snapshot.extensionApps)typeof l?.appId=="string"&&l.appId.length>0&&a.set(l.appId,l);s.extensionApps=a}s.extensionTitle=t.payload.snapshot.extensionTitle,t.payload.snapshot.extensionWorking?s.extensionWorking={...t.payload.snapshot.extensionWorking}:delete s.extensionWorking,t.payload.snapshot.extensionDraftTracked===!0?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;const i=ub(t.payload.snapshot.extensionSurfaces);i?s.extensionSurfaces=i:delete s.extensionSurfaces,pb(s,t.payload.snapshot.bashExecutions),vb(s,{isStreaming:t.payload.snapshot.isStreaming,lifecycle:s.lifecycle,...t.payload.snapshot.command?{command:t.payload.snapshot.command}:{},...t.payload.snapshot.retry?{retry:t.payload.snapshot.retry}:{},settleWhenIdle:!0})}break;case"session.lifecycle":e6(s,t.payload);break;case"assistant.message.start":s.lifecycle=s.retry?"retry":"busy",delete s.runningCommand,s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages),t.payload.files?.length&&(os(s),s.partOrder=new Map(s.partOrder)),t6(s,t.directory,t.payload),t.payload.role==="assistant"&&s.streamingMessages.add(t.payload.messageId),zn(s,t.payload.messageId,"structure");break;case"assistant.message.delta":os(s),i0(s,t.payload,"text")&&(s.lifecycle="busy",s.retry=void 0),zn(s,t.payload.messageId,"part");break;case"assistant.message.end":s.messages=new Map(s.messages),os(s),s.partOrder=new Map(s.partOrder),s.streamingMessages=new Set(s.streamingMessages),n6(s,t.payload),zn(s,t.payload.messageId,"structure");break;case"assistant.thinking.delta":os(s),i0(s,t.payload,"thinking")&&(s.lifecycle="busy",s.retry=void 0),zn(s,t.payload.messageId,"part");break;case"session.tool.start":os(s),s.partOrder=new Map(s.partOrder),s.toolsByCallId=new Map(s.toolsByCallId),ef(s,"start",t.payload)&&(s.lifecycle="busy",s.retry=void 0),zn(s,t.payload.messageId,"part");break;case"session.tool.update":os(s),ef(s,"update",t.payload)&&(s.lifecycle="busy",s.retry=void 0),zn(s,t.payload.messageId,"part");break;case"session.tool.end":os(s),ef(s,"end",t.payload)&&(s.lifecycle="busy",s.retry=void 0),zn(s,t.payload.messageId,"part");break;case"session.queue":s.queue={steering:t.payload.steering,followUp:t.payload.followUp};break;case"session.model":s.model=t.payload.model;break;case"session.thinking":s.thinking=t.payload.thinking;break;case"session.compaction":s.compaction={...t.payload};break;case"session.updated":break;case"session.input":break;case"session.bash":L6(s,t.payload.bash);break;case"session.bash.output":R6(s,t.payload);break;case"session.bash.recorded":P6(s,t.directory,t.sessionId,t.payload);break;case"session.tree.updated":s.sessionTreeRevision=(s.sessionTreeRevision??0)+1;break;case"session.error":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}s6(s,t.payload.code,t.payload.message);break;case"session.interrupted":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}r6(s,t.payload.streaming);break;case"extension.entry":h6(s,t.directory,t.sessionId,t.payload);break;case"extension.message":p6(s,t.directory,t.sessionId,t.payload);break;case"extension.notify":{const i=typeof t.payload.id=="string"&&t.payload.id.length>0?t.payload.id:void 0;if(i&&s.extensionNotices.some(a=>a.id===i)){const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:a},didApply:!0,sessionId:t.sessionId}}x6(s,t.payload);break}case"extension.catalog":b6(s,t.payload);break;case"extension.editor":w6(s,t.payload,t.sequence);break;case"extension.title":S6(s,t.payload);break;case"extension.status":m6(s,t.payload);break;case"extension.widget":g6(s,t.payload);break;case"extension.dialog":y6(s,t.payload);break;case"extension.dialog.dismiss":v6(s,t.payload);break;case"extension.ui":C6(s,t.payload);break;case"extension.app":k6(s,t.payload);break;case"extension.working":I6(s,t.payload);break;case"extension.editor.track":t.payload.enabled?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;break;case"extension.custom":_6(s,t.payload);break;case"extension.custom.frame":j6(s,t.payload);break;case"extension.custom.dismiss":fb(s,t.payload);break;case"extension.error":M6(s,t.payload);break}const o={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return o.bySession.set(t.sessionId,s),o.lastSequence.set(t.sessionId,t.sequence),{state:o,didApply:!0,sessionId:t.sessionId}},U6={fetchHealth:E5,createStream:Gl},nf=e=>e instanceof at?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},q6=async(e,t=U6)=>{const n={phase:"idle",reducerState:{bySession:new Map,lastSequence:new Map},lastSequence:new Map,stream:null,errors:[],health:{state:"pending"}},r=async a=>e.retry?e.retry(a):a();n.phase="runtime-probe";const s=e.initialHealth??await r(()=>t.fetchHealth(e.signal,e.runtimeKey));if(s.state==="ready"){if(!(s.capabilities.includes(_5)&&typeof s.streamEpoch=="string"&&s.streamEpoch.length>0)){const l={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."};return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:l},n.phase="failed",n.errors.push({phase:"runtime-probe",error:l}),n}n.health={state:"ready",protocolVersion:s.protocolVersion,capabilities:[...s.capabilities],streamEpoch:s.streamEpoch},n.streamEpoch=s.streamEpoch}else return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:{code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}}},n.phase="failed",n.errors.push({phase:"runtime-probe",error:n.health.error}),n;n.phase="session-list";const o=a=>{for(const l of a)n.lastSequence.set(l.session.id,-1)};if(e.initialSessions)o(e.initialSessions);else try{const a=await r(()=>Ie.listSessions({...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session list omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");o(a.sessions)}catch(a){if(n.errors.push({phase:"session-list",error:nf(a)}),a instanceof at&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}if(e.selectedSessionId){n.phase="session-hydrate";try{const a=e.initialDetail??await r(()=>Ie.getSession(e.selectedSessionId,{...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new at("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");n.selectedSessionTiming={sessionId:a.session.id,isStreaming:a.isStreaming,lifecycle:a.lifecycle,...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{}};const{state:l}=ed(a);n.reducerState=l,n.lastSequence.set(a.session.id,a.lastSequence)}catch(a){if(n.errors.push({phase:"session-hydrate",error:nf(a)}),a instanceof at&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}}n.phase="stream-attach";try{const a=e.selectedSessionId?n.lastSequence.get(e.selectedSessionId):e.fromSequence,l=t.createStream({onEvent:e.onEvent,onDisconnect:d=>e.onStreamDisconnect?.(d),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:d=>e.onEpochChange?.(d),onAuthRequired:()=>e.onAuthRequired?.()},{...typeof a=="number"&&a>=0?{fromSequence:a}:{},...n.streamEpoch?{streamEpoch:n.streamEpoch}:{},...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal});n.stream=l}catch(a){n.errors.push({phase:"stream-attach",error:nf(a)})}const i=n.errors.some(a=>a.phase==="runtime-probe");return n.phase=i?"failed":"ready",n};let p0=null;const xb=()=>(p0??=j5(),p0),W6=e=>({sessionId:e.sessionId,directory:e.directory,isStreaming:e.isStreaming,lastSequence:e.lastSequence,queue:e.queue??{steering:0,followUp:0},...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.compaction?{compaction:e.compaction}:{},...e.lastText?{lastText:e.lastText}:{},...e.lastThinking?{lastThinking:e.lastThinking}:{},...e.lastToolPart?{lastToolPart:e.lastToolPart}:{},lifecycle:e.lifecycle}),K6=()=>({bySession:new Map,lastSequence:new Map}),G6=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.lastSequence<=n)return{state:e,didUpdate:!1};const r={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return r.bySession.set(t.sessionId,W6(t)),r.lastSequence.set(t.sessionId,t.lastSequence),{state:r,didUpdate:!0}},Z6={fetchHealth:E5,createStream:Gl},m0=e=>e instanceof at?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},Y6=async(e,t=Z6)=>{const n={phase:"idle",snapshotState:K6(),reducerState:{bySession:new Map,lastSequence:new Map},stream:null,lastSequence:e.lastKnownSequence??-1},r=async a=>e.retry?e.retry(a):a();n.phase="health-check";const s=await r(()=>t.fetchHealth(e.signal,e.runtimeKey,{fresh:!0}));if(s.state!=="ready")return n.phase="unavailable",n.error={code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}},n;if(!s.capabilities.includes(_5)||typeof s.streamEpoch!="string"||s.streamEpoch.length===0)return n.phase="failed",n.error={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."},n;n.epoch=s.streamEpoch;const o=typeof e.streamEpoch=="string"&&e.streamEpoch.length>0?e.streamEpoch:null,i=o!==null&&o!==n.epoch;i&&(n.epochChanged=!0),n.phase="snapshot-fetch";try{const a=await r(()=>Ie.getSession(e.sessionId,{directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new at("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.epoch)throw new at("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");const l=ed(a);n.reducerState=l.state,(a.lifecycle==="busy"||a.lifecycle==="retry")&&Number.isFinite(a.runStartedAt)&&(n.runStartedAt=a.runStartedAt,Number.isFinite(a.serverNow)&&(n.serverNow=a.serverNow));const d={protocolVersion:1,kind:"event",name:"session.snapshot",sequence:a.lastSequence,sessionId:a.session.id,directory:a.session.directory,payload:{snapshot:{sessionId:a.session.id,directory:a.session.directory,lastSequence:a.lastSequence,isStreaming:a.isStreaming===!0,queue:{steering:0,followUp:0},lifecycle:a.lifecycle??(a.isStreaming?"busy":"idle"),...a.command?{command:a.command}:{},...a.retry?{retry:a.retry}:{},...a.compaction?{compaction:a.compaction}:{},...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{},...a.session.model?{model:a.session.model}:{},...a.session.thinking?{thinking:a.session.thinking}:{}}}},f=G6(n.snapshotState,d.payload.snapshot);n.snapshotState=f.state;const u=e.lastKnownSequence??-1;n.lastSequence=i?a.lastSequence:o!==null&&u>=0?u:Math.max(u,a.lastSequence)}catch(a){const l=m0(a);return l.code==="INVALID_SESSION",n.phase="failed",n.error=l,n}n.phase="stream-attach";try{n.stream=t.createStream({onEvent:e.onEvent,onDisconnect:a=>e.onStreamDisconnect?.(a),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:a=>e.onEpochChange?.(a),onAuthRequired:()=>e.onAuthRequired?.()},{fromSequence:n.lastSequence,streamEpoch:n.epoch,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal})}catch(a){return n.phase="failed",n.error=m0(a),n}return n.phase="ready",n},X6=new Set(["assistant.message.delta","assistant.thinking.delta","session.tool.update"]),J6=e=>X6.has(e.name),td=e=>e.name==="assistant.message.delta"||e.name==="assistant.thinking.delta"?e:null,Q6=(e,t)=>{const n=td(e),r=td(t);return!n||!r||n.name!==r.name||n.sessionId!==r.sessionId?!1:n.payload.messageId===r.payload.messageId&&n.payload.contentIndex===r.payload.contentIndex&&(n.payload.partId??"")===(r.payload.partId??"")},ek=(e,t)=>{const n=td(e),r=td(t);return!n||!r||n.name!==r.name?t:{...r,payload:{...r.payload,delta:sb(n.payload.delta,r.payload.delta)}}},tk=(e,t)=>e.name==="session.tool.update"&&t.name==="session.tool.update"&&e.sessionId===t.sessionId&&e.payload.toolCallId===t.payload.toolCallId&&e.payload.partId===t.payload.partId&&e.payload.messageId===t.payload.messageId,rf=e=>{const t=[];for(const n of e){const r=t[t.length-1];r&&Q6(r,n)?t[t.length-1]=ek(r,n):r&&tk(r,n)?t[t.length-1]=n:t.push(n)}return t};class nk{constructor(t){this.publish=t}publish;buffer=[];scheduled="none";generation=0;rafId=0;push(t){if(!J6(t)){const n=this.takeBuffer();this.publish(rf([...n,t]));return}this.buffer.push(t),this.schedule()}flush(){const t=this.takeBuffer();t.length!==0&&this.publish(rf(t))}dispose(){this.flush()}takeBuffer(){if(this.generation+=1,this.scheduled="none",this.rafId&&typeof globalThis.cancelAnimationFrame=="function"&&globalThis.cancelAnimationFrame(this.rafId),this.rafId=0,this.buffer.length===0)return[];const t=this.buffer;return this.buffer=[],t}schedule(){if(this.scheduled!=="none")return;const t=++this.generation,n=()=>{if(t!==this.generation)return;this.scheduled="none",this.rafId=0;const r=this.buffer;this.buffer=[],r.length!==0&&this.publish(rf(r))};if(typeof globalThis.requestAnimationFrame=="function"){this.scheduled="frame",this.rafId=globalThis.requestAnimationFrame(n);return}this.scheduled="microtask",queueMicrotask(n)}}const rk=[{name:"undo",description:"Undo the last message"},{name:"redo",description:"Redo previously undone messages"},{name:"timeline",description:"Open the conversation timeline"},{name:"compact",description:"Compress session history using AI to reduce context size"}],Mr=()=>rk.map(e=>({id:`system:${e.name}`,name:e.name,invocationName:e.name,source:"system",description:e.description})),sk=e=>e.map(t=>{if(t.source==="skill"){const n=t.name.startsWith("skill:")?t.name:`skill:${t.name}`,r=n.slice(6);return{id:`skill:${t.scope??"runtime"}:${n}`,name:r,invocationName:n,source:"skill",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}return t.source==="extension"?{id:`extension:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"extension",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}:{id:`prompt:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"prompt",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}),ok=3e4,Jt=new Map;let bb=0;const $h=new Set,wb=()=>{bb+=1;for(const e of $h)e()},sf=()=>bb,ik=e=>($h.add(e),()=>$h.delete(e)),ak=20,Jd=(e,t)=>`${e}
5
- ${t?.trim()??""}`,g0=(e,t)=>Jt.get(Jd(e,t))?.commands,ck=(e,t)=>{const n=Jt.get(Jd(e,t));return n?{...n}:void 0},lk=(e,t=Date.now())=>t-e.fetchedAt<ok,dk=(e,t,n,r)=>{const s=Jd(e,t);for(Jt.delete(s),Jt.set(s,{commands:n,fetchedAt:r?.fetchedAt??Date.now(),promptSignature:r?.promptSignature??"",skillSignature:r?.skillSignature??""});Jt.size>ak;){const o=Jt.keys().next().value;if(typeof o!="string")break;Jt.delete(o)}},uk=(e,t,n,r)=>{const s=Jd(e,t),o=Jt.get(s);return o?(Jt.delete(s),Jt.set(s,{...o,promptSignature:n,skillSignature:r}),!0):!1},xl=e=>{if(typeof e=="string"&&e.trim().length>0){const t=`
6
- ${e.trim()}`;for(const n of[...Jt.keys()])n.endsWith(t)&&Jt.delete(n)}else Jt.clear();wb()},fk=()=>{Jt.clear(),wb()};function zh(e,t=50){if(typeof e!="string"||e.trim().length===0)return"";const r=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[attachment:[^\]]+\]/g," ").replace(/(^|\s)@[\w.-]+/g," ").replace(/<[^>]+>/g," ").replace(/\r\n/g,`
7
- `).split(`
8
- `).map(o=>o.trim()).find(o=>o.length>0);if(!r)return"";const s=r.replace(/\s+/g," ");return s.length<=t?s:`${s.slice(0,t).trimEnd()}…`}const of="pichamber.piSessionCatalog.v1",nd=1,hk=250,Sb=4,Cb=512,Uh=2e3,y0=512,pk=8192,mk=4096,gk=16384,hi=(e,t,n=!1)=>typeof e=="string"&&e.length<=t&&(n||e.length>0),bl=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,v0=e=>{if(!e||typeof e!="object")return null;const t=e;if(!bl(t.updatedAt)||!Array.isArray(t.directories)||t.directories.length>Cb)return null;const n=new Map,r=new Map,s=new Map;let o=0;for(const i of t.directories){if(!i||typeof i!="object")return null;const a=i.directory,l=i.sessions;if(!hi(a,pk)||!Array.isArray(l))return null;const d=de(a);if(!d||r.has(d)||(o+=l.length,o>Uh))return null;const f=[];for(const u of l){if(!u||typeof u!="object")return null;const h=u;if(!hi(h.id,y0)||h.parentId!==null&&!hi(h.parentId,y0)||!hi(h.title,mk,!0)||typeof h.archived!="boolean"||!bl(h.createdAt)||!bl(h.updatedAt)||h.preview!==void 0&&!hi(h.preview,gk,!0)||h.messageCount!==void 0&&(!Number.isSafeInteger(h.messageCount)||h.messageCount<0)||n.has(h.id))return null;const m=h.id;n.set(m,{id:m,directory:d,parentId:h.parentId,title:h.title,archived:h.archived,createdAt:h.createdAt,updatedAt:h.updatedAt,...h.preview!==void 0?{preview:h.preview}:{},...h.messageCount!==void 0?{messageCount:h.messageCount}:{},lifecycle:"idle",hydrated:!1}),f.push(m)}r.set(d,f),s.set(d,"idle")}return{byId:n,byDirectory:r,listStatusByDirectory:s}},x0=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t.version!==nd||!t.runtimes||typeof t.runtimes!="object"||Array.isArray(t.runtimes))return null;const n=Object.entries(t.runtimes);return n.length>Sb?null:{version:nd,runtimes:Object.fromEntries(n)}}catch{return null}},yk=(e,t)=>{const n=[];let r=0;const s=new Set([...e.byDirectory.keys(),...e.listStatusByDirectory.keys()]);for(const o of s){if(n.length>=Cb||r>=Uh)break;const i=de(o);if(!i)continue;const a=[];for(const l of e.byDirectory.get(o)??[]){if(r>=Uh)break;const d=e.byId.get(l);!d||de(d.directory)!==i||(a.push({id:d.id,parentId:d.parentId,title:d.title,archived:d.archived,createdAt:d.createdAt,updatedAt:d.updatedAt,...d.preview!==void 0?{preview:d.preview}:{},...d.messageCount!==void 0?{messageCount:d.messageCount}:{}}),r+=1)}n.push({directory:i,sessions:a})}return{updatedAt:t,directories:n}},vk=(e=Gt(),t={})=>{const n=t.flushDelayMs??hk,r=new Map;let s=null,o=!1;const i=u=>{if(!u)return null;try{const h=x0(e.getItem(of));return!h||!Object.prototype.hasOwnProperty.call(h.runtimes,u)?null:v0(h.runtimes[u])}catch{return null}},a=()=>{if(s!==null&&clearTimeout(s),s=null,r.size===0)return;let u={version:nd,runtimes:{}};try{const x=x0(e.getItem(of));x&&(u=x)}catch{}const h=new Map(Object.entries(u.runtimes));let m=[...h.values()].reduce((x,b)=>bl(b?.updatedAt)?Math.max(x,b.updatedAt):x,0);for(const[x,b]of r)m=Math.max(Date.now(),m+1),h.set(x,yk(b,m));r.clear();const g=[...h.entries()].filter(([,x])=>v0(x)!==null).sort(([,x],[,b])=>b.updatedAt-x.updatedAt).slice(0,Sb);try{e.setItem(of,JSON.stringify({version:nd,runtimes:Object.fromEntries(g)}))}catch{}},l=(u,h)=>{o||!u||(r.set(u,h),s===null&&(s=setTimeout(a,Math.max(0,n))))},d=()=>a(),f=()=>{document.visibilityState==="hidden"&&a()};return t.registerLifecycleListeners&&typeof window<"u"&&(window.addEventListener("pagehide",d,{capture:!0}),window.addEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",f),document.addEventListener("freeze",d))),{read:i,schedule:l,flush:a,dispose:()=>{o||(a(),o=!0,t.registerLifecycleListeners&&typeof window<"u"&&(window.removeEventListener("pagehide",d,{capture:!0}),window.removeEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.removeEventListener("visibilitychange",f),document.removeEventListener("freeze",d))))}}},xk={read:()=>null,schedule:()=>{},flush:()=>{},dispose:()=>{}};let b0=null;const bk=()=>typeof window>"u"?xk:(b0??=vk(Gt(),{registerLifecycleListeners:!0}),b0),Gn=Gt(),qh="projects",Wh="activeProjectId",wk=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim().replace(/\/+$/,""):""},Tm=()=>{const e=qd().trim().replace(/\/+$/,"");return e||""},Qd=()=>{const e=Tm();return e?`${qh}:${encodeURIComponent(e)}`:qh},kb=()=>{const e=Tm();return e?`${Wh}:${encodeURIComponent(e)}`:Wh},Mb=()=>{const e=Tm();if(!e)return!0;const t=wk();return!!(t&&e===t)},Sk=(e,t)=>{const n=e.trim();return!n.startsWith("~")||!t?n:n==="~"?t:n.startsWith("~/")||n.startsWith("~\\")?`${t}${n.slice(1)}`:n},Ck=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Ib=e=>{if(typeof e!="string")return;const t=e.trim();if(!t)return;const n=t.indexOf("/");if(!(n<=0||n>=t.length-1))return t},Eb=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&Ck.test(t)?t.toLowerCase():null},Am=e=>{const t=e.trim();if(!t)return"";const n=Gn.getItem("homeDirectory")||nt.getState().homeDirectory||"",s=Sk(t,n).replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},kk=e=>{const t=Am(e);if(!t||t==="/")return"Root";const n=t.split("/").filter(Boolean);return(n[n.length-1]||t).replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase())},Mk=e=>{if(!e||typeof e!="object")return;const t=e,n=typeof t.mime=="string"?t.mime.trim():"",r=typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?Math.max(0,Math.round(t.updatedAt)):0,s=t.source==="custom"||t.source==="auto"?t.source:null;if(!(!n||!r||!s))return{mime:n,updatedAt:r,source:s}},Ik=e=>{const t=typeof e.type=="string"?e.type.trim().toLowerCase():"";if(t==="image/png"||t==="image/jpeg"||t==="image/svg+xml")return t;const n=e.name.toLowerCase();return n.endsWith(".png")?"image/png":n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".svg")?"image/svg+xml":null},Ek=async e=>await new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(new Error("Failed to read icon file"))},r.onload=()=>{const s=typeof r.result=="string"?r.result:"";if(!s){n(new Error("Failed to read icon file"));return}t(s)},r.readAsDataURL(e)}),_b=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set,r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s,i=typeof o.path=="string"?o.path.trim():"";if(!i)continue;const a=Am(i);if(!a)continue;const l=mm(a);if(!l||n.has(l)||r.has(a))continue;n.add(l),r.add(a);const d={id:l,path:a};if(typeof o.label=="string"&&o.label.trim().length>0&&(d.label=o.label.trim()),typeof o.icon=="string"&&o.icon.trim().length>0&&(d.icon=o.icon.trim()),o.iconImage===null)d.iconImage=null;else{const u=Mk(o.iconImage);u&&(d.iconImage=u)}typeof o.color=="string"&&o.color.trim().length>0&&(d.color=o.color.trim());const f=Ib(o.defaultModel);if(f&&(d.defaultModel=f),o.iconBackground===null)d.iconBackground=null;else{const u=Eb(o.iconBackground);u&&(d.iconBackground=u)}typeof o.addedAt=="number"&&Number.isFinite(o.addedAt)&&o.addedAt>=0&&(d.addedAt=o.addedAt),typeof o.lastOpenedAt=="number"&&Number.isFinite(o.lastOpenedAt)&&o.lastOpenedAt>=0&&(d.lastOpenedAt=o.lastOpenedAt),typeof o.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=o.sidebarCollapsed),t.push(d)}return t},_k=()=>{try{const e=Gn.getItem(Qd())||(Mb()?Gn.getItem(qh):null);return e?_b(JSON.parse(e)):[]}catch{return[]}},jk=()=>{try{const e=Gn.getItem(Qd()+":manualOrder");if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},w0=()=>{try{const e=Gn.getItem(kb())||(Mb()?Gn.getItem(Wh):null);if(typeof e=="string"&&e.trim().length>0)return e.trim()}catch{return null}return null},jb=e=>{try{const t=kb();e?Gn.setItem(t,e):Gn.removeItem(t)}catch{}},Tb=(e,t)=>{try{Gn.setItem(Qd(),JSON.stringify(e))}catch{}jb(t)},Tk=e=>{jb(e),$r({activeProjectId:e})},pi=(e,t,n)=>{Tb(e,t),n&&Kh(n),$r({projects:e,activeProjectId:t??void 0})},Kh=e=>{try{Gn.setItem(Qd()+":manualOrder",JSON.stringify(e))}catch{}},Gh=_k(),Ak=Gh.some(e=>e.id===w0())?w0():Gh[0]?.id??null,lt=Et()(gr((e,t)=>({projects:Gh,activeProjectId:Ak,manualProjectOrder:jk(),validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=Am(n);return r?{ok:!0,normalizedPath:r}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(n,r)=>{const{validateProjectPath:s}=t(),o=s(n);if(!o.ok||!o.normalizedPath)return null;const i=o.normalizedPath,a=t().projects.find(m=>m.path===i);if(a)return t().setActiveProject(a.id),a;const l=Date.now(),d=r?.label?.trim()||kk(i),u={id:mm(i),path:i,label:d,addedAt:l,lastOpenedAt:l},h=[...t().projects,u];return e({projects:h}),T5()&&console.info("[ProjectsStore] Added project",u),t().setActiveProject(u.id),u},removeProject:n=>{const r=t(),s=r.projects.filter(a=>a.id!==n);let o=r.activeProjectId;r.activeProjectId===n&&(o=s[0]?.id??null);const i=t().manualProjectOrder.filter(a=>a!==n);if(e({projects:s,activeProjectId:o,manualProjectOrder:i}),pi(s,o,i),o){const a=s.find(l=>l.id===o);a&&nt.getState().setDirectory(a.path,{showOverlay:!1})}else nt.getState().goHome()},setActiveProject:n=>{const{projects:r,activeProjectId:s}=t();if(s===n)return;const o=r.find(l=>l.id===n);if(!o)return;const i=Date.now(),a=r.map(l=>l.id===n?{...l,lastOpenedAt:i}:l);e({projects:a,activeProjectId:n}),pi(a,n,t().manualProjectOrder),nt.getState().setDirectory(o.path,{showOverlay:!1})},setActiveProjectIdOnly:n=>{const{projects:r,activeProjectId:s}=t();s===n||!r.some(o=>o.id===n)||(e({activeProjectId:n}),Tk(n))},renameProject:(n,r)=>{const s=r.trim();if(!s)return;const{projects:o,activeProjectId:i}=t(),a=o.map(l=>l.id===n?{...l,label:s}:l);e({projects:a}),pi(a,i,t().manualProjectOrder)},updateProjectMeta:(n,r)=>{const{projects:s,activeProjectId:o}=t(),i=s.map(a=>{if(a.id!==n)return a;const l={...a};if(r.label!==void 0){const d=r.label.trim();d&&(l.label=d)}if(r.icon!==void 0&&(l.icon=r.icon),r.color!==void 0&&(l.color=r.color),r.iconBackground!==void 0&&(l.iconBackground=Eb(r.iconBackground)),r.defaultModel!==void 0){const d=Ib(r.defaultModel);d?l.defaultModel=d:delete l.defaultModel}return l});e({projects:i}),pi(i,o,t().manualProjectOrder)},uploadProjectIcon:async(n,r)=>{const s=Ik(r);if(!s)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(r.size)||r.size<=0)return{ok:!1,error:"Icon file is empty"};if(r.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await Ek(r)).replace(/^data:[^;]+;/i,`data:${s};`),a=await Rt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!a.ok)return{ok:!1,error:(await a.json().catch(()=>null))?.error||"Failed to upload project icon"};const l=await a.json().catch(()=>null);return l?.settings&&t().synchronizeFromSettings(l.settings),{ok:!0}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to upload project icon"}}},removeProjectIcon:async n=>{try{const r=await Rt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!r.ok)return{ok:!1,error:(await r.json().catch(()=>null))?.error||"Failed to remove project icon"};const s=await r.json().catch(()=>null);return s?.settings&&t().synchronizeFromSettings(s.settings),{ok:!0}}catch(r){return{ok:!1,error:(r instanceof Error?r.message:String(r))||"Failed to remove project icon"}}},discoverProjectIcon:async()=>({ok:!0,skipped:!0,reason:"unsupported"}),reorderProjects:(n,r)=>{const{projects:s,activeProjectId:o}=t();if(n<0||n>=s.length||r<0||r>=s.length||n===r)return;const i=[...s],[a]=i.splice(n,1);i.splice(r,0,a);const l=i.map(d=>d.id);e({projects:i,manualProjectOrder:l}),pi(i,o,l)},resetForRuntimeSwitch:()=>{e({projects:[],activeProjectId:null,manualProjectOrder:[]})},synchronizeFromSettings:n=>{const r=_b(n.projects??[]),s=t(),o=n.activeProjectId===void 0?r.some(f=>f.id===s.activeProjectId)?s.activeProjectId:null:typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,i=r.map(f=>f.id),a=JSON.stringify(s.projects)!==JSON.stringify(r),l=s.activeProjectId!==o,d=s.manualProjectOrder.length!==i.length||s.manualProjectOrder.some((f,u)=>f!==i[u]);if(!a&&!l){d&&(e({manualProjectOrder:i}),Kh(i));return}if(e({projects:r,activeProjectId:o,manualProjectOrder:i}),Tb(r,o),Kh(i),o&&(l||n.activeProjectId!==void 0)){const f=r.find(u=>u.id===o);f&&nt.getState().setDirectory(f.path,{showOverlay:!1})}},getActiveProject:()=>{const{projects:n,activeProjectId:r}=t();return r?n.find(s=>s.id===r)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{const t=e.detail;t&&typeof t=="object"&&lt.getState().synchronizeFromSettings(t)});const xs=de,Nk=(e,t)=>{const n=xs(t);if(!n)return null;let r=null;for(const s of e){const o=xs(s.path);o&&(n!==o&&!n.startsWith(`${o}/`)||(!r||o.length>(xs(r.path)?.length??0))&&(r=s))}return r},dr=(e,t,n)=>{const s=xs((typeof t=="string"?t:n)??null);if(!s)return null;const o=Nk(e,s);if(o)return o;if(!(t instanceof Map))return null;const i=new Map;for(const l of e){const d=xs(l.path);d&&i.set(d,l)}let a=null;for(const[l,d]of t){const f=xs(l),u=f?i.get(f):null;if(u)for(const h of d??[]){const m=xs(h?.path??null);m&&(s!==m&&!s.startsWith(`${m}/`)||(!a||m.length>a.worktreePath.length)&&(a={project:u,worktreePath:m}))}}return a?.project??null},S0=500,Lk=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("PICHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},it=(e,t)=>{if(!Lk())return;const n=typeof performance<"u"?performance.now():Date.now();window.__PICHAMBER_STARTUP_TRACE_START__??=n,window.__PICHAMBER_STARTUP_TRACE__??=[],window.__PICHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__PICHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__PICHAMBER_STARTUP_TRACE__.length>S0&&window.__PICHAMBER_STARTUP_TRACE__.splice(0,window.__PICHAMBER_STARTUP_TRACE__.length-S0)},Rk=()=>{const e=typeof window<"u"?window.__PICHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory"))};typeof window<"u"&&(window.__PICHAMBER_STARTUP_TRACE_SUMMARY__=Rk);const Zh=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();it(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return it(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw it(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},jc="https://models.dev/api.json",Sa=e=>typeof e=="object"&&e!==null,rd=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Pk=e=>{if(!Sa(e))return!1;const t=e;if(!t.modalities)return!0;const{input:n,output:r}=t.modalities;return(!n||rd(n))&&(!r||rd(r))},Dk=e=>{if(!Sa(e))return!1;const t=e;return t.models===void 0||Sa(t.models)},Ab=(e,t)=>{const n=e?.toLowerCase?.()??"";return!n||!t?"":`${n}/${t}`},C0=e=>{if(!e)return[];const t=[];return e.text&&t.push("text"),e.audio&&t.push("audio"),e.image&&t.push("image"),e.video&&t.push("video"),e.pdf&&t.push("pdf"),t},Ok=(e,t)=>({id:t.id,providerId:e,name:t.name,tool_call:t.capabilities?.toolcall,reasoning:t.capabilities?.reasoning,temperature:t.capabilities?.temperature,attachment:t.capabilities?.attachment,modalities:t.capabilities?{input:C0(t.capabilities.input),output:C0(t.capabilities.output)}:void 0,cost:t.cost?{input:t.cost.input,output:t.cost.output,cache_read:t.cost.cache?.read,cache_write:t.cost.cache?.write}:void 0,limit:t.limit,release_date:t.release_date}),Hk=e=>{const t=new Map;if(!Sa(e))return t;for(const[n,r]of Object.entries(e)){if(!Dk(r))continue;const s=typeof r.id=="string"&&r.id.length>0?r.id:n,o=r.models;if(!(!o||!Sa(o)))for(const[i,a]of Object.entries(o)){if(!Pk(a))continue;const l=i||a.id;if(!l)continue;const d=Ab(s,l);d&&t.set(d,{id:typeof a.id=="string"&&a.id.length>0?a.id:l,providerId:s,name:typeof a.name=="string"?a.name:void 0,tool_call:typeof a.tool_call=="boolean"?a.tool_call:void 0,reasoning:typeof a.reasoning=="boolean"?a.reasoning:void 0,temperature:typeof a.temperature=="boolean"?a.temperature:void 0,attachment:typeof a.attachment=="boolean"?a.attachment:void 0,structured_output:typeof a.structured_output=="boolean"?a.structured_output:void 0,modalities:a.modalities?{input:rd(a.modalities.input)?a.modalities.input:void 0,output:rd(a.modalities.output)?a.modalities.output:void 0}:void 0,cost:a.cost,limit:a.limit,knowledge:typeof a.knowledge=="string"?a.knowledge:void 0,release_date:typeof a.release_date=="string"?a.release_date:void 0,last_updated:typeof a.last_updated=="string"?a.last_updated:void 0})}}return t},Fk=async()=>{if(typeof fetch!="function")return new Map;const e=typeof AbortController<"u"?new AbortController:void 0,t=e?setTimeout(()=>e.abort(),8e3):void 0;try{const n=await fetch(jc,{signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store",mode:"cors"});if(!n.ok)throw new Error(`Metadata request to ${jc} returned status ${n.status}`);return Hk(await n.json())}catch(n){return n?.name==="AbortError"?console.warn(`Model metadata request aborted (${jc})`):console.warn(`Failed to fetch model metadata from ${jc}:`,n),new Map}finally{t&&clearTimeout(t)}};let Qi=null;const Bk=3e4;let ro=null;const Vk=1500;let Tc=null;const $k=()=>{if(typeof window<"u"&&typeof window.requestIdleCallback=="function")return window.requestIdleCallback.bind(window);const e=globalThis.requestIdleCallback;return typeof e=="function"?e:null},Yh=(e,t)=>{e().size>0||Qi||ro!==null&&Date.now()-ro<Bk||(it("modelsMetadata:queued"),Qi=Zh("modelsMetadata",Fk).then(n=>(n.size>0?(ro=null,it("modelsMetadata:set",{entries:n.size}),t(n)):ro=Date.now(),n)).catch(()=>(ro=Date.now(),new Map)).finally(()=>{Qi=null}))},zk=()=>{Qi=null,ro=null},Uk=(e,t)=>{if(e().size>0||Qi||Tc)return;it("modelsMetadata:scheduledIdle");const n=()=>{Tc=null,it("modelsMetadata:idleFired"),Yh(e,t)},r=$k();if(r){Tc={kind:"idle",handle:r(n,{timeout:5e3})};return}Tc={kind:"timeout",handle:setTimeout(n,Vk)}},qk=(e,t,n,r)=>{const s=Ab(t,n);if(s)return e.get(s)??(r?Ok(t,r):void 0)},Nb=e=>{if(!e)return null;const t=e.indexOf("/");return t<=0||t>=e.length-1?null:{providerId:e.slice(0,t),modelId:e.slice(t+1)}},Wk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!Nb(n))continue;const s=ln(r);s&&(t[n]=s)}return t},Kk=async()=>{try{const e=await Rt("/api/pi/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return{ok:!1};const n=(await e.json())?.pichamber,r=n?.defaultModel;let s;if(r&&typeof r.providerId=="string"&&typeof r.modelId=="string"){const o=r.providerId.trim(),i=r.modelId.trim();o&&i&&(s=`${o}/${i}`)}return{ok:!0,defaultModel:s,defaultThinking:ln(n?.defaultThinking)??void 0,defaultThinkingByModel:Wk(n?.defaultThinkingByModel)}}catch{return{ok:!1}}},af=e=>{const t=typeof e.defaultModel=="string"?e.defaultModel.trim():"",n=typeof e.defaultVariant=="string"?e.defaultVariant.trim():"",r=typeof e.zenModel=="string"?e.zenModel.trim():"",s=e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse"||e.messageStreamTransport==="auto"?e.messageStreamTransport:void 0;return{defaultModel:t.length>0?t:void 0,defaultVariant:n.length>0?n:void 0,autoCreateWorktree:typeof e.autoCreateWorktree=="boolean"?e.autoCreateWorktree:void 0,zenModel:r.length>0?r:void 0,messageStreamTransport:s}},Gk=async()=>{it("config.defaults:start");const e=typeof performance<"u"?performance.now():Date.now(),t=(n,r)=>{const s=typeof performance<"u"?performance.now():Date.now();return it("config.defaults:end",{source:n,durationMs:Math.round(s-e),hasDefaultModel:!!r.defaultModel}),r};try{const n=await Kk(),r=(l,d)=>n.ok?t(l,{...d,defaultModel:n.defaultModel,defaultThinking:n.defaultThinking,defaultThinkingByModel:n.defaultThinkingByModel}):t(l,d),s=await CS().catch(()=>null);if(s)return r("shared-settings",af(s));const o=zr()?.settings;if(o)try{const d=(await o.load())?.settings;if(d)return r("runtime-settings",af(d))}catch{}const i=await Rt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)return r("settings-route-not-ok",{});const a=await i.json();return r("settings-route",a&&typeof a=="object"&&!Array.isArray(a)?af(a):{})}catch(n){return it("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),t("error",{})}},Zk=3e4,Ac=new Map,k0=new WeakMap;let Nc=0;const Yk=(e,t)=>JSON.stringify([e,de(t)??t]),Xk=(e,t)=>e.length===t.length&&e.every((n,r)=>{const s=t[r];return s&&n.path===s.path&&n.head===s.head&&n.branch===s.branch&&n.name===s.name&&n.isPrimary===s.isPrimary&&n.detached===s.detached&&n.locked===s.locked&&n.prunable===s.prunable}),M0=()=>({worktrees:[],status:"idle",error:null,fetchedAt:0}),un=Et()((e,t)=>({runtimeKey:Y(),projects:new Map,refreshProject:async(n,r,s)=>{const o=de(n);if(!o)return null;const i=Y(),a=Nc,l=Yk(i,o),d=Ac.get(l);if(d)return d;const f=t().projects.get(o)??M0();if(!s?.force&&f.status==="ready"&&f.error===null&&Date.now()-f.fetchedAt<Zk)return f.worktrees;f.status==="idle"&&e(h=>{const m=new Map(h.projects);return m.set(o,{...f,status:"loading"}),{projects:m}});const u=(async()=>{try{const m=await r.checkIsGitRepository(o)?await(()=>{if(!r.listGitWorktrees)throw new Error("Git worktrees are unavailable for this runtime.");return r.listGitWorktrees(o)})():[];return a!==Nc||i!==Y()||t().runtimeKey!==i?null:(e(g=>{const x=g.projects.get(o)??M0(),b=Xk(x.worktrees,m);if(b&&x.status==="ready"&&x.error===null)return g;const S=new Map(g.projects);return S.set(o,{worktrees:b?x.worktrees:m,status:"ready",error:null,fetchedAt:Date.now()}),{projects:S}}),m)}catch(h){if(a!==Nc||i!==Y()||t().runtimeKey!==i)return null;const m=h instanceof Error?h.message:"Failed to discover Git worktrees.";return e(g=>{const x=g.projects.get(o)??f,b=new Map(g.projects);return b.set(o,{...x,status:"failed",error:m}),{projects:b}}),null}finally{Ac.delete(l)}})();return Ac.set(l,u),u},resetForRuntimeSwitch:n=>{Nc+=1,Ac.clear(),e({runtimeKey:n,projects:new Map})}})),Jk=(e,t)=>{const n=de(t??null);if(!n)return[];const r=e.projects.get(n)?.worktrees;if(!r)return[];const s=k0.get(r);if(s)return s;const o=r.filter(i=>!i.isPrimary&&!i.prunable);return k0.set(r,o),o},Zn=(e,t)=>{const n=new Map;for(const r of e){const s=de(r.path??null);s&&n.set(s,Jk(t,s))}return n},Nm="__global__",bs=e=>{const t=typeof e=="string"?e.trim():"";return t.length>0?t:Nm},ds=e=>e===Nm?null:e,Qk=()=>typeof window>"u"?Nm:Sl(nt.getState().currentDirectory),Lb="oc.worktreeProjectMap.v2",Xh="oc.worktreeProjectMap",eM=8,I0=new Map,Rb=()=>{try{const e=typeof localStorage<"u"?localStorage.getItem(Lb):null;if(!e)return{version:2,legacyClaimed:!1,runtimes:{}};const t=JSON.parse(e);return t.version!==2||!t.runtimes||typeof t.runtimes!="object"?{version:2,legacyClaimed:!1,runtimes:{}}:{version:2,legacyClaimed:t.legacyClaimed===!0,runtimes:t.runtimes}}catch{return{version:2,legacyClaimed:!1,runtimes:{}}}},Pb=e=>{const t=Object.fromEntries(Object.entries(e.runtimes).sort(([,n],[,r])=>r.updatedAt-n.updatedAt).slice(0,eM));localStorage.setItem(Lb,JSON.stringify({...e,runtimes:t}))},Db=()=>{const e=Y()||"default",t=I0.get(e);if(t)return t;const n=Rb();let r=n.runtimes[e]?.entries??null;if(!r&&!n.legacyClaimed)try{const o=typeof localStorage<"u"?localStorage.getItem(Xh):null;r=o?JSON.parse(o):{},n.legacyClaimed=!0,n.runtimes[e]={updatedAt:Date.now(),entries:r},Pb(n),localStorage.removeItem(Xh)}catch{r={}}const s=r??{};return I0.set(e,s),s},tM=(e,t)=>{if(!e||!t||e===t)return;const n=Db();if(n[e]!==t){n[e]=t;try{const r=Y()||"default",s=Rb();s.legacyClaimed=!0,s.runtimes[r]={updatedAt:Date.now(),entries:n},Pb(s),localStorage.removeItem(Xh)}catch{}}},ea=e=>{const t=de(e);return t===null?null:t||"/"},nM=()=>{try{return lt.getState().projects.map(e=>ea(e.path)).filter(e=>!!e)}catch{return[]}},rM=()=>{try{const{projects:e,activeProjectId:t}=lt.getState(),n=t?e.find(r=>r.id===t):null;return ea(n?.path??e[0]?.path??null)}catch{return null}},wl=e=>{const t=ea(e),n=nM();if(!t)return null;if(n.includes(t))return t;const r=ea(Db()[t]);if(r)return r;try{const s=lt.getState().projects,o=dr(s,Zn(s,un.getState()),t),i=ea(o?.path??null);if(i&&i!==t)return tM(t,i),i}catch{return null}return null},Sl=e=>bs(wl(e)),Ob="__add_provider__",is="zen",E0="big-pickle",Hb=e=>Nb(e),Fb=(e,t)=>{const n=ln(t);return n&&_m(e).includes(n)?n:void 0},_0=e=>e===Ob?"":e??"",sd=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},od=(e,t,n)=>{const r=e.find(s=>s.id===t);return r?r.models.some(s=>s.id===n):!1},sM=({providers:e,currentProviderId:t,currentModelId:n,currentVariant:r,settingsDefaultModel:s,settingsDefaultVariant:o})=>{const i=(d,f,u)=>{if(!u)return;const h=e.find(m=>m.id===d)?.models.find(m=>m.id===f);return Fb(h,u)};if(t&&n&&od(e,t,n))return{providerId:t,modelId:n,variant:i(t,n,r)};if(s){const d=Hb(s);if(d&&od(e,d.providerId,d.modelId))return{providerId:d.providerId,modelId:d.modelId,variant:i(d.providerId,d.modelId,o)}}const a=e.find(d=>d.authenticated&&d.models.length>0)||e.find(d=>d.models.length>0)||e[0],l=a?.models[0];return a&&l?{providerId:a.id,modelId:l.id}:null},cf=({providers:e,settingsZenModel:t})=>{const n=sd(t);if(!Array.isArray(e)||e.length===0)return n?{providerId:is,modelId:n}:null;if(n&&od(e,is,n))return{providerId:is,modelId:n};if(od(e,is,E0))return{providerId:is,modelId:E0};const r=e.find(s=>s.id===is);if(r?.models.length){const s=Math.floor(Math.random()*r.models.length),o=sd(r.models[s]?.id);if(o)return{providerId:is,modelId:o}}return null},oM=4,iM=800,aM=3e4,cM=1e3,lM=e=>{const t={...e};delete t.agents,delete t.currentAgentName,delete t.agentModelSelections,delete t.runtimeDefaultAgent,delete t.runtimeDefaultModel,delete t.settingsDefaultFileViewerPreview,delete t.defaultFileViewerPreview,delete t.settingsGitmojiEnabled,delete t.gitmojiEnabled;const n=e.directoryScoped;if(n&&typeof n=="object"){const a={};for(const[l,d]of Object.entries(n)){if(!d||typeof d!="object"){a[l]=d;continue}const f={...d};delete f.agents,delete f.currentAgentName,delete f.agentModelSelections,delete f.runtimeDefaultAgent,delete f.runtimeDefaultModel,delete f.settingsDefaultFileViewerPreview,delete f.defaultFileViewerPreview,a[l]=f}t.directoryScoped=a}const r=t.directoryScoped,s=t.activeDirectoryKey;if(!r||!s)return t;const o=r[s];if(!o)return t;const i={...t};return(!i.providers||i.providers.length===0)&&o.providers?.length&&(i.providers=o.providers),(!i.defaultProviders||Object.keys(i.defaultProviders).length===0)&&o.defaultProviders&&Object.keys(o.defaultProviders).length>0&&(i.defaultProviders=o.defaultProviders),o.selectionSource&&(i.selectionSource=o.selectionSource),i},j0=new Map,dM=(e,t)=>{const n=e.get(t);return typeof n=="number"&&Date.now()-n<aM},uM=e=>new Promise(t=>setTimeout(t,e)),Bb=async()=>(await Ie.health({runtimeKey:Y()})).state==="ready",fM=async(e=iM)=>Promise.race([Bb().catch(()=>!1),uM(Math.max(1,e)).then(()=>!1)]),T0=new Set;function hM(e){return T0.add(e),()=>{T0.delete(e)}}function pM(e,t){return e.scopes.includes("all")||e.scopes.includes(t)}const mM=async(e,t)=>{const n=e.getState(),r=Array.from(new Set([n.activeDirectoryKey,...Object.keys(n.directoryScoped)])).filter(a=>a.length>0);n.invalidateProviderCache();let s=0;const o=Math.min(oM,r.length),i=Array.from({length:o},async()=>{for(;s<r.length;){const a=r[s];s+=1,await e.getState().loadProviders({directory:ds(a),source:t})}});await Promise.all(i)};let A0=null,N0=null;const gM=e=>{typeof window<"u"&&(window.__zustand_config_store__=e),A0||(A0=hM(async t=>{pM(t,"providers")&&await mM(e,"configChange:providers")})),typeof window<"u"&&!N0&&(N0=nt.subscribe((t,n)=>{const r=bs(t.currentDirectory),s=bs(n.currentDirectory);r!==s&&(it("directoryStore:changed",{previous:s,next:r}),e.getState().activateDirectory(t.currentDirectory))}))},yM=e=>{if(e.authenticated!==!0)return!1;const t=e.models;return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!1},vM=e=>e.filter(yM),xM=async()=>{const e=await Ie.listProviders({runtimeKey:Y()}),n=vM(e.providers).map(s=>{const o=s.models.map(i=>({id:i.id,name:i.label??i.id,providerID:i.providerId,reasoning:i.supportsThinking===!0,...Number.isSafeInteger(i.contextWindow)?{limit:{context:i.contextWindow}}:{},...Array.isArray(i.thinkingLevels)&&i.thinkingLevels.length>0?{thinkingLevels:i.thinkingLevels}:{}}));return{id:s.id,name:s.label??s.id,authenticated:s.authenticated===!0,models:o}}),r=e.default?{[e.default.providerId]:e.default.modelId}:{};return{providers:n,defaults:r}},lf=e=>new Promise(t=>setTimeout(t,e)),df=new Map;let Lc=null;const We=Et()(gr(Gd((e,t)=>({activeDirectoryKey:Qk(),directoryScoped:{},providers:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,selectedProviderId:"",defaultProviders:{},selectionSource:"auto",isConnected:!1,hasEverConnected:!1,connectionPhase:"connecting",lastDisconnectReason:null,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultThinking:void 0,settingsDefaultThinkingByModel:{},settingsAutoCreateWorktree:!1,settingsZenModel:void 0,activateDirectory:async n=>{const r=wl(n),s=typeof n=="string"&&n.trim().length>0;if(!r&&s){it("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=bs(r);let i=!1;e(a=>{const l=a.directoryScoped[o];return l?(i=l.providers.length>0,{activeDirectoryKey:o,providers:l.providers,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,selectedProviderId:l.selectedProviderId,defaultProviders:l.defaultProviders,selectionSource:l.selectionSource??"auto"}):{activeDirectoryKey:o,providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{},selectionSource:"auto"}}),t().isConnected&&(i?dM(j0,o)?it("activateDirectory:providersFresh",{directoryKey:o}):(it("activateDirectory:refreshProvidersBackground",{directoryKey:o}),t().loadProviders({directory:ds(o),source:"activateDirectory:refresh"})):await t().loadProviders({directory:ds(o),source:"activateDirectory"}))},invalidateProviderCache:n=>{const r=n===void 0?null:bs(n);e(s=>{const o={};let i=!1;const a={...s.directoryScoped},l=d=>d.providers.length===0&&Object.keys(d.defaultProviders).length===0?d:(i=!0,{...d,providers:[],defaultProviders:{}});if(r){const d=s.directoryScoped[r];d&&(a[r]=l(d))}else for(const[d,f]of Object.entries(s.directoryScoped))a[d]=l(f);return i&&(o.directoryScoped=a),(r===null||r===s.activeDirectoryKey)&&(s.providers.length>0&&(o.providers=[]),Object.keys(s.defaultProviders).length>0&&(o.defaultProviders={})),Object.keys(o).length>0?o:s})},loadProviders:async n=>{const r=n?.directory??ds(t().activeDirectoryKey),s=wl(r),o=typeof r=="string"&&r.trim().length>0;if(!s&&o){it("loadProviders:skippedUnknownDirectory",{requestedDirectory:r,source:n?.source??"unknown"});return}const i=s??null,a=bs(s),l=n?.source??"unknown";it("loadProviders:called",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const d=df.get(a);if(d)return it("loadProviders:deduped",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i}),d;const f=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();it("loadProviders:start",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const h=t().directoryScoped[a],m=h?.providers??(t().activeDirectoryKey===a?t().providers:[]),g=h?.defaultProviders??(t().activeDirectoryKey===a?t().defaultProviders:{});let x=null;for(let b=0;b<3;b++)try{const S=await Zh("loadProviders:api",async()=>xM(),{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1}),y=S?.providers??[],v=S?.defaults??{};e(w=>{const I=w.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},E=w.activeDirectoryKey===a?w.currentProviderId:I.currentProviderId,T=w.activeDirectoryKey===a?w.currentModelId:I.currentModelId,A=w.activeDirectoryKey===a?w.currentVariant:I.currentVariant,j=sM({providers:y,currentProviderId:E,currentModelId:T,currentVariant:A,settingsDefaultModel:w.settingsDefaultModel,settingsDefaultVariant:w.settingsDefaultVariant}),k=w.activeDirectoryKey===a?w.selectedProviderId:I.selectedProviderId,_=k===Ob||y.some(O=>O.id===k)?k:j?.providerId??y[0]?.id??"",M={...I,providers:y,defaultProviders:v,currentProviderId:j?.providerId??"",currentModelId:j?.modelId??"",currentVariant:j?.variant,selectedProviderId:_},L={directoryScoped:{...w.directoryScoped,[a]:M}};return w.activeDirectoryKey===a&&(L.providers=y,L.defaultProviders=v,L.currentProviderId=M.currentProviderId,L.currentModelId=M.currentModelId,L.currentVariant=M.currentVariant,L.selectedProviderId=_),L});const C=typeof performance<"u"?performance.now():Date.now();it("loadProviders:end",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,durationMs:Math.round(C-u),providers:y.length,models:y.reduce((w,I)=>w+I.models.length,0)}),j0.set(a,Date.now());return}catch(S){x=S,it("loadProviders:attemptError",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1,error:S instanceof Error?S.message:String(S)});const y=200*(b+1);await new Promise(v=>setTimeout(v,y))}console.error("Failed to load providers:",x),it("loadProviders:error",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,error:x instanceof Error?x.message:String(x)}),e(b=>{const y={...b.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},providers:m,defaultProviders:g},v={directoryScoped:{...b.directoryScoped,[a]:y}};if(b.activeDirectoryKey===a&&(v.providers=m,v.defaultProviders=g,!b.currentProviderId&&!b.currentModelId&&b.settingsDefaultModel)){const C=Hb(b.settingsDefaultModel);if(C){const w=m.find(I=>I.id===C.providerId);if(w?.models.some(I=>I.id===C.modelId)){const I=w.models.find(T=>T.id===C.modelId),E=Fb(I,b.settingsDefaultVariant);v.currentProviderId=C.providerId,v.currentModelId=C.modelId,v.currentVariant=E,v.selectedProviderId=C.providerId,y.currentProviderId=C.providerId,y.currentModelId=C.modelId,y.currentVariant=E,y.selectedProviderId=C.providerId}}}return v})})().finally(()=>df.delete(a));return df.set(a,f),f},setProvider:n=>{const{providers:r}=t(),s=r.find(a=>a.id===n);if(!s)return;const i=s.models[0]?.id||"";e(a=>{const l=a.activeDirectoryKey,f={...a.directoryScoped[l]??{providers:a.providers,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,selectedProviderId:a.selectedProviderId,defaultProviders:a.defaultProviders},currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual"};return{currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual",directoryScoped:{...a.directoryScoped,[l]:f}}})},setModel:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentModelId:n,selectionSource:"manual"};return{currentModelId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},setCurrentVariant:n=>{e(r=>{if(r.currentVariant===n)return r;const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentVariant:n,selectionSource:"manual"};return{currentVariant:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},getCurrentModelVariants:()=>_m(t().getCurrentModel()),cycleCurrentVariant:()=>{const n=jm(t().getCurrentModelVariants(),t().currentVariant,1);t().setCurrentVariant(n)},setSelectedProvider:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},selectedProviderId:n,selectionSource:"manual"};return{selectedProviderId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},invalidateModelMetadataCache:()=>{zk(),e({modelsMetadata:new Map})},ensureModelMetadata:()=>{Yh(()=>t().modelsMetadata,n=>e({modelsMetadata:n}))},setSettingsDefaultModel:n=>{e({settingsDefaultModel:n})},setSettingsDefaultVariant:n=>{e({settingsDefaultVariant:n})},setSettingsDefaultThinking:n=>{e({settingsDefaultThinking:n})},setSettingsDefaultThinkingByModel:n=>{e({settingsDefaultThinkingByModel:n})},setSettingsAutoCreateWorktree:n=>{e({settingsAutoCreateWorktree:n})},setSettingsZenModel:n=>{e({settingsZenModel:n})},getResolvedGitGenerationModel:()=>{const n=t();return cf({providers:n.providers,settingsZenModel:n.settingsZenModel})},probeConnection:async n=>{if(await fM(n?.timeoutMs))return e({isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),!0;const s=t();return s.isConnected?!0:(e({isConnected:!1,connectionPhase:s.hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_probe_unhealthy"}),!1)},checkConnection:async()=>{it("checkConnection:start");const n=5;let r=0,s=null;for(;r<n;)try{it("checkConnection:attempt",{attempt:r+1});const o=await Zh("checkConnection:health",()=>Bb(),{attempt:r+1});if(!o&&r<n-1){const a=t().hasEverConnected;e({isConnected:!1,connectionPhase:a?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),r+=1,await lf(400*r);continue}const i=t().hasEverConnected;return e(o?{isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}:{isConnected:!1,connectionPhase:i?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),it("checkConnection:end",{healthy:o,attempts:r+1}),o}catch(o){s=o,r+=1;const i=400*r;await lf(i)}return s&&console.warn("[ConfigStore] Failed to reach Pi after retrying:",s),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_check_failed"}),it("checkConnection:end",{healthy:!1,attempts:n}),!1},initializeApp:async()=>{if(Lc)return it("initializeApp:deduped"),Lc;const n=(async()=>{const r=typeof performance<"u"?performance.now():Date.now();it("initializeApp:start");try{const s=T5();s&&console.log("Starting app initialization...");const o=await t().checkConnection();if(s&&console.log("Connection check result:",o),!o){s&&console.log("Server not connected"),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting"});return}s&&console.log("Initializing app..."),it("initApp:skipped",{reason:"checkConnection already verified health"});const i=nt.getState().currentDirectory??ds(t().activeDirectoryKey),a=dr(lt.getState().projects,null,i??null),l=wl(a?.path??i??null),d=l??rM();d||it("initializeApp:globalConfigScope"),d&&!l&&i!==d&&(it("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),nt.getState().setDirectory(d,{showOverlay:!1}));const f=bs(d);t().activeDirectoryKey!==f&&e({activeDirectoryKey:f}),s&&console.log("Loading providers..."),await t().loadProviders({directory:d,source:"initializeApp"});const u=await Gk(),h=t().providers,m=sd(t().settingsZenModel),g=sd(u.zenModel),b=(cf({providers:h,settingsZenModel:m})??cf({providers:h,settingsZenModel:g}))?.modelId||g||m;e({settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultThinking:u.defaultThinking,settingsDefaultThinkingByModel:u.defaultThinkingByModel??{},settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsZenModel:b}),b&&b!==g&&$r({zenModel:b,gitProviderId:"",gitModelId:""}).catch(()=>{}),e({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),Uk(()=>t().modelsMetadata,y=>e({modelsMetadata:y})),t().prewarmProjectConfigs(d);const S=typeof performance<"u"?performance.now():Date.now();it("initializeApp:end",{durationMs:Math.round(S-r),providers:t().providers.length}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),e({isInitialized:!1,isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"init_error"}),it("initializeApp:error",{error:s instanceof Error?s.message:String(s)})}})().finally(()=>{Lc=null});return Lc=n,n},prewarmProjectConfigs:async n=>{if(!t().isConnected)return;const r=Sl(n??ds(t().activeDirectoryKey)),s=lt.getState().projects.map(a=>a.path).filter(a=>typeof a=="string"&&a.trim().length>0),o=new Set([r]),i=[];for(const a of s){const l=Sl(a);if(o.has(l)||(o.add(l),t().directoryScoped[l]?.providers.length))continue;const f=ds(l);f&&i.push(f)}for(const a of i){if(await lf(cM),!t().isConnected)return;const l=Sl(a),d=t().directoryScoped[l],f=[];d?.providers.length||f.push(t().loadProviders({directory:a,source:"projectConfigPrewarm"})),f.length>0&&await Promise.allSettled(f)}},getCurrentProvider:()=>{const{providers:n,currentProviderId:r}=t();return n.find(s=>s.id===r)},getCurrentModel:()=>{const n=t().getCurrentProvider(),{currentModelId:r}=t();if(n)return n.models.find(s=>s.id===r)},getModelMetadata:(n,r)=>{Yh(()=>t().modelsMetadata,a=>e({modelsMetadata:a}));const{modelsMetadata:s,providers:o}=t(),i=o.find(a=>a.id===n)?.models.find(a=>a.id===r);return qk(s,n,r,i)}}),{name:"config-store",storage:gm(),merge:(e,t)=>lM({...t,...e&&typeof e=="object"?e:{}}),partialize:e=>({activeDirectoryKey:e.activeDirectoryKey,directoryScoped:Object.fromEntries(Object.entries(e.directoryScoped).map(([t,n])=>[t,{...n,selectedProviderId:_0(n.selectedProviderId)}])),providers:e.providers,currentProviderId:e.currentProviderId,currentModelId:e.currentModelId,currentVariant:e.currentVariant,selectedProviderId:_0(e.selectedProviderId),defaultProviders:e.defaultProviders,settingsDefaultModel:e.settingsDefaultModel,settingsDefaultVariant:e.settingsDefaultVariant,settingsDefaultThinking:e.settingsDefaultThinking,settingsDefaultThinkingByModel:e.settingsDefaultThinkingByModel,settingsAutoCreateWorktree:e.settingsAutoCreateWorktree,settingsZenModel:e.settingsZenModel})})));gM(We);const bM=5e3,wo=new Map,So=new Map,id=e=>{const t=Y();wo.delete(t),So.delete(t),(!t||t==="local")&&(wo.clear(),So.clear())},Vb=()=>{wo.clear(),So.clear()},Hr=Et()(gr(Gd((e,t)=>({selectedSkillName:null,skills:[],isLoading:!1,setSelectedSkill:n=>e({selectedSkillName:n}),loadSkills:async()=>{const n=Y(),r=Date.now(),s=wo.get(n)??0;if(s>0&&r-s<bM)return!0;const o=So.get(n);if(o)return o;const i=(async()=>{e({isLoading:!0});try{const l=(await Ie.listResources({runtimeKey:n})).skills.map(d=>({id:d.id,name:d.name,path:d.id,scope:d.location==="project"?"project":"user",source:"agents",...d.description?{description:d.description}:{},location:d.location,...typeof d.content=="string"&&d.content.length>0?{content:d.content}:{},...d.editable===!0?{editable:!0}:{}}));return e(d=>({skills:l,isLoading:!1,...d.selectedSkillName&&!l.some(f=>f.name===d.selectedSkillName)?{selectedSkillName:null}:{}})),wo.set(n,Date.now()),!0}catch{return e({isLoading:!1}),!1}})();So.set(n,i);try{return await i}finally{So.delete(n)}},renameSkill:async()=>!1,updateSkillContent:async(n,r)=>{const s=t().skills.find(o=>o.name===n);if(!s)return!1;try{const i=(await Ie.updateResource({resourceId:s.id,content:r},{runtimeKey:Y()})).skills.map(a=>({id:a.id,name:a.name,path:a.id,scope:a.location==="project"?"project":"user",source:"agents",...a.description?{description:a.description}:{},location:a.location,...typeof a.content=="string"&&a.content.length>0?{content:a.content}:{},...a.editable===!0?{editable:!0}:{}}));return e({skills:i}),wo.set(Y(),Date.now()),!0}catch{return!1}},getSkillByName:n=>t().skills.find(r=>r.name===n),resetForRuntimeSwitch:()=>{Vb(),e({skills:[],isLoading:!1,selectedSkillName:null})}}),{name:"skills-store",storage:gm(),partialize:e=>({selectedSkillName:e.selectedSkillName})}),{name:"skills-store"})),LX=Object.freeze(Object.defineProperty({__proto__:null,invalidateSkillsLoadCache:id,resetSkillsForRuntimeSwitch:Vb,useSkillsStore:Hr},Symbol.toStringTag,{value:"Module"})),wM=200,$b=1440*60*1e3,SM=3e4,CM=15e3,kM=9e4,Jh="oc.session-activity.v1",MM=new Set,IM=new Map,Ln=Et(()=>({startedAt:new Map,settledMs:new Map})),Ts=new Map;let Lm=0,ad=null;const EM=()=>typeof performance<"u"&&Number.isFinite(performance.timeOrigin)?performance.timeOrigin:Date.now();let Rm=EM();const zb=(e,t)=>e.start<=t&&t-e.start<=$b&&e.seen<=t&&Rm-e.seen<=SM,_M=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const{start:t,seen:n}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)?null:{start:t,seen:n}},jM=()=>{const e=new Map;let t=null;try{t=Wd().getItem(Jh)}catch{return e}if(!t)return e;let n;try{n=JSON.parse(t)}catch{return e}if(!n||typeof n!="object"||Array.isArray(n))return e;const r=Date.now();for(const[s,o]of Object.entries(n)){const i=_M(o);i&&zb(i,r)&&e.set(s,i)}return e},eu=()=>(ad??=jM(),ad),TM=e=>e-Rm>kM?(ad?.clear(),IM):eu(),Ms=(e,t)=>{const n={};for(const[r,s]of eu())zb(s,t)&&(n[r]=s);for(const[r,s]of e)n[r]={start:s,seen:Ts.get(r)??t};Lm=t;try{const r=Wd();if(Object.keys(n).length===0){r.removeItem(Jh);return}r.setItem(Jh,JSON.stringify(n))}catch{}},uf=()=>{const{startedAt:e}=Ln.getState();if(e.size===0)return;const t=Date.now();for(const n of e.keys())Ts.set(n,t);Ms(e,t)};let L0=!1;const Ub=()=>{if(!(L0||typeof window>"u")){L0=!0;try{window.addEventListener("pagehide",uf,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&uf()}),document.addEventListener("freeze",uf))}catch{}}},AM=e=>{for(;e.size>wM;){const t=e.keys().next();if(t.done)return;e.delete(t.value)}},R0=(e,t)=>{const n=Date.now(),r=TM(n),s=Ln.getState(),o={started:null,settled:null};let i=!1,a=!1;const l=()=>o.started??=new Map(s.startedAt),d=()=>o.settled??=new Map(s.settledMs);for(const u of e)i=!0,Ts.set(u,n),!(o.started??s.startedAt).has(u)&&(l().set(u,r.get(u)?.start??n),(o.settled??s.settledMs).has(u)&&d().delete(u));const f=(u,h)=>{l().delete(u),Ts.delete(u),d().set(u,Math.max(0,n-h))};if(t!==null){eu().delete(t)&&(a=!0);const u=s.startedAt.get(t);u!==void 0&&f(t,u)}if(o.settled&&AM(o.settled),(o.started||o.settled)&&Ln.setState({startedAt:o.started??s.startedAt,settledMs:o.settled??s.settledMs}),o.started){o.started.size>0&&Ub(),Ms(o.started,n);return}if(a){Ms(s.startedAt,n);return}i&&s.startedAt.size>0&&n-Lm>=CM&&Ms(s.startedAt,n)},P0=(e,t)=>{if(t==="active"){R0(new Set([e]),null);return}R0(MM,e)},Mn=(e,t,n)=>{if(!Number.isFinite(t))return;const r=Date.now(),s=Fo(t,n,r);if(s===void 0||r-s>$b||s>r+6e4)return;const o=Ln.getState(),i=o.startedAt.get(e);if(i!==void 0&&s>=i)return;const a=new Map(o.startedAt);a.set(e,s);const l=new Map(o.settledMs);l.delete(e),Ts.set(e,r),Ln.setState({startedAt:a,settledMs:l}),Ub(),Ms(a,r)},D0=e=>{const t=eu().delete(e),n=Ln.getState(),r=n.startedAt.has(e),s=n.settledMs.has(e);if(Ts.delete(e),!r&&!s){t&&Ms(n.startedAt,Date.now());return}let o=n.startedAt;if(r){const a=new Map(n.startedAt);a.delete(e),o=a}let i=n.settledMs;if(s){const a=new Map(n.settledMs);a.delete(e),i=a}Ln.setState({startedAt:o,settledMs:i}),(r||t)&&Ms(o,Date.now())},RX=(e={})=>{ad=null,Ts.clear(),Lm=0,Rm=e.pageLoadAt??Date.now(),Ln.setState({startedAt:new Map,settledMs:new Map})},qb=e=>Ln(H.useCallback(t=>t.startedAt.get(e),[e])),PX=e=>Ln(H.useCallback(t=>t.settledMs.get(e),[e])),DX=(e,t)=>Ln(H.useCallback(n=>t?n.startedAt.has(e):n.settledMs.has(e),[t,e])),Qh="oc.sessions.pinned.v2",NM="oc.sessions.pinned",Cl=Gt(),ep=(e,t,n)=>{const r=de(t);return!e||!r||!n?null:JSON.stringify([e,r,n])},Wb=e=>{try{const t=JSON.parse(e);if(!Array.isArray(t)||t.length!==3)return null;const[n,r,s]=t;if(typeof n!="string"||typeof r!="string"||typeof s!="string")return null;const o=de(r);return!n||!o||o!==r||!s?null:[n,o,s]}catch{return null}},cd=(e,t,n)=>{if(!t)return!1;const r=ep(Y(),t,n);return r?e.has(r):!1},LM=()=>{Cl.removeItem(NM);const e=Cl.getItem(Qh);if(e===null)return{ids:new Set,touchedAt:{}};try{const t=JSON.parse(e);if(t.version!==2||!t.sessions||typeof t.sessions!="object")return{ids:new Set,touchedAt:{}};const n=Object.entries(t.sessions).filter(([r,s])=>Wb(r)&&typeof s=="number"&&Number.isFinite(s)).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}}catch{return Cl.removeItem(Qh),{ids:new Set,touchedAt:{}}}},O0=(e,t)=>{const n=[...e].filter(r=>Wb(r)!==null).map(r=>[r,t[r]??Date.now()]).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}},H0=({ids:e,touchedAt:t})=>{const n=Object.fromEntries([...e].map(r=>[r,t[r]??Date.now()]));Cl.setItem(Qh,JSON.stringify({version:2,sessions:n}))},F0=LM(),Pm=Et((e,t)=>({ids:F0.ids,touchedAt:F0.touchedAt,setIds:n=>{const r=t().ids,s=typeof n=="function"?n(r):n;if(s===r)return;const o=O0(s,t().touchedAt);e(o),H0(o)},toggle:n=>{const r=ep(Y(),n.directory,n.sessionId);if(!r)return;const s=new Set(t().ids),o={...t().touchedAt};s.has(r)?(s.delete(r),delete o[r]):(s.add(r),o[r]=Date.now());const i=O0(s,o);e(i),H0(i)},clearPinnedSession:(n,r,s)=>{const o=ep(n,r,s);if(!o||!t().ids.has(o))return;const i=new Set(t().ids);i.delete(o),t().setIds(i)}})),OX=new Map,ld=new Map,Bo=new Map;let kl=0;const Ca=Et(()=>({rankById:new Map})),B0=()=>(kl=Math.max(kl+1,Date.now()),kl),RM=(e,t=!1)=>{const n=[...e];n.length!==0&&Ca.setState(r=>{const s=new Map(r.rankById),o=t?B0():null;for(const i of n)s.set(i,o??B0());return{rankById:s}})},PM=(e,t)=>{const n=ld.get(e);ld.set(e,t),t==="active"&&n!=="active"&&RM([e])},DM=e=>{ld.delete(e),Bo.delete(e),Ca.setState(t=>{if(!t.rankById.has(e))return t;const n=new Map(t.rankById);return n.delete(e),{rankById:n}})},HX=()=>{ld.clear(),Bo.clear(),kl=0,Ca.setState({rankById:new Map})},tp=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Kb=e=>tp(e.time?.updated)||tp(e.time?.created),OM=e=>tp(e.time?.created),np=e=>e.parentID??null,rp=e=>{const t=e;return de(t.directory??null)??de(t.project?.worktree??null)},Pi=(e,t)=>{const n=Bo.get(e.id),r=t?"created":"updated",s=n?.[r];if(s!==void 0)return s;const o=t?OM(e):Kb(e);return Bo.set(e.id,{...n,[r]:o}),o},HM=e=>{const t=Ca.getState().rankById;let n=!1;for(const r of e){const s=Kb(r);if(t.get(r.id)!==void 0)continue;const o=Bo.get(r.id);o?.updated!==void 0&&o.updated>=s||(Bo.set(r.id,{...o,updated:s}),n=!0)}n&&Ca.setState(r=>({rankById:new Map(r.rankById)}))},V0=(e,t,n=!1)=>t.get(e.id)??Pi(e,n),Gb=(e,t,n,r,s)=>{if(n!==r)return n?-1:1;const o=Pi(e,n),i=Pi(t,r);if(np(e)===np(t)){const d=V0(t,s,r)-V0(e,s,n);if(d!==0)return d}const a=i-o;if(a!==0)return a;const l=Pi(t,!0)-Pi(e,!0);return l!==0?l:e.id.localeCompare(t.id)},FX=(e,t,n,r)=>Gb(e,t,cd(n,rp(e),e.id),cd(n,rp(t),t.id),r),FM=(e,t,n=r=>r)=>{const r=new Map,s=o=>{let i=r.get(o);return i===void 0&&(i=cd(e,rp(o),o.id),r.set(o,i)),i};return(o,i)=>{const a=n(o),l=n(i);return Gb(a,l,s(a),s(l),t)}},BX=(e,t,n)=>{const r=new Set(e.map(f=>f.id)),s=[],o=new Map;for(const f of e){const u=np(f);if(!u||!r.has(u)){s.push(f);continue}const h=o.get(u);h?h.push(f):o.set(u,[f])}const i=FM(t,n);s.sort(i);for(const f of o.values())f.sort(i);const a=[],l=new Set,d=f=>{if(!l.has(f.id)){l.add(f.id),a.push(f);for(const u of o.get(f.id)??[])d(u)}};for(const f of s)d(f);for(const f of e)d(f);return a},$0=500,BM=1e3*60*60*24*30;function VM(e){const t=Date.now()-BM,n=e.filter(r=>r.time>=t);return n.length<=$0?n:n.slice(n.length-$0)}function ff(e){const t={session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}};for(const n of e)n.viewed||(n.session&&(t.session.unseenCount[n.session]=(t.session.unseenCount[n.session]??0)+1,n.type==="error"&&(t.session.unseenHasError[n.session]=!0)),n.directory&&(t.project.unseenCount[n.directory]=(t.project.unseenCount[n.directory]??0)+1,n.type==="error"&&(t.project.unseenHasError[n.directory]=!0)));return t}const tu=Et((e,t)=>({list:[],index:{session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}},append:n=>{const r=t().list,s=VM([...r,n]);e({list:s,index:ff(s)})},markSessionViewed:n=>{const r=t();if((r.index.session.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.session===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:ff(o)})},markProjectViewed:n=>{const r=t();if((r.index.project.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.directory===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:ff(o)})},sessionUnseenCount:n=>t().index.session.unseenCount[n]??0,sessionHasError:n=>t().index.session.unseenHasError[n]??!1,projectUnseenCount:n=>t().index.project.unseenCount[n]??0,projectHasError:n=>t().index.project.unseenHasError[n]??!1}));function nu(e){tu.getState().markSessionViewed(e)}function Zb(e,t,n){const r=tu.getState();(r.index.session.unseenCount[e]??0)>0||r.append(n?.error?{type:"error",session:e,directory:t,error:n.error,time:Date.now(),viewed:!1}:{type:"turn-complete",session:e,directory:t,time:Date.now(),viewed:!1})}function Yb(e){const t=re.getState();if(!t.nativeNotificationsEnabled||e.kind==="completion"&&!t.notifyOnCompletion||e.kind==="error"&&!t.notifyOnError)return;const n=zr()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to review the session.";n.notify({title:e.kind==="error"?"Work failed":"Work completed",body:r,tag:`pichamber:${e.kind}:${e.sessionId}:${e.sequence}`,kind:e.kind,sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function Dm(e,t){return`pichamber:input:${e}:${t}`}function Xb(e){const t=re.getState();if(!t.nativeNotificationsEnabled||t.notifyOnInputNeeded===!1)return;const n=zr()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to answer.";n.notify({title:e.kind==="approval"?"Approval needed":"Input needed",body:r,tag:Dm(e.sessionId,e.since),kind:"input",sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function $M(e){return tu(t=>t.index.session.unseenCount[e]??0)}const VX=Object.freeze(Object.defineProperty({__proto__:null,dispatchInputNeededNotification:Xb,dispatchSessionNotification:Yb,inputNeededNotificationTag:Dm,markSessionViewed:nu,notifySessionTurnComplete:Zb,useNotificationStore:tu,useSessionUnseenCount:$M},Symbol.toStringTag,{value:"Module"})),zM="pichamber_sync_perf",Om=()=>({pipelineRawEvents:0,pipelineCoalescedEvents:0,pipelineDeliveredEvents:0,reducerEvents:0,reducerChangedEvents:0,directoryStorePublications:0,streamingFullReconciliations:0,streamingIncrementalReconciliations:0,streamingStatusEntriesVisited:0,streamingSessionCandidatesVisited:0,streamingMessagesVisited:0,streamingHeartbeatAttempts:0,streamingHeartbeatCommits:0,permissionChangeCallbacks:0,questionChangeCallbacks:0,sessionMessageChangeCallbacks:0,sessionRenderableNotificationSkips:0,userMessageHistoryNotificationSkips:0,sessionMessageRecordNotificationSkips:0,materializationEnqueues:0,materializationEmptyAssistantEnqueues:0,materializationMissingMessageEnqueues:0,materializationMissingPartEnqueues:0,materializationLifecycleEnqueues:0,materializationPreflightSkips:0,materializationRequests:0,statusAggregationSessionEntries:0,statusAggregationCandidates:0,persistenceSerializations:0,persistenceStorageWrites:0,persistenceUtf8Bytes:0}),UM=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(zM)==="1"}catch{return!1}},Jb=UM();let Ml=Jb||Xo()?Om():null;const qM=()=>Xo()||Jb,Hm=()=>qM()?(Ml||(Ml=Om()),Ml):null;function Qb(){Hm()&&(Ml=Om())}function ew(){const e=Hm();return e?{...e}:null}function WM(e){const t=Hm();t&&(t.persistenceSerializations+=1,t.persistenceUtf8Bytes+=new TextEncoder().encode(e).byteLength)}typeof window<"u"&&(window.__pichamberSyncPerformance={getSnapshot:ew,reset:Qb});const sp="pichamber.chatDrafts.v2",KM=50,op=Gt(),ip=new Set;let Di,sr;const Jo=(e,t,n)=>{const r=de(t);return!e||!r?null:{runtimeKey:e,directory:r,sessionId:n}},Qt=e=>JSON.stringify([e.runtimeKey,e.directory,e.sessionId]),tw=()=>{const e=op.getItem(sp);if(e===Di&&sr)return sr;try{const t=JSON.parse(e??"");if(t.version!==2||!t.drafts||typeof t.drafts!="object"||Array.isArray(t.drafts))return Di=e,sr={version:2,drafts:{}},sr;const n={};for(const[r,s]of Object.entries(t.drafts)){if(!s||typeof s!="object")continue;const o=s;typeof o.text!="string"||!Array.isArray(o.confirmedMentions)||typeof o.touchedAt!="number"||(n[r]={text:o.text,confirmedMentions:o.confirmedMentions.filter(i=>typeof i=="string"),touchedAt:o.touchedAt})}return Di=e,sr={version:2,drafts:n},sr}catch{return op.removeItem(sp),Di=null,sr={version:2,drafts:{}},sr}},GM=e=>{const t=JSON.stringify(e);Di=t,sr=e,WM(t),op.setItem(sp,t)},ru=e=>{if(!e)return{text:"",confirmedMentions:new Set};const t=tw().drafts[Qt(e)];return t?{text:t.text,confirmedMentions:new Set(t.confirmedMentions)}:{text:"",confirmedMentions:new Set}},As=(e,t,n)=>{if(!e)return;const r=tw(),s=Qt(e),o=Array.from(new Set(n));if(!t&&o.length===0){if(!(s in r.drafts))return;delete r.drafts[s]}else r.drafts[s]={text:t,confirmedMentions:o,touchedAt:Date.now()};const i=Object.entries(r.drafts).sort((a,l)=>l[1].touchedAt-a[1].touchedAt).slice(0,KM);GM({version:2,drafts:Object.fromEntries(i)})},ZM=(e,t=!1)=>{As(e,"",[]),t&&ip.forEach(n=>n(e))},YM=e=>(ip.add(e),()=>ip.delete(e)),su=e=>({...e,previewUrl:void 0,uploadState:e.uploadState?{...e.uploadState}:e.uploadState}),XM=["image/png","image/jpeg","image/gif","image/webp","image/heic","image/heif","application/pdf","application/zip","application/x-zip-compressed","application/gzip","application/x-tar","application/x-7z-compressed","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","text/*","application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml",".bat",".c",".cc",".cjs",".cmd",".conf",".cpp",".cs",".css",".csv",".cts",".dart",".diff",".docx",".drawio",".env",".erl",".ex",".exs",".fs",".fsx",".go",".gql",".graphql",".h",".har",".hh",".hcl",".heic",".heif",".hpp",".hrl",".htm",".html",".ini",".ipynb",".java",".jl",".js",".json",".jsonl",".jsx",".kt",".kts",".log",".lua",".md",".mdx",".mjs",".mts",".ndjson",".odp",".ods",".odt",".patch",".php",".proto",".pptx",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sol",".sql",".svelte",".svg",".swift",".tf",".toml",".ts",".tsx",".txt",".vue",".xml",".xlsx",".yaml",".yml",".zig",".zip",".7z",".gz",".rar",".tar",".tgz",".zsh"],JM=XM.join(","),QM=e=>{const t=e.toLowerCase().split(";",1)[0]?.trim()??"";if(t.startsWith("image/"))return"image";if(t.startsWith("audio/"))return"audio";if(t.startsWith("video/"))return"video";if(t==="application/pdf")return"pdf";if(t.startsWith("text/"))return"text"},eI=(e,t)=>{const n=new Set(t.map(s=>s.toLowerCase())),r=[];for(const s of e){const o=QM(s.mimeType);o&&!n.has(o)&&r.push({attachment:s,modality:o})}return r},tI=new Map([["image/png","image/png"],["image/jpeg","image/jpeg"],["image/gif","image/gif"],["image/webp","image/webp"],["application/pdf","application/pdf"]]),nI=new Map([["gif","image/gif"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["pdf","application/pdf"],["png","image/png"],["webp","image/webp"]]),rI=new Set(["application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml","image/svg+xml"]),sI=4096,oI=new Set(["docx","pptx","xlsx","odt","odp","ods"]),Il="[REDACTED]",iI="[OMITTED BY PICHAMBER]",ap=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|client[-_]?secret|password|secret|access[-_]?token|refresh[-_]?token|id[-_]?token|token)$/i,Fm=e=>{const t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()},nw=e=>e.type.split(";",1)[0]?.trim().toLowerCase()??"",aI=async e=>{const t=new Uint8Array(await e.slice(0,sI).arrayBuffer());if(t.some(r=>r===0))return;const n=t.filter(r=>r<9||r>13&&r<32).length;if(!(t.length>0&&n/t.length>.3))return"text/plain"},cI=e=>{const t=nw(e),n=tI.get(t);if(n)return n;const r=Fm(e.name),s=nI.get(r);return(!t||t==="application/octet-stream")&&s?s:t.startsWith("text/")||rI.has(t)||t.endsWith("+json")||t.endsWith("+xml")?"text/plain":aI(e).then(o=>o||t||"application/octet-stream")},Rc=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):"",lI=(e,t)=>{if(!e||typeof e!="object")return;const n=e;if(!Array.isArray(n.cells))return;const r=typeof n.metadata?.kernelspec?.language=="string"?n.metadata.kernelspec.language:"",s=[`# Notebook: ${t}`];return n.cells.forEach((o,i)=>{if(!o||typeof o!="object")return;const a=o,l=Rc(a.source).trimEnd();if(a.cell_type==="markdown"){s.push(`## Markdown cell ${i+1}
9
-
10
- ${l}`);return}if(a.cell_type!=="code"||(s.push(`## Code cell ${i+1}
11
-
12
- \`\`\`${r}
13
- ${l}
14
- \`\`\``),!Array.isArray(a.outputs)))return;const d=[];for(const f of a.outputs){if(!f||typeof f!="object")continue;const u=f,h=Rc(u.text)||Rc(u.traceback);if(h){d.push(h.trimEnd());continue}if(u.data&&typeof u.data=="object"){const m=u.data,g=Rc(m["text/plain"]);g&&d.push(g.trimEnd());const x=Object.keys(m).filter(b=>b!=="text/plain");x.length>0&&d.push(`[Non-text output omitted: ${x.join(", ")}]`);continue}(typeof u.ename=="string"||typeof u.evalue=="string")&&d.push(`${String(u.ename??"Error")}: ${String(u.evalue??"")}`.trimEnd())}d.length>0&&s.push(`### Output
15
-
16
- ${d.join(`
17
-
18
- `)}`)}),`${s.join(`
19
-
20
- `)}
21
- `},dI=e=>{try{const t=new URL(e);for(const n of Array.from(t.searchParams.keys()))ap.test(n)&&t.searchParams.set(n,Il);return t.toString()}catch{return e}},cp=(e,t)=>{if(t&&ap.test(t))return Il;if(t==="cookies"&&Array.isArray(e))return e.map(s=>!s||typeof s!="object"?s:{...s,value:Il});if(t==="text"||t==="encoding")return iI;if(typeof e=="string")return t==="url"?dI(e):e;if(Array.isArray(e))return e.map(s=>cp(s));if(!e||typeof e!="object")return e;const n=e,r=typeof n.name=="string"&&ap.test(n.name);return Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r&&s==="value"?Il:cp(o,s)]))},uI=async(e,t)=>{const n=await e.text();if(t==="har")try{const r=cp(JSON.parse(n));return new File([`${JSON.stringify(r,null,2)}
22
- `],e.name,{type:"text/plain"})}catch{return}if(t==="ipynb")try{const r=lI(JSON.parse(n),e.name);if(r)return new File([r],e.name,{type:"text/plain"})}catch{}return new File([n],e.name,{type:"text/plain"})},fI=async e=>{try{const t=(await mt(async()=>{const{default:o}=await import("./vendor-heic2any-sztndhZI.js").then(i=>i.h);return{default:o}},__vite__mapDeps([0,1]))).default,n=await t({blob:e,toType:"image/jpeg",quality:.9}),r=Array.isArray(n)?n[0]:n;if(!r)return;const s=e.name.replace(/\.(heic|heif)$/i,".jpg");return new File([r],s,{type:"image/jpeg"})}catch(t){console.warn("Failed to convert HEIC attachment to JPEG",t);return}},z0=e=>{const t=Fm(e.name),n=nw(e);if(n==="image/heic"||n==="image/heif"||t==="heic"||t==="heif")return fI(e).then(s=>s?{file:s,mimeType:"image/jpeg"}:void 0);if(t==="har"||t==="ipynb")return uI(e,t).then(s=>s?{file:s,mimeType:"text/plain"}:void 0);const r=cI(e);return typeof r=="string"?{file:e,mimeType:r}:r?.then(s=>s?{file:e,mimeType:s}:void 0)},hI=(e,t=[])=>{if(!oI.has(Fm(e.name))){const n=z0(e);return n instanceof Promise?n.then(r=>r?[r]:void 0):n?[n]:void 0}return mt(()=>import("./document-attachments-CZl9rK1z.js"),__vite__mapDeps([2,3])).then(async({extractDocumentAttachments:n})=>{const r=await n(e,t);if(!r)return;const s=[{file:r.textFile,mimeType:"text/plain"}];for(const o of r.images){const i=await z0(o);if(!i||!i.mimeType.startsWith("image/"))return;s.push(i)}return s})},pI=3,mI=3,gI=100*1024*1024,Ys=20;let so=0,hf=0;const Vo=[],Co=new Map,ms=new Map,dd=new Map,U0=(e,t)=>{if(e.length===0)return!1;const n=new Set(t.map(r=>r.filename.toLowerCase()));return e.some(r=>n.has(r.toLowerCase()))},Pc=(e="attachment")=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`,yI=(e,t)=>{if(!(!t.startsWith("image/")||typeof URL.createObjectURL!="function"))return URL.createObjectURL(e)},q0=new Set,rw=e=>{!e||q0.has(e)||(q0.add(e),typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e))},vI=e=>{for(const t of e)rw(t.previewUrl)},xI=(e,t)=>new Promise((n,r)=>{const s=new FileReader;s.onload=()=>{const o=typeof s.result=="string"?s.result:"",i=o.indexOf(",");n(i===-1?o:`data:${t};base64,${o.slice(i+1)}`)},s.onerror=()=>r(s.error??new Error("Failed to read file")),s.onabort=()=>r(new Error("File read aborted")),s.readAsDataURL(e)}),sw=async e=>Promise.all(e.map(async t=>{if(t.source!=="local"||t.dataUrl.startsWith("data:"))return{...t,previewUrl:void 0};const n=t.file instanceof Blob?t.file:null;if(!n)throw new Error("Attachment data is unavailable");return{...t,dataUrl:await xI(n,t.mimeType),previewUrl:void 0}})),bI=e=>{if(!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(";base64"))return 0;let s=0;return r.endsWith("==")?s=2:r.endsWith("=")&&(s=1),Math.max(0,Math.floor(r.length*3/4)-s)},wI=(e,t)=>{const n=e.indexOf(",");if(!e.startsWith("data:")||n<0)return null;const r=e.slice(5,n);if(!r.toLowerCase().endsWith(";base64"))return null;try{const s=atob(e.slice(n+1)),o=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)o[i]=s.charCodeAt(i);return new Blob([o],{type:r.slice(0,-7)||t})}catch{return null}},SI=e=>{const t=typeof e=="object"&&e&&"code"in e?String(e.code):"";return t==="ATTACHMENT_TOO_LARGE"?"File exceeds the 100 MB upload limit.":t==="ATTACHMENT_LIMIT_REACHED"?"Too many unused uploads. Remove a file and retry.":t==="DAEMON_UNAVAILABLE"?"The runtime changed or is unavailable. Retry the upload.":e instanceof DOMException&&e.name==="AbortError"?"Upload canceled.":"Upload failed. Retry or remove this file."},an=(e,t)=>{let n=!1;return Ye.setState(r=>({attachedFiles:r.attachedFiles.map(s=>s.id!==e?s:(n=!0,t(s)))})),n},ow=()=>{for(;hf<mI&&Vo.length>0;){const e=Vo.shift();if(!e)continue;const t=Ye.getState().attachedFiles.find(n=>n.id===e);!t||t.source!=="local"||t.uploadState?.status!=="preparing"||(hf+=1,CI(e).finally(()=>{hf-=1,ow()}))}},pf=e=>{Vo.includes(e)||Co.has(e)||(Vo.push(e),ow())},CI=async e=>{const t=Ye.getState().attachedFiles.find(a=>a.id===e);if(!t||t.source!=="local")return;const n=t.file instanceof Blob?t.file:wI(t.dataUrl,t.mimeType);if(!n||n.size===0){an(e,a=>({...a,uploadState:{status:"failed",error:"The file data is no longer available."}}));return}const r=Y(),s=(ms.get(e)??0)+1;ms.set(e,s);const o=new AbortController;Co.set(e,o);let i=-1;an(e,a=>({...a,uploadState:{status:"uploading",progress:n.size>0?0:null}}));try{const a=await Ie.uploadAttachment(n,{filename:t.filename,mime:t.mimeType,signal:o.signal,onProgress:({loaded:d,total:f})=>{const u=f>0?Math.min(99,Math.floor(d/f*100)):null;u!==i&&(i=u??i,!(ms.get(e)!==s||r!==Y())&&an(e,h=>h.uploadState?.status==="uploading"?{...h,uploadState:{status:"uploading",progress:u}}:h))}},{runtimeKey:r});if(ms.get(e)!==s||r!==Y()){Ie.deleteAttachment(a.id,{runtimeKey:r}).catch(()=>{});return}an(e,d=>({...d,uploadState:{status:"ready",attachmentId:a.id,expiresAt:a.expiresAt}}));const l=setTimeout(()=>{dd.delete(e),an(e,d=>d.uploadState?.status==="ready"&&d.uploadState.attachmentId===a.id?{...d,uploadState:{status:"failed",error:"Upload expired. Retry the upload."}}:d)},Math.max(0,a.expiresAt-Date.now()+1));dd.set(e,l)}catch(a){if(ms.get(e)!==s)return;an(e,l=>({...l,uploadState:{status:"failed",error:SI(a)}}))}finally{Co.get(e)===o&&Co.delete(e)}},lp=e=>{ms.set(e.id,(ms.get(e.id)??0)+1),Co.get(e.id)?.abort(),Co.delete(e.id);const t=dd.get(e.id);t&&clearTimeout(t),dd.delete(e.id);const n=Vo.indexOf(e.id);n>=0&&Vo.splice(n,1)},kI=(e,t)=>{lp(e),rw(e.previewUrl),t&&e.uploadState?.status==="ready"&&Ie.deleteAttachment(e.uploadState.attachmentId,{runtimeKey:Y()}).catch(()=>{})},tr=(e,t)=>{for(const n of e)kI(n,t)},MI=10,II=50*1024*1024,EI=e=>{let t=0;for(const n of Object.values(e))for(const r of n)t+=Number.isFinite(r.size)?r.size:0;return t};let W0=0;const _I=(e,t,n)=>!e||e.draftKey!==t?!1:n===e.text,Ye=Et()((e,t)=>({pendingInputText:null,pendingInputMode:"replace",pendingRevertText:null,pendingSyntheticParts:null,pendingStarterInsert:null,pendingWorktreeRestore:null,attachedFiles:[],stashedAttachmentsByDraft:{},activeAttachmentsDraftKey:null,sentDraftClear:null,setPendingInputText:(n,r="replace")=>e({pendingInputText:n,pendingInputMode:r}),consumePendingInputText:()=>{const{pendingInputText:n,pendingInputMode:r}=t();return n===null?null:(e({pendingInputText:null,pendingInputMode:"replace"}),{text:n,mode:r})},setPendingRevertText:n=>e({pendingRevertText:n}),consumePendingRevertText:()=>{const{pendingRevertText:n}=t();return n===null?null:(e({pendingRevertText:null}),n)},requestStarterInsert:n=>e({pendingStarterInsert:{name:n}}),requestStarterTextInsert:n=>e({pendingStarterInsert:{text:n}}),consumePendingStarterInsert:()=>{const{pendingStarterInsert:n}=t();return n===null?null:(e({pendingStarterInsert:null}),n)},setPendingSyntheticParts:n=>e({pendingSyntheticParts:n}),consumePendingSyntheticParts:()=>{const{pendingSyntheticParts:n}=t();return n!==null&&e({pendingSyntheticParts:null}),n},requestWorktreeRestore:n=>e({pendingWorktreeRestore:n}),consumePendingWorktreeRestore:()=>{const{pendingWorktreeRestore:n}=t();return n===null?null:(e({pendingWorktreeRestore:null}),n)},resetForRuntimeSwitch:()=>{t().pendingWorktreeRestore!==null&&e({pendingWorktreeRestore:null}),t().sentDraftClear!==null&&e({sentDraftClear:null})},publishSentDraftClear:(n,r)=>{n&&(W0+=1,e({sentDraftClear:{draftKey:n,text:r,nonce:W0}}))},consumeSentDraftClear:n=>{t().sentDraftClear?.nonce===n&&e({sentDraftClear:null})},addAttachedFile:async n=>{const r=so,s=Pc("preparing"),o={id:s,file:n,dataUrl:"",mimeType:n.type||"application/octet-stream",filename:n.name,size:n.size,source:"local",uploadState:{status:"preparing"}};if(e(i=>({attachedFiles:[...i.attachedFiles,o]})),t().attachedFiles.length>Ys)return an(s,i=>({...i,uploadState:{status:"failed",error:`You can attach up to ${Ys} files to one message.`}})),!1;for(let i=0;i<pI;i+=1){const a=t().attachedFiles.filter(h=>h.id!==s).map(h=>h.filename);let l;try{const h=hI(n,a);l=h instanceof Promise?await h:h}catch{l=null}if(r!==so||!t().attachedFiles.some(h=>h.id===s))return!1;if(!l||l.length===0)return an(s,h=>({...h,uploadState:{status:"failed",error:"This file could not be prepared."}})),!1;if(t().attachedFiles.length-1+l.length>Ys)return an(s,h=>({...h,uploadState:{status:"failed",error:`You can attach up to ${Ys} files to one message.`}})),!1;if(l.some(h=>h.file.size>gI))return an(s,h=>({...h,uploadState:{status:"failed",error:"File exceeds the 100 MB upload limit."}})),!1;const d=l.slice(1).map(h=>h.file.name);if(U0(d,t().attachedFiles.filter(h=>h.id!==s)))continue;const f=l.length>1?Pc("document"):void 0,u=l.map(h=>({id:Pc(),file:h.file,dataUrl:"",previewUrl:yI(h.file,h.mimeType),mimeType:h.mimeType,filename:h.file.name,size:h.file.size,source:"local",uploadState:{status:"preparing"},sourceDocumentId:f}));if(r!==so)return tr(u,!1),!1;if(U0(d,t().attachedFiles.filter(h=>h.id!==s))){tr(u,!1);continue}e(h=>({attachedFiles:h.attachedFiles.flatMap(m=>m.id===s?u:[m])}));for(const h of u)pf(h.id);return!0}return an(s,i=>({...i,uploadState:{status:"failed",error:"Generated filenames conflict with existing attachments."}})),!1},retryAttachmentUpload:n=>{const r=t().attachedFiles.find(s=>s.id===n);if(!(!r||r.source!=="local")){if(r.sourceDocumentId){for(const s of t().attachedFiles.filter(o=>o.sourceDocumentId===r.sourceDocumentId))(s.uploadState?.status==="failed"||s.uploadState?.status==="ready"&&s.uploadState.expiresAt<=Date.now())&&(an(s.id,o=>({...o,uploadState:{status:"preparing"}})),pf(s.id));return}an(n,s=>({...s,uploadState:{status:"preparing"}})),pf(n)}},removeAttachedFile:n=>{const r=t().attachedFiles.find(i=>i.id===n);if(!r)return;const s=r.sourceDocumentId?t().attachedFiles.filter(i=>i.sourceDocumentId===r.sourceDocumentId):[r];tr(s,!0);const o=new Set(s.map(i=>i.id));e(i=>({attachedFiles:i.attachedFiles.filter(a=>!o.has(a.id))}))},detachAttachedFiles:n=>{const r=new Set(n),s=t().attachedFiles.filter(a=>r.has(a.id));tr(s,!1);const o=t().stashedAttachmentsByDraft;let i=o;if(o){i={};for(const[a,l]of Object.entries(o)){const d=l.filter(f=>!r.has(f.id));vI(l.filter(f=>r.has(f.id))),d.length>0&&(i[a]=d)}}e(a=>({attachedFiles:a.attachedFiles.filter(l=>!r.has(l.id)),stashedAttachmentsByDraft:i}))},restoreAttachmentsForRetry:n=>{const r=t().attachedFiles.length;if(!n||n.length===0)return{ok:!0,restoredCount:0,totalCount:r};const s=new Set(t().attachedFiles.map(f=>f.id)),o=new Set,i=[];for(const f of n)s.has(f.id)||o.has(f.id)||(o.add(f.id),i.push(f));if(i.length===0)return{ok:!0,restoredCount:0,totalCount:r};if(r+i.length>Ys)return{ok:!1,reason:"attachment-limit",limit:Ys,currentCount:r,missingCount:i.length};const a=new Set(i.map(f=>f.id)),l=t().stashedAttachmentsByDraft??{},d={};for(const[f,u]of Object.entries(l)){const h=u.filter(m=>!a.has(m.id));h.length>0&&(d[f]=h)}return e(f=>({attachedFiles:[...f.attachedFiles,...i.map(su)],stashedAttachmentsByDraft:d})),{ok:!0,restoredCount:i.length,totalCount:r+i.length}},activateAttachmentsDraft:n=>{const r=t().activeAttachmentsDraftKey;if(r===null){e({activeAttachmentsDraftKey:n});return}if(r===n)return;const s=t().stashedAttachmentsByDraft,o=t().attachedFiles,i=s[n]??[],a={};for(const[d,f]of Object.entries(s))d!==r&&d!==n&&(a[d]=f);o.length>0&&(a[r]=o);const l=Object.keys(a);for(;l.length>MI||EI(a)>II;){const d=l.shift();if(!d)break;tr(a[d]??[],!0),delete a[d]}e({attachedFiles:i,stashedAttachmentsByDraft:a,activeAttachmentsDraftKey:n})},clearStashedAttachmentsForSession:n=>{const r=a=>{try{const l=JSON.parse(a);return Array.isArray(l)&&l[0]===n.runtimeKey&&l[1]===n.directory&&l[2]===n.sessionId}catch{return!1}},s=t(),o={};for(const[a,l]of Object.entries(s.stashedAttachmentsByDraft))r(a)?tr(l,!0):o[a]=l;const i=s.activeAttachmentsDraftKey!==null&&r(s.activeAttachmentsDraftKey);i&&tr(s.attachedFiles,!0),e({attachedFiles:i?[]:s.attachedFiles,stashedAttachmentsByDraft:o})},setAttachedFiles:n=>{so+=1;const r=new Set(n.map(s=>s.id));tr(t().attachedFiles.filter(s=>!r.has(s.id)),!1),e({attachedFiles:n.map(s=>s.source==="local"&&s.uploadState===void 0?{...s,uploadState:{status:"failed",error:"Upload needs to be refreshed. Retry the upload."}}:s)})},clearAttachedFiles:()=>{so+=1,tr(t().attachedFiles,!0),e({attachedFiles:[]})},addRestoredAttachment:({url:n,mimeType:r,filename:s})=>{const o=Pc("restored"),i=new File([],s,{type:r}),a={id:o,file:i,dataUrl:n,mimeType:r,filename:s,size:bI(n),source:"server",serverPath:n};e(l=>({attachedFiles:[...l.attachedFiles,a]}))}}));A5(()=>{so+=1;const e=s=>s.map(o=>o.source==="local"?{...o,uploadState:{status:"failed",error:"The runtime changed. Retry the upload."}}:o),t=Ye.getState().attachedFiles;for(const s of t)lp(s);const n=Ye.getState().stashedAttachmentsByDraft??{},r={};for(const[s,o]of Object.entries(n)){for(const i of o)lp(i);r[s]=e(o)}Ye.setState({attachedFiles:e(t),stashedAttachmentsByDraft:r,pendingWorktreeRestore:null,sentDraftClear:null})});const ko="oc.sessions.folders",Mo="oc.sessions.folderCollapse",ud="oc.sessions.folders.v2.index",iw="/api/pi/session-folders",jI=250,zt=Gt(),mf=Wd();let ws=null,ta=!1,El=!1,na=!1,ra,sa,oa=null,ia=null,$o=null,Rn=Y(),Is=0,fd=0;const hd=new Map,qr=(e,t)=>`${e}.v2:${encodeURIComponent(t)}`,Bm=()=>{try{const e=JSON.parse(zt.getItem(ud)??"");return e.version===2&&Array.isArray(e.runtimes)?{version:2,legacyClaimed:!!e.legacyClaimed,runtimes:e.runtimes}:{version:2,legacyClaimed:!1,runtimes:[]}}catch{return{version:2,legacyClaimed:!1,runtimes:[]}}},ka=(e,t=Date.now(),n=zt)=>{const r=Bm(),s=[{runtimeKey:e,updatedAt:t},...r.runtimes.filter(o=>o.runtimeKey!==e)];n.setItem(ud,JSON.stringify({version:2,legacyClaimed:r.legacyClaimed,runtimes:s}))},aw=e=>{const t=Bm();if(t.legacyClaimed)return;const n=zt.getItem(ko),r=zt.getItem(Mo);n&&zt.setItem(qr(ko,e),n),r&&zt.setItem(qr(Mo,e),r);const s={...t,legacyClaimed:!0};zt.setItem(ud,JSON.stringify(s)),zt.getItem(ud)===JSON.stringify(s)&&(zt.removeItem(ko),zt.removeItem(Mo)),ka(e,0)},TI=(e,t)=>{if(typeof window>"u")return;ws&&clearTimeout(ws);const n=JSON.parse(JSON.stringify(e)),r=Array.from(t),s=Rn,o=Is;ws=setTimeout(()=>{if(ws=null,s!==Y()||o!==Is)return;const i=Math.max(Date.now(),(hd.get(s)??0)+1);hd.set(s,i),Rt(iw,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:1,foldersMap:n,collapsedFolderIds:r,updatedAt:i})}).then(l=>{l.status===409&&(s!==Y()||o!==Is||(ta=!1,na=!0,ou()))}).catch(()=>{})},jI)},K0=(e=Rn)=>{try{aw(e);const t=zt.getItem(qr(ko,e));if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};const r={};for(const[s,o]of Object.entries(n)){if(!Array.isArray(o))continue;const i=[];for(const a of o){if(!a||typeof a!="object")continue;const l=a,d=typeof l.id=="string"?l.id.trim():"",f=typeof l.name=="string"?l.name.trim():"",u=typeof l.createdAt=="number"?l.createdAt:0;if(!d||!f)continue;const h=Array.isArray(l.sessionIds)?l.sessionIds.filter(g=>typeof g=="string"&&g.trim().length>0):[],m=typeof l.parentId=="string"?l.parentId:null;i.push({id:d,name:f,sessionIds:h,createdAt:u,parentId:m})}i.length>0&&(r[s]=i)}return r}catch{return{}}},G0=(e=Rn)=>{try{aw(e);const t=zt.getItem(qr(Mo,e));if(!t)return new Set;const n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}},cw=e=>{oa=e,$o=Rn,clearTimeout(ra),ra=setTimeout(()=>{try{const t=$o??Rn;zt.setItem(qr(ko,t),JSON.stringify(e)),ka(t),oa=null}catch{}},300)},lw=e=>{ia=e,$o=Rn,clearTimeout(sa),sa=setTimeout(()=>{try{const t=$o??Rn;zt.setItem(qr(Mo,t),JSON.stringify(Array.from(e))),ka(t),ia=null}catch{}},300)},dw=()=>{ra&&clearTimeout(ra),sa&&clearTimeout(sa),ra=void 0,sa=void 0;const e=$o??Rn;let t=!1;if(oa!==null){const n=qr(ko,e),r=JSON.stringify(oa);zt.setItem(n,r),mf.setItem(n,r),oa=null,t=!0}if(ia!==null){const n=qr(Mo,e),r=JSON.stringify(Array.from(ia));zt.setItem(n,r),mf.setItem(n,r),ia=null,t=!0}if(t){const n=Date.now();ka(e,n),ka(e,n,mf)}$o=null};if(typeof window<"u"){const e=()=>{try{dw()}catch{}};window.addEventListener("pagehide",e,{capture:!0}),window.addEventListener("beforeunload",e,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),document.addEventListener("freeze",e))}const nr=(e,t)=>{fd+=1,cw(e),lw(t),TI(e,t)},AI=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,mi=(e,t,n)=>{const r=new Set(t.map(o=>o.id));let s=null;for(const o of e)!r.has(o.id)&&n.has(o.id)&&(s||(s=new Set(n)),s.delete(o.id));return s},Vm=Et()(gr((e,t)=>({foldersMap:K0(),collapsedFolderIds:G0(),resetForRuntimeSwitch:n=>{try{dw()}catch{}Rn=n,Is+=1,fd=0,ta=!1,El=!1,na=!1,ws&&clearTimeout(ws),ws=null,e({foldersMap:K0(n),collapsedFolderIds:G0(n)}),queueMicrotask(()=>{ou()})},getFoldersForScope:n=>n?t().foldersMap[n]??[]:[],createFolder:(n,r,s)=>{const o=r.trim()||"New folder",i={id:AI(),name:o,sessionIds:[],createdAt:Date.now(),parentId:s??null},a=t().foldersMap,l=a[n]??[],d={...a,[n]:[...l,i]};return e({foldersMap:d}),nr(d,t().collapsedFolderIds),i},renameFolder:(n,r,s)=>{const o=s.trim();if(!o||!n)return;const i=t().foldersMap,a=i[n];if(!a)return;const l=a.map(f=>f.id===r?{...f,name:o}:f),d={...i,[n]:l};e({foldersMap:d}),nr(d,t().collapsedFolderIds)},deleteFolder:(n,r)=>{if(!n)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set([r]);let a=!0;for(;a;){a=!1;for(const h of o)h.parentId&&i.has(h.parentId)&&!i.has(h.id)&&(i.add(h.id),a=!0)}const l=o.filter(h=>!i.has(h.id)),d={...s,[n]:l},f=t().collapsedFolderIds,u=mi(o,l,f);e(u?{foldersMap:d,collapsedFolderIds:u}:{foldersMap:d}),nr(d,u??f)},addSessionToFolder:(n,r,s)=>{if(!n||!r||!s)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=i.find(h=>h.id===r);if(!a)return;const l=i.reduce((h,m)=>h+(m.sessionIds.includes(s)?1:0),0);if(a.sessionIds.includes(s)&&l===1)return;const d=i.map(h=>{const m=h.sessionIds.filter(g=>g!==s);return h.id===r?{...h,sessionIds:[...m,s]}:m.length!==h.sessionIds.length?{...h,sessionIds:m}:h}),f={...o,[n]:d},u=mi(i,d,t().collapsedFolderIds);e(u?{foldersMap:f,collapsedFolderIds:u}:{foldersMap:f}),nr(f,u??t().collapsedFolderIds)},addSessionsToFolder:(n,r,s)=>{if(!n||!r||s.length===0)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=new Set(s.filter(m=>typeof m=="string"&&m.length>0));if(a.size===0)return;const l=i.find(m=>m.id===r);if(!l)return;let d=!1;for(const m of i){for(const g of a)if(m.sessionIds.includes(g)&&(m.id!==r||!l.sessionIds.includes(g))){d=!0;break}if(d)break}if(!d){for(const m of a)if(!l.sessionIds.includes(m)){d=!0;break}}if(!d)return;const f=i.map(m=>{const g=m.sessionIds.filter(x=>!a.has(x));return m.id===r?{...m,sessionIds:[...g,...a]}:g.length!==m.sessionIds.length?{...m,sessionIds:g}:m}),u={...o,[n]:f},h=mi(i,f,t().collapsedFolderIds);e(h?{foldersMap:u,collapsedFolderIds:h}:{foldersMap:u}),nr(u,h??t().collapsedFolderIds)},removeSessionsFromFolders:(n,r)=>{if(!n||r.length===0)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set(r.filter(u=>typeof u=="string"&&u.length>0));if(i.size===0)return;let a=!1;const l=o.map(u=>{const h=u.sessionIds.filter(m=>!i.has(m));return h.length!==u.sessionIds.length?(a=!0,{...u,sessionIds:h}):u});if(!a)return;const d={...s,[n]:l},f=mi(o,l,t().collapsedFolderIds);e(f?{foldersMap:d,collapsedFolderIds:f}:{foldersMap:d}),nr(d,f??t().collapsedFolderIds)},removeSessionFromFolder:(n,r)=>{if(!n||!r)return;const s=t().foldersMap,o=s[n];if(!o)return;let i=!1;const a=o.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length!==f.sessionIds.length?(i=!0,{...f,sessionIds:u}):f});if(!i)return;const l={...s,[n]:a},d=mi(o,a,t().collapsedFolderIds);e(d?{foldersMap:l,collapsedFolderIds:d}:{foldersMap:l}),nr(l,d??t().collapsedFolderIds)},removeSessionEverywhere:(n,r)=>{if(!n||n!==Rn||n!==Y()||!r)return;const s=t().foldersMap;let o=null;for(const[i,a]of Object.entries(s)){let l=!1;const d=a.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length===f.sessionIds.length?f:(l=!0,{...f,sessionIds:u})});l&&(o??={...s},o[i]=d)}o&&(e({foldersMap:o}),nr(o,t().collapsedFolderIds))},toggleFolderCollapse:n=>{const r=t().collapsedFolderIds,s=new Set(r);s.has(n)?s.delete(n):s.add(n),e({collapsedFolderIds:s}),nr(t().foldersMap,s)},getSessionFolderId:(n,r)=>{if(!n||!r)return null;const s=t().foldersMap[n];if(!s)return null;for(const o of s)if(o.sessionIds.includes(r))return o.id;return null}}),{name:"session-folders-store"})),ou=async()=>{if(typeof window>"u"||El||ta&&!na)return;na=!1,El=!0;const e=Rn,t=Is,n=fd;let r=!1;try{const s=await Rt(iw).catch(()=>null);if(!s||!s.ok)return;const o=await s.json().catch(()=>null);if(!o)return;if(o.exists===!1){r=!0;return}const i=o.foldersMap&&typeof o.foldersMap=="object"?o.foldersMap:{},a=Array.isArray(o.collapsedFolderIds)?new Set(o.collapsedFolderIds.filter(u=>typeof u=="string")):new Set;if(t!==Is||e!==Y())return;const l=Bm().runtimes.find(u=>u.runtimeKey===e)?.updatedAt??0,d=typeof o.updatedAt=="number"&&Number.isFinite(o.updatedAt)?o.updatedAt:0;d>0&&hd.set(e,Math.max(hd.get(e)??0,d)),(o.exists===!0||d>0)&&fd===n&&d>=l&&(Vm.setState({foldersMap:i,collapsedFolderIds:a}),cw(i),lw(a)),r=!0}catch{}finally{t===Is&&e===Y()&&(El=!1,r&&(ta=!0),na&&(ta=!1,queueMicrotask(()=>{ou()})))}},NI=()=>{typeof window>"u"||ou()};NI();const LI=e=>{if(e.runtimeKey!==Y()||!e.directory||e.directory==="global"||!e.sessionId)return;const t=ym(e.sessionId,e.directory,e.runtimeKey);t&&ft.getState().clearQueue(t),Vm.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),Pm.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Jo(e.runtimeKey,e.directory,e.sessionId);n&&ZM(n,!0),Ye.getState().clearStashedAttachmentsForSession(e)},Ma=e=>{if(!e||e.streamingMessages.size===0)return null;let t=null;for(const n of e.streamingMessages){const r=e.messages.get(n);r?.role==="assistant"&&(t=r.id)}return t},RI=(e,t)=>e.sessionId===t.sessionId&&e.directory===t.directory&&e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder&&e.streamingMessages===t.streamingMessages&&e.lifecycle===t.lifecycle&&e.model===t.model&&e.thinking===t.thinking&&e.queue===t.queue,PI=e=>{let t=null;for(const n of e.messages.values())n.role==="user"&&(t=n.id);return t},uw=e=>{const t=e?.awaitingPromptEcho?.baselineUserMessageId;return!e||e.awaitingPromptEcho===void 0?!1:PI(e)===t},DI=(e,t)=>{if(e===t||e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder)return!0;if(e.messages.size!==t.messages.size||t.lastMutationKind==="structure")return!1;if(t.lastMutationKind==="part"&&t.lastMutatedMessageId)return t.messages.get(t.lastMutatedMessageId)?.role!=="user";const n=Ma(t);return n?dp(e,t,n):!1},dp=(e,t,n)=>e===t?!0:e.messages.size!==t.messages.size||e.messages!==t.messages||t.lastMutationKind==="structure"?!1:t.lastMutationKind==="part"&&t.lastMutatedMessageId===n?!0:t.lastMutationKind==="part"&&t.lastMutatedMessageId&&t.lastMutatedMessageId!==n?!1:HI(e,t,n),OI=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},HI=(e,t,n)=>{for(const[r,s]of t.messages){const o=e.messages.get(r);if(!o||o.id!==s.id)return!1;if(r===n)continue;if(o!==s)return!1;const i=e.partOrder.get(r)??[],a=t.partOrder.get(r)??[];if(!OI(i,a))return!1;for(const l of a)if(e.parts.get(l)!==t.parts.get(l))return!1}for(const r of e.messages.keys())if(!t.messages.has(r))return!1;return!0},FI="selection-store",BI=3,Z0="context-store",Y0=1,Io=500,Ia=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ns=e=>typeof e=="string",$m=e=>typeof e=="object"&&e!==null&&typeof e.providerId=="string"&&typeof e.modelId=="string",X0=(e,t)=>`${e}/${t}`,J0=(e,t,n)=>JSON.stringify([e,t,n]),VI=(e,t)=>JSON.stringify([e,t]),Tn=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===3&&t.every(Ns))return t}catch{}return null},gf=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===2&&t.every(Ns))return t}catch{}return null},oo=new Set,io=new Set,_r=new Set;let up=!1;const $I=()=>{oo.clear(),io.clear(),_r.clear(),up=!1},iu=e=>{if(!Array.isArray(e))return[];const t=new Set,n=[];for(const r of e)typeof r!="string"||t.has(r)||(t.add(r),n.push(r));return n},zI=e=>{const t=iu(e.sessionRecency),n=new Set(t),r=s=>{n.has(s)||(n.add(s),t.push(s))};for(const s of e.sessionModelSelections.keys())r(s);for(const s of e.sessionAgentSelections.keys())r(s);for(const s of e.sessionAgentModelSelections.keys())r(s);for(const s of e.sessionAgentModelVariantSelections.keys())r(s);for(const s of e.clearedVariantKeys){const o=typeof s=="string"?Tn(s):null;o&&r(o[0])}return t},Dc=(e,t)=>{let n=null;for(const r of t)(n??e).has(r)&&(n||(n=new Map(e)),n.delete(r));return n??e},Oc=(e,t)=>{if(!e.has(t))return e;const n=new Map(e);return n.delete(t),n},as=(e,t=[])=>{const n=zI(e);for(const o of t){const i=n.indexOf(o);i!==-1&&n.splice(i,1),n.push(o)}if(n.length<=Io){const o=e.sessionRecency;return o.length===n.length&&o.every((a,l)=>a===n[l])?e:{...e,sessionRecency:n}}const r=new Set(n.slice(0,n.length-Io));let s=e.clearedVariantKeys;return s.some(o=>{const i=typeof o=="string"?Tn(o):null;return i!==null&&r.has(i[0])})&&(s=s.filter(o=>{const i=typeof o=="string"?Tn(o):null;return i===null||!r.has(i[0])})),{sessionModelSelections:Dc(e.sessionModelSelections,r),sessionAgentSelections:Dc(e.sessionAgentSelections,r),sessionAgentModelSelections:Dc(e.sessionAgentModelSelections,r),sessionAgentModelVariantSelections:Dc(e.sessionAgentModelVariantSelections,r),clearedVariantKeys:s,sessionRecency:n.slice(n.length-Io)}},Q0=(e,t)=>e.sessionModelSelections.has(t)||e.sessionAgentSelections.has(t)||e.sessionAgentModelSelections.has(t)||e.sessionAgentModelVariantSelections.has(t)||e.sessionRecency.includes(t)?!0:e.clearedVariantKeys.some(n=>Tn(n)?.[0]===t),UI=e=>{const t=iu(e.sessionRecency),n=new Set(t),r=o=>{typeof o=="string"&&!n.has(o)&&(n.add(o),t.push(o))},s=o=>{if(Array.isArray(o))for(const i of o)Array.isArray(i)&&i.length>0&&r(i[0])};if(s(e.sessionModelSelections),s(e.sessionAgentSelections),s(e.sessionAgentModelSelections),s(e.sessionAgentModelVariantSelections),Array.isArray(e.clearedVariantKeys)){for(const o of e.clearedVariantKeys)if(typeof o=="string"){const i=Tn(o);i&&r(i[0])}}return t},Hc=(e,t)=>Array.isArray(e)?e.filter(n=>{const r=Array.isArray(n)&&n.length>0&&typeof n[0]=="string"?n[0]:null;return r===null||t.has(r)}):e,qI=(e,t)=>Array.isArray(e)?e.filter(n=>{if(typeof n!="string")return!0;const r=Tn(n);return r===null||t.has(r[0])}):e,WI=e=>{if(!Ia(e))return e;try{const t=UI(e),n=iu(e.sessionRecency),r=n.length===t.length&&n.every((o,i)=>o===t[i])&&Array.isArray(e.sessionRecency)&&e.sessionRecency.length===n.length;if(t.length<=Io)return r?e:{...e,sessionRecency:t};const s=new Set(t.slice(t.length-Io));return{...e,sessionModelSelections:Hc(e.sessionModelSelections,s),sessionAgentSelections:Hc(e.sessionAgentSelections,s),sessionAgentModelSelections:Hc(e.sessionAgentModelSelections,s),sessionAgentModelVariantSelections:Hc(e.sessionAgentModelVariantSelections,s),clearedVariantKeys:qI(e.clearedVariantKeys,s),sessionRecency:t.slice(t.length-Io)}}catch{return e}},e2=(e,t,n)=>{e.delete(t),e.set(t,n)},Es=(e,t)=>{const n=new Map;if(e===void 0)return{value:n,failed:!1};if(!Array.isArray(e))return{value:n,failed:!0};let r=!1;for(const s of e){if(!Array.isArray(s)||s.length!==2){r=!0;continue}const[o,i]=s;if(typeof o!="string"||!t(i)){r=!0;continue}n.set(o,i)}return{value:n,failed:r}},fw=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=Es(o,$m);i.failed&&(n=!0),(i.value.size>0||o.length===0)&&t.set(s,i.value)}return{value:t,failed:n}},hw=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=new Map;for(const a of o){if(!Array.isArray(a)||a.length!==2){n=!0;continue}const[l,d]=a;if(typeof l!="string"||!Array.isArray(d)){n=!0;continue}const f=Es(d,Ns);f.failed&&(n=!0),f.value.size>0&&i.set(l,f.value)}i.size>0&&t.set(s,i)}return{value:t,failed:n}},Ss=()=>({models:new Map,agents:new Map,agentModels:new Map,variants:new Map,currentAgentContext:new Map}),t2=e=>{if(e===null)return{status:"missing",failed:!1,data:Ss()};let t;try{t=JSON.parse(e)}catch{return{status:"failed",failed:!0,data:Ss()}}if(!Ia(t))return{status:"failed",failed:!0,data:Ss()};const n="state"in t?t.state:t;if(!Ia(n))return{status:"failed",failed:!0,data:Ss()};const r=Es(n.sessionModelSelections??void 0,$m),s=Es(n.sessionAgentSelections??void 0,Ns),o=fw(n.sessionAgentModelSelections??void 0),i=hw(n.sessionAgentModelVariantSelections??void 0),a=Es(n.currentAgentContext??void 0,Ns),l=r.failed||s.failed||o.failed||i.failed||a.failed;return{status:l?"failed":"ok",failed:l,data:{models:r.value,agents:s.value,agentModels:o.value,variants:i.value,currentAgentContext:a.value}}},KI=()=>{try{if(typeof window<"u"&&window.localStorage)return t2(window.localStorage.getItem(Z0))}catch{return{status:"failed",failed:!0,data:Ss()}}try{return t2(Wd().getItem(Z0))}catch{return{status:"failed",failed:!0,data:Ss()}}},GI=(e,t,n,r)=>{const s=e.get(t),o=s?.get(n);return o?.has(r)?(o.delete(r),o.size===0&&s?.delete(n),s&&s.size===0&&e.delete(t),!0):!1},Lt=Et()(Gd((e,t)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,lastUsedProvider:null,hasHydrated:typeof window>"u",contextStoreMigrationVersion:void 0,clearedVariantKeys:[],sessionRecency:[],saveSessionModelSelection:(n,r,s)=>{oo.add(n),up=!0,e(o=>{const i=new Map(o.sessionModelSelections);return i.delete(n),i.set(n,{providerId:r,modelId:s}),{...as({...o,sessionModelSelections:i},[n]),lastUsedProvider:{providerID:r,modelID:s}}})},getSessionModelSelection:n=>t().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,r)=>{t().sessionAgentSelections.get(n)!==r&&(oo.add(n),e(s=>{if(s.sessionAgentSelections.get(n)===r)return s;const o=new Map(s.sessionAgentSelections);return o.delete(n),o.set(n,r),as({...s,sessionAgentSelections:o},[n])}))},getSessionAgentSelection:n=>t().sessionAgentSelections.get(n)??null,saveAgentModelForSession:(n,r,s,o)=>{const i=t().sessionAgentModelSelections.get(n)?.get(r);i?.providerId===s&&i?.modelId===o||(io.add(VI(n,r)),e(a=>{const l=a.sessionAgentModelSelections.get(n)?.get(r);if(l?.providerId===s&&l?.modelId===o)return a;const d=new Map(a.sessionAgentModelSelections),f=new Map(d.get(n)??new Map);return d.delete(n),f.set(r,{providerId:s,modelId:o}),d.set(n,f),as({...a,sessionAgentModelSelections:d},[n])}))},getAgentModelForSession:(n,r)=>t().sessionAgentModelSelections.get(n)?.get(r)??null,saveAgentModelVariantForSession:(n,r,s,o,i)=>{const a=X0(s,o),l=J0(n,r,a);if(i===void 0){if(t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0){t().hasHydrated||(_r.add(l),e(f=>f.clearedVariantKeys.includes(l)?f:as({...f,clearedVariantKeys:[...f.clearedVariantKeys,l]},[n])));return}_r.add(l),e(f=>{if(f.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0)return f;const u=new Map(f.sessionAgentModelVariantSelections),h=new Map(u.get(n)??new Map),m=new Map(h.get(r)??new Map);m.delete(a),m.size===0?h.delete(r):h.set(r,m),h.size===0?u.delete(n):(u.delete(n),u.set(n,h));const g=f.clearedVariantKeys.includes(l)?f.clearedVariantKeys:[...f.clearedVariantKeys,l];return as({...f,sessionAgentModelVariantSelections:u,clearedVariantKeys:g},[n])});return}t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)!==i&&(_r.add(l),e(d=>{if(d.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===i)return d;const f=new Map(d.sessionAgentModelVariantSelections),u=new Map(f.get(n)??new Map),h=new Map(u.get(r)??new Map);return f.delete(n),h.set(a,i),u.set(r,h),f.set(n,u),as({...d,sessionAgentModelVariantSelections:f},[n])}))},getAgentModelVariantForSession:(n,r,s,o)=>{const i=X0(s,o);return t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(i)},forgetSession:n=>{if(!(!n||!Q0(t(),n))){oo.delete(n);for(const r of Array.from(io))gf(r)?.[0]===n&&io.delete(r);for(const r of Array.from(_r))Tn(r)?.[0]===n&&_r.delete(r);e(r=>{if(!Q0(r,n))return r;let s=r.clearedVariantKeys;s.some(i=>Tn(i)?.[0]===n)&&(s=s.filter(i=>Tn(i)?.[0]!==n));let o=r.sessionRecency;return o.includes(n)&&(o=o.filter(i=>i!==n)),{sessionModelSelections:Oc(r.sessionModelSelections,n),sessionAgentSelections:Oc(r.sessionAgentSelections,n),sessionAgentModelSelections:Oc(r.sessionAgentModelSelections,n),sessionAgentModelVariantSelections:Oc(r.sessionAgentModelVariantSelections,n),clearedVariantKeys:s,sessionRecency:o}})}}}),{name:FI,version:BI,storage:gm(),partialize:e=>({sessionModelSelections:Array.from(e.sessionModelSelections.entries()),sessionAgentSelections:Array.from(e.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(e.sessionAgentModelSelections.entries()).map(([t,n])=>[t,Array.from(n.entries())]),sessionAgentModelVariantSelections:Array.from(e.sessionAgentModelVariantSelections.entries()).map(([t,n])=>[t,Array.from(n.entries()).map(([r,s])=>[r,Array.from(s.entries())])]),lastUsedProvider:e.lastUsedProvider,contextStoreMigrationVersion:e.contextStoreMigrationVersion,clearedVariantKeys:e.clearedVariantKeys,sessionRecency:e.sessionRecency}),merge:(e,t)=>{let n=!1,r;e===void 0?r=void 0:Ia(e)?r=e:(n=!0,r=void 0);const s=Es(r?.sessionModelSelections??void 0,$m),o=Es(r?.sessionAgentSelections??void 0,Ns),i=fw(r?.sessionAgentModelSelections??void 0),a=hw(r?.sessionAgentModelVariantSelections??void 0);r!==void 0&&(n=n||s.failed||o.failed||i.failed||a.failed);let l=t.lastUsedProvider;if(r?.lastUsedProvider!==void 0){const w=r.lastUsedProvider;w===null||Ia(w)&&typeof w.providerID=="string"&&typeof w.modelID=="string"?l=w:n=!0}let d=[];if(r?.clearedVariantKeys!==void 0){const w=r.clearedVariantKeys;Array.isArray(w)&&w.every(Ns)?d=[...w]:n=!0}const f=r?.contextStoreMigrationVersion===Y0,u=f?{status:"missing",failed:!1,data:Ss()}:KI(),h=u.failed,m=new Map(s.value),g=new Map(o.value),x=new Map(Array.from(i.value.entries()).map(([w,I])=>[w,new Map(I)])),b=new Map(Array.from(a.value.entries()).map(([w,I])=>[w,new Map(Array.from(I.entries()).map(([E,T])=>[E,new Map(T)]))])),S=new Set([...d,...t.clearedVariantKeys]);if(u.status==="ok"||u.status==="failed"){const w=u.data;for(const[I,E]of w.models)m.has(I)||m.set(I,E);for(const[I,E]of w.agents)g.has(I)||g.set(I,E);for(const[I,E]of w.currentAgentContext)g.has(I)||g.set(I,E);for(const[I,E]of w.agentModels){let T=x.get(I);T||(T=new Map,x.set(I,T));for(const[A,j]of E)T.has(A)||T.set(A,j)}for(const[I,E]of w.variants)for(const[T,A]of E)for(const[j,k]of A){if(S.has(J0(I,T,j)))continue;let _=b.get(I);_||(_=new Map,b.set(I,_));let M=_.get(T);M||(M=new Map,_.set(T,M)),M.has(j)||M.set(j,k)}}for(const w of oo){const I=t.sessionModelSelections.get(w);I&&e2(m,w,I);const E=t.sessionAgentSelections.get(w);E!==void 0&&e2(g,w,E)}for(const w of io){const I=gf(w);if(!I)continue;const[E,T]=I,A=t.sessionAgentModelSelections.get(E)?.get(T);if(!A)continue;let j=x.get(E);j||(j=new Map,x.set(E,j)),j.set(T,A),x.delete(E),x.set(E,j)}for(const w of _r){const I=Tn(w);if(!I)continue;const[E,T,A]=I,j=t.sessionAgentModelVariantSelections.get(E)?.get(T)?.get(A);if(j!==void 0){let k=b.get(E);k||(k=new Map,b.set(E,k));let _=k.get(T);_||(_=new Map,k.set(T,_)),_.set(A,j)}else GI(b,E,T,A)}up&&t.lastUsedProvider!==null&&(l=t.lastUsedProvider);const y=new Set;for(const w of oo)y.add(w);for(const w of io){const I=gf(w);I&&y.add(I[0])}for(const w of _r){const I=Tn(w);I&&y.add(I[0])}const v=as({sessionModelSelections:m,sessionAgentSelections:g,sessionAgentModelSelections:x,sessionAgentModelVariantSelections:b,clearedVariantKeys:Array.from(S),sessionRecency:iu(r?.sessionRecency)},Array.from(y)),C=f||!n&&!h;return $I(),{...t,sessionModelSelections:v.sessionModelSelections,sessionAgentSelections:v.sessionAgentSelections,sessionAgentModelSelections:v.sessionAgentModelSelections,sessionAgentModelVariantSelections:v.sessionAgentModelVariantSelections,lastUsedProvider:l,hasHydrated:!0,clearedVariantKeys:C?[]:v.clearedVariantKeys,sessionRecency:v.sessionRecency,contextStoreMigrationVersion:C?Y0:t.contextStoreMigrationVersion}},migrate:e=>WI(e)}));if(typeof window<"u"){const e=Lt.persist,t=()=>{Lt.getState().hasHydrated||Lt.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const zm=(e,t)=>`${e}::${t}`,Qo=Et(e=>({byKey:new Map,setEntry:t=>e(n=>{const r=new Map(n.byKey);return r.set(zm(t.runtimeKey,t.sessionId),t),{byKey:r}}),clearForSession:t=>e(n=>{const r=new Map(n.byKey);let s=!1;for(const o of r.keys())o.endsWith(`::${t}`)&&(r.delete(o),s=!0);return s?{byKey:r}:n}),clearAll:()=>e({byKey:new Map}),clearForRuntime:t=>e(n=>{const r=`${t}::`,s=new Map(n.byKey);let o=!1;for(const i of s.keys())i.startsWith(r)&&(s.delete(i),o=!0);return o?{byKey:s}:n})}));typeof window<"u"&&Zt(e=>{e.runtimeKey!==e.previousRuntimeKey&&e.previousRuntimeKey&&Qo.getState().clearForRuntime(e.previousRuntimeKey)});const ZI=(e,t,n)=>{const r=Y();Qo.getState().setEntry({sessionId:e,runtimeKey:r,targetEntryId:t.targetEntryId,previousLeafId:t.previousLeafId,newLeafId:t.newLeafId,...t.editorText!==void 0?{editorText:t.editorText}:{},abandoned:n,createdAt:Date.now()})},yf=e=>{Qo.getState().clearForSession(e)},vf=()=>{Qo.getState().clearAll()},Um=e=>{const t=Y();return Qo.getState().byKey.get(zm(t,e))},YI=e=>Qo(t=>{if(e)return t.byKey.get(zm(Y(),e))}),qm=e=>{const t=["~"],n=r=>{const s=de(r);s&&!t.includes(s)&&t.push(s)};n(e);try{n(Gt().getItem("homeDirectory"))}catch{}try{typeof window<"u"&&Yr()&&n(window.__PICHAMBER_HOME__)}catch{}return t},XI=(e,t)=>{const n=de(e);return!!(n&&qm(t).includes(n))},fp=()=>({byId:new Map,byDirectory:new Map,listStatusByDirectory:new Map}),Cs=(e,t,n,r,s)=>{if(e.byId.has(t))return e;const o=Wr(n),i=s??Date.now(),a={id:t,directory:o,parentId:null,title:"",archived:!1,createdAt:i,updatedAt:i,lifecycle:r,hydrated:!1},l=new Map(e.byId);l.set(t,a);const d=e.byDirectory.get(o),f=new Map(e.byDirectory);return d&&d.includes(t)?f.set(o,d):d?f.set(o,[t,...d]):f.set(o,[t]),{...e,byId:l,byDirectory:f}},Wr=e=>de(e)??e,Ea=(e,t)=>e===void 0||t===void 0||e===null||t===null?e===t:e.count===t.count&&e.kind===t.kind&&e.since===t.since,pw=(e,t)=>e.id===t.id&&e.directory===t.directory&&e.parentId===t.parentId&&e.title===t.title&&e.archived===t.archived&&e.archivedAt===t.archivedAt&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt&&e.preview===t.preview&&e.messageCount===t.messageCount&&e.lifecycle===t.lifecycle&&e.retry===t.retry&&e.hydrated===t.hydrated&&Ea(e.pendingInput,t.pendingInput),JI=(e,t,n,r)=>{const s=t.get(n)??[];for(const o of s){if(r.includes(o))continue;const i=e.get(o);i&&i.directory!==n||e.delete(o)}t.set(n,[...r])},QI=(e,t)=>e===t||!!e&&!!t&&e.attempt===t.attempt&&e.next===t.next&&e.message===t.message,eE=(e,t,n,r,s)=>{const o=Wr(t),i=[];let a=null,l=null;for(const m of n){const g=m?.session;if(!g?.id||!g.directory)continue;const x=Wr(g.directory);if(x!==o)continue;const b=typeof g.timeArchived=="number"?g.timeArchived>0:!!g.archived,S=e.byId.get(g.id),y=typeof m.updatedAt=="number"&&Number.isFinite(m.updatedAt)?m.updatedAt:typeof g.updatedAt=="number"&&Number.isFinite(g.updatedAt)?g.updatedAt:r,v=m.live&&s?.acceptLiveObservation?.(g.id,m.live.sequence)?m.live:void 0,C=v?v.lifecycle:S?.lifecycle??"idle",w=v?.lifecycle==="retry"?v.retry??{}:void 0,I=v?QI(S?.retry,w)?S?.retry:w:S?.retry,E=m.inputState&&s?.acceptPendingInputObservation?.(g.id,m.inputState.sequence)?m.inputState.pending:void 0,T=E==null||Kd(E)?E:void 0,A=T!==void 0?T:S?.pendingInput,j={id:g.id,directory:x,parentId:g.parentId??null,title:g.title??"",archived:b,...b&&typeof g.timeArchived=="number"&&Number.isFinite(g.timeArchived)?{archivedAt:g.timeArchived}:{},createdAt:g.createdAt,updatedAt:S?S.updatedAt:y,...typeof m.preview=="string"?{preview:m.preview}:{},...typeof g.messageCount=="number"?{messageCount:g.messageCount}:S?.messageCount!==void 0?{messageCount:S.messageCount}:{},lifecycle:C,...I?{retry:I}:{},...A!==void 0?{pendingInput:A}:{},hydrated:S?.hydrated??!1};if(S&&pw(S,j)){i.push(g.id);continue}a||(a=new Map(e.byId),l=new Map(e.byDirectory)),a.set(g.id,j),i.push(g.id)}const f=e.byDirectory.get(o)??[],u=f.length!==i.length||f.some((m,g)=>m!==i[g]);if(!a&&!u){if(e.listStatusByDirectory.get(o)!=="ready"){const m=new Map(e.listStatusByDirectory);return m.set(o,"ready"),{...e,listStatusByDirectory:m}}return e}a||(a=new Map(e.byId)),l||(l=new Map(e.byDirectory)),JI(a,l,o,i);let h=null;return e.listStatusByDirectory.get(o)!=="ready"&&(h=new Map(e.listStatusByDirectory),h.set(o,"ready")),{byId:a,byDirectory:l,listStatusByDirectory:h??e.listStatusByDirectory}},tE=(e,t)=>{const n=Wr(t),r=e.listStatusByDirectory.get(n);if(r==="loading"||r==="ready")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"loading"),{...e,listStatusByDirectory:s}},nE=(e,t)=>{const n=Wr(t);if(e.listStatusByDirectory.get(n)==="failed")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"failed"),{...e,listStatusByDirectory:s}},Xs=(e,t,n,r)=>{const s=e.byId.get(t);if(!s)return e;const o=n==="retry"?r:void 0;if(s.lifecycle===n&&s.retry===o)return e;const i=new Map(e.byId);return i.set(t,{...s,lifecycle:n,retry:o}),{...e,byId:i}},xf=(e,t,n)=>{const r=e.byId.get(t);if(!r||r.hydrated===n)return e;const s=new Map(e.byId);return s.set(t,{...r,hydrated:n}),{...e,byId:s}},Fc=(e,t,n,r)=>{const s=e.byId.get(t);if(!s||s.title===n&&s.updatedAt===r)return e;const o=new Map(e.byId);return o.set(t,{...s,title:n,updatedAt:r}),{...e,byId:o}},n2=(e,t,n,r)=>{const s=e.byId.get(t);if(!s){if(!r)return e;const i=Cs(e,t,r.directory,r.lifecycle,n),a=i.byId.get(t);if(!a||a.updatedAt===n)return i;const l=new Map(i.byId);return l.set(t,{...a,updatedAt:n}),{...i,byId:l}}if(s.updatedAt>=n&&s.lifecycle===(r?.lifecycle??s.lifecycle))return e;const o=new Map(e.byId);return o.set(t,{...s,updatedAt:Math.max(s.updatedAt,n),...r?.lifecycle?{lifecycle:r.lifecycle}:{}}),{...e,byId:o}},r2=(e,t,n,r,s)=>{const o=e.byId.get(t);if(!o)return e;const i=n?s??(o.archived?o.archivedAt:void 0):void 0;if(o.archived===n&&o.updatedAt===r&&o.archivedAt===i)return e;const a={...o,archived:n,updatedAt:r};i===void 0?delete a.archivedAt:a.archivedAt=i;const l=new Map(e.byId);return l.set(t,a),{...e,byId:l}},aa=(e,t,n,r,s,o)=>{if(r!==null&&!Kd(r))return e;const i=e.byId.get(t);if(i){if(Ea(i.pendingInput,r))return e;const f=new Map(e.byId);return f.set(t,{...i,pendingInput:r}),{...e,byId:f}}if(r===null)return e;const a=Cs(e,t,n,"idle"),l=a.byId.get(t);if(!l||Ea(l.pendingInput,r))return a;const d=new Map(a.byId);return d.set(t,{...l,pendingInput:r}),{...a,byId:d}},rE=(e,t,n)=>{const r=n?.streamEpoch??null;if(r!==null&&(typeof t.streamEpoch!="string"||t.streamEpoch!==r))return e;const s=t.sequence;if(!Number.isSafeInteger(s)||s<0)return e;const o=n?.acceptPendingInputObservation??(()=>!0),i=new Set;let a=e;for(const l of t.sessions)!l||typeof l.sessionId!="string"||l.sessionId.length===0||typeof l.directory!="string"||l.directory.length===0||i.has(l.sessionId)||(i.add(l.sessionId),Kd(l.pending)&&o(l.sessionId,s)&&(a=aa(a,l.sessionId,l.directory,l.pending)));for(const[l,d]of a.byId)i.has(l)||d.pendingInput!=null&&o(l,s)&&(a=aa(a,l,d.directory,null));return a},sE=e=>{let t=null;for(const[n,r]of e.byId)r.pendingInput!==void 0&&(t||(t=new Map(e.byId)),t.set(n,{...r,pendingInput:void 0}));return t?{...e,byId:t}:e},oE=[],Wm=e=>{const t=[];for(const n of e.byId.values())n.pendingInput!=null&&t.push({sessionId:n.id,directory:n.directory,pending:n.pendingInput});return t.length===0?oE:(t.sort((n,r)=>n.pending.since-r.pending.since||(n.sessionId<r.sessionId?-1:n.sessionId>r.sessionId?1:0)),t)},iE=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.sessionId!==s.sessionId||r.directory!==s.directory||!Ea(r.pending,s.pending))return!1}return!0},s2=(e,t)=>{const n=e.byId.get(t.id);if(n&&pw(n,t))return e;const r=new Map(e.byId);r.set(t.id,t);const s=e.byDirectory.get(t.directory);if(s){const i=s.filter(l=>l!==t.id),a=new Map(e.byDirectory);return a.set(t.directory,[t.id,...i]),{...e,byId:r,byDirectory:a}}const o=new Map(e.byDirectory);return o.set(t.directory,[t.id]),{...e,byId:r,byDirectory:o}},aE=(e,t)=>{const n=e.byId.get(t);if(!n)return e;const r=new Map(e.byId);r.delete(t);const s=e.byDirectory.get(n.directory);let o=null;if(s){const i=s.filter(a=>a!==t);o=new Map(e.byDirectory),i.length===0?o.delete(n.directory):o.set(n.directory,i)}return{byId:r,byDirectory:o??e.byDirectory,listStatusByDirectory:e.listStatusByDirectory}},o2=new WeakMap,Ls=e=>{const t=o2.get(e);if(t)return t;const n={id:e.id,directory:e.directory,parentID:e.parentId,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.updatedAt}:{}}};return o2.set(e,n),n},i2=[],cE=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},pd=(e,t)=>{const n=t?.archived??!1,r=t?.directory;let s;if(typeof r=="string"&&r.length>0){const i=Wr(r),a=e.byDirectory.get(i)??[],l=qm();if(!l.includes(i))s=a;else{const d=[],f=new Set(a);for(const u of l){if(u===i)continue;const h=e.byDirectory.get(u);if(h)for(const m of h)f.has(m)||(f.add(m),d.push(m))}s=d.length>0?[...a,...d]:a}}else{if(r===null||r==="")return i2;s=[...e.byId.keys()]}const o=[];for(const i of s){const a=e.byId.get(i);a&&!!a.archived===n&&o.push(Ls(a))}return o.length===0?i2:o},lE=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n);return t},$X=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n.id);return t.sort(),t.join("|")},bf=(e,t,n,r,s,o,i)=>{const a=Wr(n),l=[],d=[],f=new Set;for(const O of r){const N=O?.session;!N?.id||!N.directory||Wr(N.directory)===a&&(f.has(N.id)||(f.add(N.id),l.push(N.id),d.push(O)))}const u=new Set(l),h=e.byDirectory.get(a)??[],m=t.byDirectory.get(a)??[],g=new Set(h),x=new Set;for(const O of g)t.byId.has(O)||x.add(O);const b=new Map,S=new Map,y=new Map,v=new Map,C=new Set,w=new Set;for(const O of h)w.add(O);for(const O of m)w.add(O);for(const O of l)w.add(O);for(const O of w){const N=t.byId.get(O);if(!N)continue;const D=e.byId.get(O);if(D===N)continue;if(N.directory!==a){D&&(D.directory===a||g.has(O)||u.has(O))&&C.add(O);continue}if(!D){if(u.has(O))continue;b.set(O,N);continue}const W=N.title!==D.title,z=N.archived!==D.archived;if(u.has(O)){(W||z)&&v.set(O,{rec:N,titleChanged:W,archivedChanged:z});continue}W||z?S.set(O,N):y.set(O,N)}const I=d.filter(O=>{const N=O.session.id;return!(x.has(N)||o?.has(N)||C.has(N))}),E=eE(t,a,I,s,i);let T=null;for(const[O,N]of v){const D=E.byId.get(O);if(!D){S.set(O,N.rec);continue}const W=N.titleChanged?N.rec.title:D.title,z=N.archivedChanged?N.rec.archived:D.archived;if(D.title!==W||D.archived!==z){T||(T=new Map(E.byId));const X=N.archivedChanged?N.rec.archivedAt:D.archivedAt,F={...D,title:W,archived:z};z&&X!==void 0?F.archivedAt=X:delete F.archivedAt,T.set(O,F)}}if(b.size===0&&S.size===0&&y.size===0&&!T)return E;const A=T??E.byId,j=E.byDirectory.get(a)??[],k=new Set(j),_=new Map([...b,...S,...y]),M=[];for(const O of m)_.has(O)&&!k.has(O)&&M.push(O);let L=null;if(M.length>0){L=new Map(E.byDirectory),L.set(a,[...M,...j]),T||(T=new Map(A));for(const O of M){const N=_.get(O);N&&T.set(O,N)}}return!T&&!L?E:{byId:T??E.byId,byDirectory:L??E.byDirectory,listStatusByDirectory:E.listStatusByDirectory}},dE=2,uE=(e,t)=>Oh([...e],dE,async n=>t(n)),a2="*",yt="catalog",Bc="dialogs",At="chrome",wf=16,c2=2,fE=5,hE=300,pE=new Set(["DAEMON_UNAVAILABLE","DAEMON_TIMEOUT","DAEMON_START_TIMEOUT","DAEMON_SPAWN_FAILED","DAEMON_REQUEST_FAILED"]),Vc=e=>e==="busy"||e==="retry"?e:e==="error"?"error":"idle",mw=e=>{if(e.name==="session.lifecycle"){const t=e.payload&&typeof e.payload=="object"?e.payload.state:void 0;return t==="busy"||t==="retry"||t==="error"?t:t==="idle"?"idle":void 0}if(e.name==="assistant.message.start")return"busy";if(e.name==="session.error")return"error"},In=e=>e instanceof at?e:new at("DAEMON_REQUEST_FAILED",e instanceof Error?e.message:void 0),gi=e=>e instanceof at&&e.code==="INVALID_SESSION",Sf=e=>e instanceof at&&e.code==="SESSION_IN_USE",mE=e=>e instanceof at&&e.code==="SESSION_RUNTIME_CONFLICT",l2=async()=>{await new Promise(e=>setTimeout(e,hE))},$c=(e=fp())=>({directory:null,sessions:[],selectedSessionId:null,reducer:Jl(),connection:"loading",error:null,showArchived:!1,hydratedSessionIds:new Set,sessionLoadErrorById:new Map,focusPending:!1,sessionsListStatus:"idle",catalog:e,syncReadiness:"ready",syncRecovery:{directories:[],residents:[]}}),gE=(e,t,n)=>{const r=n?.now??Date.now(),s=t.byId.get(e.id),o=de(e.directory)??e.directory,i=typeof e.timeArchived=="number"?e.timeArchived>0:!!e.archived;return{id:e.id,directory:o,parentId:e.parentId??null,title:e.title??"",archived:i,createdAt:e.createdAt,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:r,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:s?.messageCount!==void 0?{messageCount:s.messageCount}:{},lifecycle:s?.lifecycle??"idle",hydrated:s?.hydrated??!1,...s?.pendingInput!==void 0?{pendingInput:s.pendingInput}:{}}},d2=(e,t,n,r)=>{if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)return e;const s=e.byId.get(t);if(s){if(s.messageCount===r)return e;const l=new Map(e.byId);return l.set(t,{...s,messageCount:r}),{...e,byId:l}}const o=Cs(e,t,n,"idle"),i=o.byId.get(t);if(!i||i.messageCount===r)return o;const a=new Map(o.byId);return a.set(t,{...i,messageCount:r}),{...o,byId:a}},yE=(e,t,n={})=>{if(!t||t.sessionId!==e.sessionId)return e;const r=e.lifecycle!=="busy"&&e.lifecycle!=="retry"&&e.streamingMessages.size===0&&e.lastSequence>=t.lastSequence&&n.localSendPending!==!0,o=(t.lifecycle==="busy"||t.lifecycle==="retry")&&!r||t.lastSequence>e.lastSequence,i=t.lastSequence>e.lastSequence,a=e.hasMoreBefore===!0&&t.messages.size>0,l={extensionNotices:t.extensionNotices,extensionErrors:t.extensionErrors,extensionCatalogRevision:t.extensionCatalogRevision,sessionTreeRevision:t.sessionTreeRevision,extensionEditor:t.extensionEditor,extensionEditorOps:t.extensionEditorOps,...t.awaitingPromptEcho!==void 0?{awaitingPromptEcho:t.awaitingPromptEcho}:{}};if(t.messages.size===0&&!o)return{...e,...l};const d={...e,...a&&t.hasMoreBefore!==void 0?{hasMoreBefore:t.hasMoreBefore,beforeCursor:t.beforeCursor}:{},lifecycle:o?t.lifecycle:e.lifecycle,lastSequence:Math.max(e.lastSequence,t.lastSequence),messages:new Map(e.messages),partOrder:new Map(e.partOrder),parts:Xl(e.parts),toolsByCallId:new Map(e.toolsByCallId),streamingMessages:new Set(o?t.streamingMessages:e.streamingMessages),queue:t.queue.steering>0||t.queue.followUp>0?t.queue:e.queue,...t.model&&(o||!e.model)?{model:t.model}:{},...t.thinking&&(o||!e.thinking)?{thinking:t.thinking}:{},...i?{extensionStatuses:t.extensionStatuses,extensionWidgets:t.extensionWidgets,extensionDialogs:t.extensionDialogs,extensionPanels:t.extensionPanels,extensionApps:t.extensionApps,extensionTitle:t.extensionTitle,...t.extensionWorking?{extensionWorking:t.extensionWorking}:{},...t.extensionDraftTracked?{extensionDraftTracked:!0}:{},extensionSurfaces:t.extensionSurfaces,bashExecutions:t.bashExecutions}:{},...l},f=o?t.runningCommand:e.runningCommand;if(f?d.runningCommand=f:delete d.runningCommand,o||a){for(const[u,h]of t.messages)(o||!d.messages.has(u))&&Z8(d,u,h);for(const[u,h]of t.partOrder)if(!(!o&&d.partOrder.has(u))){d.partOrder.set(u,h);for(const m of h){const g=t.parts.get(m);g&&d.parts.set(m,g)}}for(const[u,h]of t.toolsByCallId)(o||!d.toolsByCallId.has(u))&&d.toolsByCallId.set(u,h)}return d};let u2=null;const vE=new Set(["session.snapshot","session.interrupted","session.deleted"]),f2=e=>mw(e)!==void 0||vE.has(e.name),yi=e=>e.inputState?{pending:e.inputState.pending,sequence:e.lastSequence}:void 0,qe=()=>(u2??=new Km,u2),zX=e=>qe().subscribeOpenRequests(e),xE=e=>qe().subscribePendingInputTransitions(e),bE=e=>e instanceof at&&typeof e.status=="number"&&e.status>=400&&e.status<500&&e.status!==408;class Km{state;listenersByTopic=new Map;stream=null;streamGeneration=0;streamReadyRevision=0;runtimeGeneration=0;archiveRevision=0;archiveRevisionById=new Map;focusGeneration=0;recovering=!1;pendingFocus=null;pendingPreferredSessionId=null;selectionRevision=0;userSelection=null;newerSelection(t,n){const r=this.userSelection;return r&&r.revision>t&&(!r.directory||de(r.directory)===de(n))?r.id:null}hydratedSessionIds=new Set;activityPhaseById=new Map;pendingPromptById=new Set;promptGenerationById=new Map;acceptedPromptGenerationById=new Map;acceptedPromptReconcileInFlight=new Map;lastAccessById=new Map;lastAccessClock=0;lastSelectedByDirectory=new Map;directoryRefreshGenerationByDirectory=new Map;pendingCatalogPassByKey=new Map;deletedSessionIds=new Set;static MAX_DELETED_SESSION_TOMBSTONES=4096;isDeleted=t=>this.deletedSessionIds.has(t);deletedSessionCountForTests=()=>this.deletedSessionIds.size;providerRefreshRevisionByDirectory=new Map;providerRefreshTaskByDirectory=new Map;evictionScheduled=!1;restoringTranscriptById=new Set;hydrateInflightById=new Map;transcriptPrefetch=null;historyInflightById=new Map;navigationGenerationById=new Map;navigationCounter=0;streamEpoch=null;lifecycleSequenceById=new Map;pendingInputSequenceById=new Map;pendingInputUnsupported=!1;pendingInputFetchInFlight=null;pendingInputRefetchRequested=!1;pendingMetadataBackfillAttempted=new Set;retiredStreamEpochs=new Set;recoveryDirectories=new Set;recoveryResidents=new Set;recoveryRunning=!1;recoveryRevision=0;recoveryAttempt=0;recoveryTimer=null;adoptStreamEpoch(t){return typeof t!="string"||t.length===0||this.streamEpoch===t?!1:(this.streamEpoch!==null&&this.retiredStreamEpochs.add(this.streamEpoch),this.streamEpoch=t,!0)}isResponseEpochCurrent(t){const n=typeof t?.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:void 0;return n?this.retiredStreamEpochs.has(n)?!1:this.streamEpoch===null?(this.streamEpoch=n,!0):n===this.streamEpoch:this.streamEpoch===null}createListLiveGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Set,o=new Set;return{options:{acceptLiveObservation:(l,d)=>{if(!Number.isSafeInteger(d)||d<0)return!1;const f=Math.max(this.lifecycleSequenceById.get(l)??-1,this.hydratedSessionIds.has(l)?this.state.reducer.lastSequence.get(l)??-1:-1);if(d<f)return!1;if(this.pendingPromptById.has(l)){const u=this.promptGenerationById.get(l);return u!==void 0&&this.acceptedPromptGenerationById.get(l)===u&&o.add(l),!1}return s.add(l),!0}},commit:l=>{if(r===this.streamEpoch){for(const d of l)d.live?.lifecycle==="idle"&&o.has(d.session.id)&&this.reconcileAcceptedPromptFromList(d.session.id);if(s.size!==0)for(const d of l){const f=d.live;if(!f||!s.has(d.session.id))continue;const u=d.session.id;(this.lifecycleSequenceById.get(u)??-1)<f.sequence&&this.lifecycleSequenceById.set(u,f.sequence),!(f.lifecycle==="idle"||typeof f.runStartedAt!="number")&&this.state.catalog.byId.get(u)?.lifecycle===f.lifecycle&&Mn(u,f.runStartedAt,f.serverNow)}}}}}createListPendingInputGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Map;return{options:{acceptPendingInputObservation:(a,l)=>{if(!Number.isSafeInteger(l)||l<0||l<(this.pendingInputSequenceById.get(a)??-1))return!1;const d=s.get(a);return(d===void 0||l>d)&&s.set(a,l),!0}},commit:a=>{if(r!==this.streamEpoch||s.size===0)return;const l=new Map;for(const d of a)d.inputState&&s.has(d.session.id)&&l.set(d.session.id,d.inputState.sequence);for(const[d,f]of s){const u=l.get(d)??f;(this.pendingInputSequenceById.get(d)??-1)<u&&this.pendingInputSequenceById.set(d,u)}}}}createDirectoryListGates(t,{streamAttaching:n=!1}={}){const r=this.createListLiveGate(t,{streamAttaching:n}),s=this.createListPendingInputGate(t,{streamAttaching:n});return{options:r.options||s.options?{...r.options,...s.options}:void 0,commit:a=>{r.commit(a),s.commit(a)}}}applyVerifiedEpochChange(t){const n=this.streamEpoch!==null&&this.streamEpoch!==t;if(!this.adoptStreamEpoch(t)||!n)return null;const r=this.resetForEpochChange();return this.state={...this.state,reducer:Jl(),hydratedSessionIds:new Set(this.hydratedSessionIds)},this.queueSyncRecovery({directories:"all-known",residents:r}),r}handleVerifiedEpochChange(t){const n=this.applyVerifiedEpochChange(t);n&&this.emit([At,yt,...[...n].map(r=>`session:${r}`)])}resetForEpochChange(){const t=new Set(this.hydratedSessionIds),n=[];for(const s of this.state.catalog.byId.values())s.pendingInput!=null&&n.push({type:"cleared",sessionId:s.id,directory:s.directory,pending:null});for(const[s,o]of this.openedPendingInputById)this.state.catalog.byId.has(s)||n.push({type:"cleared",sessionId:s,directory:o,pending:null});this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.hydratedSessionIds.clear(),this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch();for(const[s,o]of this.navigationGenerationById)this.navigationGenerationById.set(s,o+1);this.settleCarriedOverActivity();const r=sE(this.state.catalog);return r!==this.state.catalog&&(this.state={...this.state,catalog:r}),this.emitPendingInputTransitions(n),t}settleCarriedOverActivity(){let t=this.state.catalog;for(const n of t.byId.values())n.lifecycle!=="busy"&&n.lifecycle!=="retry"||this.pendingPromptById.has(n.id)||(t=Xs(t,n.id,"idle"),D0(n.id));t!==this.state.catalog&&(this.state={...this.state,catalog:t})}queueSyncRecovery(t){this.refreshPendingInputList();let n=!1,r=!1;if(t.directories==="all-known")for(const s of this.state.catalog.listStatusByDirectory.keys())s&&(n=!0,this.recoveryDirectories.has(s)||(this.recoveryDirectories.add(s),r=!0));else if(t.directories)for(const s of t.directories){const o=de(s);o&&(n=!0,this.recoveryDirectories.has(o)||(this.recoveryDirectories.add(o),r=!0))}if(t.residents)for(const s of t.residents)s&&(n=!0,this.recoveryResidents.has(s)||(this.recoveryResidents.add(s),r=!0));n&&(this.recoveryRevision+=1,this.recoveryAttempt=0,this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,r&&this.publishSyncRecoveryState(),this.runSyncRecovery())}publishSyncRecoveryState(){const t=[...this.recoveryDirectories],n=[...this.recoveryResidents],r=t.length===0&&n.length===0?"ready":"recovering",s=this.state.syncRecovery;r===this.state.syncReadiness&&s.directories.length===t.length&&s.residents.length===n.length&&t.every((i,a)=>s.directories[a]===i)&&n.every((i,a)=>s.residents[a]===i)||(this.state={...this.state,syncReadiness:r,syncRecovery:{directories:t,residents:n}},this.emitChrome())}clearSyncRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryDirectories.clear(),this.recoveryResidents.clear(),this.recoveryRunning=!1,this.recoveryRevision+=1,this.recoveryAttempt=0,this.publishSyncRecoveryState()}async runSyncRecovery(){if(this.recoveryRunning)return;if(this.recoveryDirectories.size===0&&this.recoveryResidents.size===0){this.publishSyncRecoveryState();return}this.recoveryRunning=!0;const t=this.runtimeGeneration,n=Y(),r=this.streamEpoch,s=this.recoveryRevision,o=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamEpoch&&s===this.recoveryRevision;try{const i=this.state.selectedSessionId,a=[...this.recoveryResidents].sort((f,u)=>f===i?-1:u===i?1:0);if(await Oh(a,c2,async f=>{if(!o()||!this.recoveryResidents.has(f))return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}const u=this.resolveSessionDirectory(f)??this.state.directory??void 0;if(u){try{const h=await Ie.getSession(f,{directory:u,runtimeKey:n});if(!o()||h.session.id!==f)return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}if(!this.isResponseEpochCurrent(h)||!o())return;const m=this.state.reducer.bySession.get(f);(!m||m.lastSequence<=h.lastSequence)&&((h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)),this.recoveryResidents.delete(f)}catch(h){o()&&gi(h)&&(this.commitDeletion(f,u),this.recoveryResidents.delete(f))}this.publishSyncRecoveryState()}}),!o())return;const l=this.state.directory?de(this.state.directory):null,d=[...this.recoveryDirectories].sort((f,u)=>f===l?-1:u===l?1:0);await Oh(d,c2,async f=>{if(o()&&this.recoveryDirectories.has(f)){try{(await this.refreshDirectoryCatalog(f)).ok&&o()&&this.recoveryDirectories.delete(f)}catch{}this.publishSyncRecoveryState()}})}finally{this.recoveryRunning=!1,t===this.runtimeGeneration&&n===Y()&&(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(s!==this.recoveryRevision||r!==this.streamEpoch)&&this.runSyncRecovery()}if(!(t!==this.runtimeGeneration||n!==Y())&&(this.publishSyncRecoveryState(),this.recoveryDirectories.size>0||this.recoveryResidents.size>0)){if(s!==this.recoveryRevision||r!==this.streamEpoch){this.runSyncRecovery();return}if(this.recoveryAttempt+=1,this.recoveryAttempt<=fE){const i=Math.min(16e3,1e3*2**(this.recoveryAttempt-1));this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.runSyncRecovery()},i)}}}commitMissedDeletion=(t,n)=>this.commitDeletion(t,n);commitDeletion(t,n){if(!t)return!1;const r=this.deletedSessionIds.has(t);this.deletedSessionIds.add(t);let s;this.deletedSessionIds.size>Km.MAX_DELETED_SESSION_TOMBSTONES&&(s=this.deletedSessionIds.values().next().value,s&&this.deletedSessionIds.delete(s));const o=n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(C=>C.session.id===t)?.session.directory??this.state.reducer.bySession.get(t)?.directory;if(o&&o!=="global")try{LI({runtimeKey:Y(),directory:o,sessionId:t})}catch{}try{Lt.getState().forgetSession(t)}catch{}D0(t),DM(t),yf(t),this.navigationGenerationById.delete(t),this.pendingInputSequenceById.delete(t),this.historyInflightById.delete(t),this.hydrateInflightById.delete(t),this.restoringTranscriptById.delete(t);const i=this.state.reducer.bySession.has(t)||this.hydratedSessionIds.has(t)||this.state.catalog.byId.has(t)||this.state.sessions.some(C=>C.session.id===t),a=this.state.catalog.byId.get(t)?.pendingInput??null,l=this.state.catalog.byId.get(t)?.directory??n??"",d=this.state.sessions.filter(C=>C.session.id!==t),f=this.state.selectedSessionId===t?d.find(C=>!C.session.archived)?.session.id??null:this.state.selectedSessionId,u=new Map(this.state.reducer.bySession);u.delete(t);const h=new Map(this.state.reducer.lastSequence);s&&h.delete(s);const m=this.state.reducer.lastSequence.get(t);m!==void 0?h.set(t,m):h.delete(t),this.hydratedSessionIds.delete(t),this.activityPhaseById.delete(t),this.pendingPromptById.delete(t),this.promptGenerationById.delete(t),this.acceptedPromptGenerationById.delete(t),this.lastAccessById.delete(t);const g=aE(this.state.catalog,t),x=g!==this.state.catalog,b=f!==this.state.selectedSessionId;let S=this.state.sessionLoadErrorById;if(S.has(t)){const C=new Map(S);C.delete(t),S=C}const y=S!==this.state.sessionLoadErrorById;if(!i&&r&&!x&&!b&&!y)return!1;this.state={...this.state,sessions:d,selectedSessionId:f,hydratedSessionIds:new Set(this.hydratedSessionIds),reducer:{bySession:u,lastSequence:h},catalog:g,sessionLoadErrorById:S};const v=[`session:${t}`,At];return x&&v.push(yt),this.emit(v),a!=null&&this.emitPendingInputTransitions([{type:"cleared",sessionId:t,directory:l,pending:null}]),!0}handleInvalidSession(t,n,r,s=[]){if(!t||r!==this.runtimeGeneration)return;const o=this.state.selectedSessionId===t;if(this.commitDeletion(t,n),s.length>0&&this.commitEvents(s),r!==this.runtimeGeneration||!o)return;const i=this.state.selectedSessionId,a=i&&!this.hydratedSessionIds.has(i);!!a!==this.state.focusPending&&(this.state={...this.state,focusPending:!!a},this.emitChrome()),i&&!this.hydratedSessionIds.has(i)&&this.hydrate(i,this.runtimeGeneration)}filterDeletedListItems(t){return this.deletedSessionIds.size===0?t:t.filter(n=>!this.deletedSessionIds.has(n.session.id))}cadence=new nk(t=>this.commitEvents(t));remoteSendRefreshDelayMs=1500;remoteSendRefreshTimers=new Map;sendUnarchiveTokenById=new Map;sendUnarchiveCounter=0;catalogCache;unsubscribeRuntime;constructor(t=bk()){this.catalogCache=t,this.state=$c(this.readCachedCatalog(Y())),this.unsubscribeRuntime=Zt(n=>{if(n.runtimeKey===n.previousRuntimeKey){this.reconnectAfterTransportSwitch();return}this.resetForRuntime()})}getRuntimeGeneration=()=>this.runtimeGeneration;getFocusGeneration=()=>this.focusGeneration;hasClusterAttached=()=>this.stream!==null||this.state.connection==="ready";getState=()=>this.state;subscribe=(t,n=a2)=>{let r=this.listenersByTopic.get(n);return r||(r=new Set,this.listenersByTopic.set(n,r)),r.add(t),()=>{const s=this.listenersByTopic.get(n);s&&s.delete(t)}};pendingInputTransitionListeners=new Set;extensionSurfaceDismissListeners=new Set;subscribeExtensionSurfaceDismissals=t=>(this.extensionSurfaceDismissListeners.add(t),()=>{this.extensionSurfaceDismissListeners.delete(t)});openedPendingInputById=new Map;subscribePendingInputTransitions=t=>(this.pendingInputTransitionListeners.add(t),()=>{this.pendingInputTransitionListeners.delete(t)});openRequestListeners=new Set;subscribeOpenRequests=t=>(this.openRequestListeners.add(t),()=>{this.openRequestListeners.delete(t)});emitOpenRequest(t){for(const n of[...this.openRequestListeners])try{n(t)}catch(r){console.error("[pi-session-store] open-request listener failed",r)}}emitPendingInputTransitions(t){for(const n of t)n.type==="opened"?this.openedPendingInputById.set(n.sessionId,n.directory):this.openedPendingInputById.delete(n.sessionId);if(!(t.length===0||this.pendingInputTransitionListeners.size===0))for(const n of[...this.pendingInputTransitionListeners])for(const r of t)try{n(r)}catch(s){console.error("[pi-session-store] pending-input listener failed",s)}}resetLiveRuntimeState(){this.providerRefreshRevisionByDirectory.clear(),this.deletedSessionIds.clear(),this.runtimeGeneration+=1,this.focusGeneration+=1,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.userSelection=null,this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear();for(const t of this.remoteSendRefreshTimers.values())clearTimeout(t);this.remoteSendRefreshTimers.clear(),this.sendUnarchiveTokenById.clear(),this.streamEpoch=null,this.retiredStreamEpochs.clear(),this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.openedPendingInputById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.clearSyncRecovery(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1}raiseOrderingBaselinesForDirectory(t){const n=de(t);if(!n)return;const r=this.state.catalog.byDirectory.get(n);if(!r||r.length===0)return;const s=[];for(const o of r){const i=this.state.catalog.byId.get(o);!i||i.archived||s.push(Ls(i))}s.length>0&&HM(s)}recordClusterConnectionChange(t,n){this.state.connection!==t&&Rr("pi-connection",{code:t,detail:(t==="error"||t==="unavailable")&&n?n.code:void 0})}dispose=()=>{this.catalogCache.flush(),this.resetLiveRuntimeState(),this.unsubscribeRuntime(),vf(),this.navigationGenerationById.clear(),this.navigationCounter=0;const t=$c();this.recordClusterConnectionChange(t.connection),this.state=t,this.emitBroadcast(),this.listenersByTopic.clear()};setShowArchived=t=>{t!==this.state.showArchived&&(this.state={...this.state,showArchived:t},this.emitChrome())};clearError=()=>{this.state.error&&(this.state={...this.state,error:null},this.emitChrome())};reportError=t=>{const n=In(t);this.recordClusterConnectionChange("error",n),this.state={...this.state,error:n,connection:"error"},this.emitChrome(),this.ensureConnectionRecovery(n)};ensureConnectionRecovery(t){if(this.stream||!pE.has(t.code))return;const n=this.runtimeGeneration,r=Y(),s=this.streamGeneration+1;this.streamGeneration=s;const o=this.streamCursor();let i=null;i=Gl({onEvent:()=>{},onAuthRequired:()=>this.handleStreamAuthRequired(),onReconnect:()=>{if(n!==this.runtimeGeneration||r!==Y()||s!==this.streamGeneration||this.stream!==i)return;i?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1;const{directory:a,selectedSessionId:l}=this.state;this.start({...a?{directory:a}:{},...l?{sessionId:l}:{}})}},{...o!==void 0?{fromSequence:o}:{},runtimeKey:r}),this.stream=i}handleStreamAuthRequired(){this.reportError(new at("DAEMON_AUTH_FAILED","The Pi runtime rejected the client authorization.")),kS()}failSessionLoad(t,n){const r=new Map(this.state.sessionLoadErrorById);r.set(t,n);const s=this.state.selectedSessionId===t;this.state={...this.state,sessionLoadErrorById:r,focusPending:s?!1:this.state.focusPending},this.emitChrome()}clearSessionLoadError(t){if(!this.state.sessionLoadErrorById.has(t))return;const n=new Map(this.state.sessionLoadErrorById);n.delete(t),this.state={...this.state,sessionLoadErrorById:n},this.emitChrome()}clear=()=>{this.resetLiveRuntimeState(),this.recordClusterConnectionChange("ready"),this.state={...$c(),connection:"ready"},vf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()};acceptPendingInputSequence(t,n){return!Number.isSafeInteger(n)||n<0||n<(this.pendingInputSequenceById.get(t)??-1)?!1:(this.pendingInputSequenceById.set(t,n),!0)}applyPendingInputList(t){if(!this.isResponseEpochCurrent(t))return;const n=rE(this.state.catalog,t,{acceptPendingInputObservation:(r,s)=>this.acceptPendingInputSequence(r,s),streamEpoch:this.streamEpoch});n!==this.state.catalog&&(this.state={...this.state,catalog:n},this.emit([yt])),this.requestNeedingSessionMetadataBackfill(t.sessions.map(r=>r.sessionId))}requestNeedingSessionMetadataBackfill(t){for(const n of t){if(!n||this.pendingMetadataBackfillAttempted.has(n))continue;const r=this.state.catalog.byId.get(n);!r||r.pendingInput==null||r.title.trim()||typeof r.messageCount!="number"&&(this.hydratedSessionIds.has(n)||this.hydrateInflightById.has(n)||this.isDeleted(n)||(this.pendingMetadataBackfillAttempted.add(n),this.ensureHydrated(n).then(()=>{this.hydratedSessionIds.has(n)||this.pendingMetadataBackfillAttempted.delete(n)},()=>{this.pendingMetadataBackfillAttempted.delete(n)})))}}refreshPendingInputList(){if(this.pendingInputUnsupported)return;if(this.pendingInputFetchInFlight){this.pendingInputRefetchRequested=!0;return}if(this.streamEpoch===null)return;const t=this.runtimeGeneration,n=Y(),r=Ie.listPendingInput({runtimeKey:n}).then(s=>{t!==this.runtimeGeneration||n!==Y()||this.applyPendingInputList(s)},s=>{t!==this.runtimeGeneration||n!==Y()||s instanceof at&&s.status===404&&(this.pendingInputUnsupported=!0)}).finally(()=>{this.pendingInputFetchInFlight===r&&(this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested&&(this.pendingInputRefetchRequested=!1,this.refreshPendingInputList()))});this.pendingInputFetchInFlight=r}adoptDetailPendingInput(t,n,r,s,o){return!s||!this.acceptPendingInputSequence(n,o)?t:aa(t,n,r,s.pending)}async refreshDirectoryCatalog(t){const n=de(t);if(!n)return{ok:!1,error:In(new at("INVALID_ARGUMENT","directory is required"))};const r=Y(),s=(this.directoryRefreshGenerationByDirectory.get(n)??0)+1;this.directoryRefreshGenerationByDirectory.set(n,s);const o=this.runtimeGeneration,i=this.state.catalog,a=tE(this.state.catalog,n);a!==this.state.catalog&&(this.state={...this.state,catalog:a},this.emit([yt]));try{const l=await Ie.listSessions({directory:n,runtimeKey:r});if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};if(!this.isResponseEpochCurrent(l))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const d=this.filterDeletedListItems(l.sessions),f=this.createDirectoryListGates(l),u=bf(i,this.state.catalog,n,d,Date.now(),this.deletedSessionIds,f.options);return u!==this.state.catalog?(this.state={...this.state,catalog:u},f.commit(d),this.emit([yt]),this.raiseOrderingBaselinesForDirectory(n)):f.commit(d),{ok:!0}}catch(l){if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};const d=In(l),f=nE(this.state.catalog,n),u=de(this.state.directory)===n,h=[];return f!==this.state.catalog&&(this.state={...this.state,catalog:f},h.push(yt)),u&&(this.state={...this.state,error:d},h.push(At)),h.length>0&&this.emit(h),{ok:!1,error:d}}}async refreshAllDirectoryCatalogs(t){const n=[...new Set(t)].map(d=>de(d)).filter(d=>!!d);if(n.length===0)return;const r=this.runtimeGeneration,s=[],o=[],i=new Map,a=new Map;for(const d of n){const f=`${r}\0${d}`,u=this.pendingCatalogPassByKey.get(f);if(u){s.push(u);continue}o.push(d);const h=new Promise(m=>i.set(d,m));a.set(d,h),this.pendingCatalogPassByKey.set(f,h)}const l=uE(o,async d=>{const f=`${r}\0${d}`;try{return await this.refreshDirectoryCatalog(d)}finally{this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}});try{await Promise.all([l,...s])}finally{for(const d of o){const f=`${r}\0${d}`;this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}}}async start(t={}){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(t.directory??null,t.sessionId??null);return}try{const n=typeof t.directory=="string"&&t.directory.trim()?t.directory:null,r=!!(t.sessionId&&t.sessionDirectoryKnown===!1);if(n&&!r){await this.open(n,t.sessionId);return}if(t.sessionId&&(!t.sessionDirectoryKnown||r))try{const a=await Ie.getSession(t.sessionId,{...r?{}:{directory:n??void 0},runtimeKey:Y()});if(a?.session?.directory){await this.open(a.session.directory,t.sessionId);return}}catch{}const s=r?void 0:t.sessionId;if(n){await this.open(n,s);return}const o=await Ie.listProjects({runtimeKey:Y()}),i=o.projects.find(a=>a.selected)?.directory??o.projects[0]?.directory;if(!i){await this.connectWithoutProject();return}await this.open(i,s)}catch(n){this.reportError(n)}}async connectWithoutProject(){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(null,null);return}const t=++this.runtimeGeneration;this.focusGeneration=t,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.clearTranscriptPrefetch(),this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"loading",sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();try{const n=await Ie.health({runtimeKey:Y()});if(t!==this.runtimeGeneration)return;if(n.state!=="ready")throw new at(n.error?.code??"DAEMON_UNAVAILABLE",n.error?.message);const r=n.streamEpoch;typeof r=="string"&&r.length>0&&this.streamEpoch!==null&&r!==this.streamEpoch?this.applyVerifiedEpochChange(r):this.adoptStreamEpoch(r),this.recordClusterConnectionChange("ready"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"ready",sessionsListStatus:"idle",focusPending:!1,error:null},this.attachClusterStream(t,Y()),this.emit([At,yt]),this.refreshPendingInputList()}catch(n){t===this.runtimeGeneration&&this.reportError(n)}}attachClusterStream(t,n){if(this.stream||t!==this.runtimeGeneration)return;const r=this.streamGeneration+1;this.streamGeneration=r;const s=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamGeneration,o=this.streamEpoch?this.streamCursor():void 0;this.stream=Gl({onEvent:i=>{s()&&this.apply(i)},onReconnect:()=>this.markStreamReconnected(t,n,r),onEpochChange:i=>{s()&&this.handleVerifiedEpochChange(i)},onAuthRequired:()=>{s()&&this.handleStreamAuthRequired()}},{...this.streamEpoch?{streamEpoch:this.streamEpoch}:{},...o!==void 0?{fromSequence:o}:{},runtimeKey:n})}async focusProject(t,n){const r=typeof t=="string"&&t.trim()?t.trim():null,s=de(r)===de(this.state.directory),o=n??null;if(s){if(!o||o===this.state.selectedSessionId)return;await this.select(o);return}if(!r){this.state={...this.state,directory:null,sessions:[],sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();return}const i=++this.focusGeneration,a=this.selectionRevision;this.pendingFocus={directory:r,expected:i,preferredSessionId:o},this.pendingPreferredSessionId=o,this.clearTranscriptPrefetch();const l=!!o&&this.hydratedSessionIds.has(o);this.state={...this.state,directory:r,sessions:[],selectedSessionId:l?o:o??null,sessionsListStatus:"loading",focusPending:!l,error:null},this.emitChrome(),l&&this.touchLastAccess(o),await this.resolveFocus(i,r,a)}async resolveFocus(t,n,r){const s=Y(),o=this.runtimeGeneration,i=this.state.catalog;let a=this.pendingPreferredSessionId,l=n;try{try{const v=await Ie.selectProject(n,{runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=v.directory,de(l)!==de(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}catch(v){if(!this.shouldRetryFocusError(v))throw v;if(await l2(),t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=(await Ie.selectProject(n,{runtimeKey:s})).directory,de(l)!==de(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}const d=await this.fetchFocusListWithRetry(l,t,o,s);if(d.kind==="stale")return;if(d.kind==="failed"){this.failFocus(t,d.error);return}const f={sessions:this.filterDeletedListItems(d.payload.sessions)};if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;a=this.newerSelection(r,l)??a;let u=a?f.sessions.find(v=>v.session.id===a):void 0;if(a&&!u&&!this.isDeleted(a))try{const v=await Ie.getSession(a,{directory:l,runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;if(v?.session?.id)if(v.session.directory&&de(v.session.directory)!==de(l)&&t===this.focusGeneration){if(!this.newerSelection(r,l)){await this.focusProject(v.session.directory,a);return}}else f.sessions.unshift({session:v.session,updatedAt:v.session.updatedAt}),u={session:v.session,updatedAt:v.session.updatedAt}}catch(v){if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;gi(v)&&this.commitDeletion(a,l)}if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;const h=this.newerSelection(r,l),m=a&&!this.isDeleted(a),g=(h&&!this.isDeleted(h)?h:null)??u?.session.id??(m?a:f.sessions.find(v=>!v.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const x=this.createDirectoryListGates(d.payload),b=bf(i,this.state.catalog,l,f.sessions,Date.now(),this.deletedSessionIds,x.options),S=b!==this.state.catalog;this.state={...this.state,sessions:f.sessions,selectedSessionId:g,sessionsListStatus:"ready",focusPending:!!g&&!this.hydratedSessionIds.has(g),error:null,catalog:b},x.commit(f.sessions);const y=[At];S&&y.push(yt),this.emit(y),S&&this.raiseOrderingBaselinesForDirectory(l),g&&this.touchLastAccess(g),g&&!this.hydratedSessionIds.has(g)?(await this.hydrate(g,this.runtimeGeneration),t===this.focusGeneration&&this.state.focusPending&&this.state.selectedSessionId===g&&this.hydratedSessionIds.has(g)&&(this.state={...this.state,focusPending:!1},this.emitChrome())):g&&this.hydratedSessionIds.has(g)&&this.state.focusPending&&(this.state={...this.state,focusPending:!1},this.emitChrome())}catch(d){t===this.focusGeneration&&o===this.runtimeGeneration&&this.failFocus(t,In(d))}finally{t===this.focusGeneration&&this.pendingFocus?.expected===t&&(this.pendingFocus=null)}}failFocus(t,n){t===this.focusGeneration&&(this.state={...this.state,sessions:[],sessionsListStatus:"failed",focusPending:!1,error:n},this.emitChrome())}shouldRetryFocusError(t){if(t instanceof at){if(t.code==="DAEMON_UNAVAILABLE")return!0;const n=t.status;return typeof n=="number"&&n>=500&&n<600||n===408||n===429}return!0}async fetchFocusListWithRetry(t,n,r,s){try{const o=await Ie.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(o))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:o}}catch(o){if(!this.shouldRetryFocusError(o))return{kind:"failed",error:In(o)};if(await l2(),n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};try{const i=await Ie.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(i))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:i}}catch(i){return{kind:"failed",error:In(i)}}}}startTranscriptPrefetch(t,n,r,s){if(!t||this.isDeleted(t))return;const o=Ie.getSession(t,{directory:n,runtimeKey:r});o.catch(()=>{}),this.transcriptPrefetch={sessionId:t,directory:n,runtimeKey:r,generation:s,promise:o}}clearTranscriptPrefetch(){this.transcriptPrefetch=null}takeTranscriptPrefetch(t,n,r,s){const o=this.transcriptPrefetch;return this.transcriptPrefetch=null,!o||o.generation!==s||o.sessionId!==t||o.directory!==n||o.runtimeKey!==r||this.isDeleted(t)?null:o.promise}async consumeTranscriptPrefetch(t,n,r,s){const o=this.takeTranscriptPrefetch(t,n,r,s);if(o)try{const i=await o;return s!==this.runtimeGeneration?void 0:i}catch{return}}async open(t,n){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){if(de(t)===de(this.state.directory)){n&&n!==this.state.selectedSessionId&&await this.select(n);return}await this.focusProject(t,n??null);return}if(t===this.state.directory&&this.state.connection==="loading"){n&&n!==this.state.selectedSessionId&&(this.pendingPreferredSessionId=n,this.state={...this.state,selectedSessionId:n,error:null},this.emitChrome());return}if(t===this.state.directory&&this.state.connection==="ready"){n&&n!==this.state.selectedSessionId&&await this.select(n);return}this.providerRefreshRevisionByDirectory.clear();const r=++this.runtimeGeneration;this.focusGeneration=r,this.pendingFocus=null;const s=!n&&this.userSelection&&(!this.userSelection.directory||de(this.userSelection.directory)===de(t))?this.userSelection.id:null;this.pendingPreferredSessionId=n??s;const o=this.selectionRevision;this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:t,selectedSessionId:this.pendingPreferredSessionId,connection:"loading",hydratedSessionIds:new Set,reducer:{bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)}},this.stripAwaitingPromptEchoMarkers(),this.emitChrome();const i=Y(),a=this.state.catalog;this.pendingPreferredSessionId&&this.startTranscriptPrefetch(this.pendingPreferredSessionId,t,i,r);try{const l=await Ie.selectProject(t,{runtimeKey:i});if(r!==this.runtimeGeneration)return;const d={directory:l.directory,runtimeKey:i};l.directory!==t&&(this.state={...this.state,directory:l.directory},this.emitChrome());const f=await Ie.health(d);if(r!==this.runtimeGeneration)return;if(f.state!=="ready")throw new at(f.error?.code??"DAEMON_UNAVAILABLE",f.error?.message);const u=f.streamEpoch;typeof u=="string"&&u.length>0&&this.streamEpoch!==null&&u!==this.streamEpoch?(this.applyVerifiedEpochChange(u),this.emit([At,yt])):this.adoptStreamEpoch(u);const h={state:"ready",protocolVersion:f.protocolVersion,capabilities:[...f.capabilities],...typeof f.streamEpoch=="string"?{streamEpoch:f.streamEpoch}:{}},m=await Ie.listSessions(d);if(r!==this.runtimeGeneration)return;if(!this.isResponseEpochCurrent(m))throw new at("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const g=this.filterDeletedListItems(m.sessions),x=this.newerSelection(o,l.directory)??this.pendingPreferredSessionId??n;let b=x?g.find(A=>A.session.id===x):void 0,S=null;if(x&&!b&&!this.isDeleted(x))try{const A=await(this.takeTranscriptPrefetch(x,t,i,r)??Ie.getSession(x,{directory:t,runtimeKey:i}));if(r!==this.runtimeGeneration)return;if(A?.session?.directory&&A.session.directory!==t){if(r!==this.runtimeGeneration)return;if(!this.newerSelection(o,l.directory)){await this.open(A.session.directory,x);return}}else A?.session?.id&&(g.unshift({session:A.session,updatedAt:A.session.updatedAt}),b={session:A.session,updatedAt:A.session.updatedAt},S=A)}catch(A){if(r!==this.runtimeGeneration)return;gi(A)&&this.commitDeletion(x,t)}const y=this.newerSelection(o,l.directory),v=x&&!this.isDeleted(x),C=(y&&!this.isDeleted(y)?y:null)??b?.session.id??(v?x:g.find(A=>!A.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const w=this.createDirectoryListGates(m,{streamAttaching:!0}),I=bf(a,this.state.catalog,l.directory,g,Date.now(),this.deletedSessionIds,w.options),E=I!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,sessions:g,selectedSessionId:C,connection:"ready",catalog:I},w.commit(g);const T=[At];if(E&&T.push(yt),this.emit(T),E&&this.raiseOrderingBaselinesForDirectory(l.directory),this.refreshPendingInputList(),C){let A;C===x?A=S??await this.consumeTranscriptPrefetch(C,t,i,r):this.clearTranscriptPrefetch(),await this.hydrate(C,r,void 0,{initialHealth:h,initialSessions:g,...A?{initialDetail:A}:{}})}}catch(l){r===this.runtimeGeneration&&this.reportError(l)}}async select(t,n){if(!t)return;const r=n??this.state.reducer.bySession.get(t)?.directory??this.state.sessions.find(o=>o.session.id===t)?.session.directory;if(this.userSelection={id:t,directory:r??this.state.directory,revision:++this.selectionRevision},r&&de(r)!==de(this.state.directory)){if(this.stream!==null){await this.focusProject(r,t);return}await this.open(r,t);return}if(this.state.connection==="loading"){if(this.state.selectedSessionId===t)return;this.pendingPreferredSessionId=t,this.state={...this.state,selectedSessionId:t,error:null},this.emitChrome();return}if(!this.state.directory){await this.focusProject(null,t);return}if(t===this.state.selectedSessionId){this.touchLastAccess(t);const o=this.state.reducer.bySession.get(t);(!this.hydratedSessionIds.has(t)||!o)&&await this.hydrate(t,this.runtimeGeneration),this.scheduleIdleEviction();return}this.state.directory&&this.lastSelectedByDirectory.set(de(this.state.directory)??this.state.directory,t),this.cadence.flush(),this.state={...this.state,selectedSessionId:t,error:null,focusPending:!1},this.emitChrome(),this.touchLastAccess(t);const s=this.state.reducer.bySession.get(t);if(this.stream&&this.hydratedSessionIds.has(t)&&s){this.scheduleIdleEviction();return}await this.hydrate(t,this.runtimeGeneration)}lastSelectedSessionForDirectory(t){return t?this.lastSelectedByDirectory.get(de(t)??t)??null:null}async ensureHydrated(t){if(!t)return;const n=this.state.reducer.bySession.get(t);if(this.hydratedSessionIds.has(t)&&n){this.touchLastAccess(t);return}await this.hydrate(t,this.runtimeGeneration)}async create(t,n){const r=n?.directory||this.directory(),s=this.runtimeGeneration;let o=n?.model,i=n?.thinking;if(!o||!i&&!We.getState().isInitialized){const u=await Ie.getSettings({directory:r,runtimeKey:Y()});o??=u.pichamber.defaultModel,i=u0({thinking:i,model:o,defaultThinkingByModel:u.pichamber.defaultThinkingByModel,defaultThinking:u.pichamber.defaultThinking})}else if(!i){const u=We.getState();i=u0({model:o,defaultThinkingByModel:u.settingsDefaultThinkingByModel,defaultThinking:u.settingsDefaultThinking})}const a=await Ie.createSession({cwd:r,...t?{title:t}:{},...o?{model:o}:{},...i?{thinking:i}:{}},{directory:r,runtimeKey:Y()});if(s!==this.runtimeGeneration)return a.session.id;this.state={...this.state,sessions:[{session:a.session,updatedAt:a.session.updatedAt},...this.state.sessions],selectedSessionId:n?.select===!1?this.state.selectedSessionId:a.session.id};const l=s2(this.state.catalog,this.recordFromPiSession(a.session)),d=l!==this.state.catalog;this.state={...this.state,catalog:l};const f=[At];return d&&f.push(yt),this.emit(f),await this.hydrate(a.session.id,s,a),a.session.id}async rename(t,n){const r=this.runtimeGeneration,s=Y();if(await Ie.renameSession({sessionId:t,title:n},this.scope()),r!==this.runtimeGeneration||s!==Y())return;const o=Date.now(),i=Fc(this.state.catalog,t,n,o),a=i!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(d=>d.session.id===t?{...d,session:{...d.session,title:n}}:d),catalog:i};const l=[At];a&&l.push(yt),this.emit(l)}resolveSessionDirectory(t,n){return n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(r=>r.session.id===t)?.session.directory}async archive(t,n,r){const s=this.runtimeGeneration,o=Y(),i=this.resolveSessionDirectory(t,r),a=this.state.catalog.byId.get(t),l=a?.archived??this.state.sessions.find(m=>m.session.id===t)?.session.archived,d=a?.updatedAt,f=a?.archivedAt,u=++this.archiveRevision;this.archiveRevisionById.set(t,u);const h=Date.now();this.commitArchiveFlag(t,n,h,n?h:void 0);try{await Ie.archiveSession({sessionId:t,archived:n},this.scope(i))}catch(m){if(s===this.runtimeGeneration&&o===Y()&&this.archiveRevisionById.get(t)===u&&typeof l=="boolean"){const x=this.state.catalog.byId.get(t)?.updatedAt,b=x===h&&d!==void 0?d:x??h;this.commitArchiveFlag(t,l,b,f)}throw m}finally{this.archiveRevisionById.get(t)===u&&this.archiveRevisionById.delete(t)}}commitArchiveFlag(t,n,r,s){const o=r2(this.state.catalog,t,n,r,s),i=o!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(l=>l.session.id===t?{...l,session:{...l.session,archived:n}}:l),catalog:o};const a=[At];i&&a.push(yt),this.emit(a)}unarchiveForSend(t){const n=this.state.catalog.byId.get(t);if(!n?.archived)return()=>{};const r=++this.sendUnarchiveCounter;this.sendUnarchiveTokenById.set(t,r),this.setArchivedLocally(t,!1);const s=this.runtimeGeneration,o=n.directory,i=n.archivedAt;return a=>{if(!(s!==this.runtimeGeneration||this.sendUnarchiveTokenById.get(t)!==r)&&(this.sendUnarchiveTokenById.delete(t),a!==void 0)){if(bE(a)){this.state.catalog.byId.get(t)?.archived===!1&&this.setArchivedLocally(t,!0,i);return}o&&this.refreshDirectoryCatalog(o)}}}setArchivedLocally(t,n,r){const s=this.state.catalog.byId.get(t);if(!s)return;const o=r2(this.state.catalog,t,n,s.updatedAt,r),i=o!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(l=>l.session.id===t?{...l,session:{...l.session,archived:n}}:l),catalog:o};const a=[At];i&&a.push(yt),this.emit(a)}scheduleRemoteSendRefresh(t){if(!t||this.remoteSendRefreshTimers.has(t))return;const n=this.runtimeGeneration,r=setTimeout(()=>{this.remoteSendRefreshTimers.delete(t),n===this.runtimeGeneration&&this.refreshDirectoryCatalog(t)},this.remoteSendRefreshDelayMs);this.remoteSendRefreshTimers.set(t,r)}async remove(t,n){const r=this.runtimeGeneration,s=Y(),o=this.resolveSessionDirectory(t,n);if(await Ie.deleteSession({sessionId:t,ignoreMissing:!0},o?this.scope(o):this.scope()),r!==this.runtimeGeneration||s!==Y())return;const i=this.state.selectedSessionId;this.commitDeletion(t,o);const a=this.state.selectedSessionId;a&&a!==i&&await this.hydrate(a,r)}async fork(t,n){const r=this.state.sessions.find(l=>l.session.id===t)?.session.title??this.state.catalog.byId.get(t)?.title??"",s=this.runtimeGeneration,o=Y(),i=await Ie.forkSession({sessionId:t,...n?{messageId:n}:{}},this.scope());if(s!==this.runtimeGeneration||o!==Y())return;this.upsertAndHydrate(i);const a=i.session.title?.trim()||r.trim()||"Untitled";if(!a.includes("(Fork)")){const l=`${a} (Fork)`;this.rename(i.session.id,l).catch(()=>{})}}async clone(t){const n=this.runtimeGeneration,r=Y(),s=await Ie.cloneSession({sessionId:t},this.scope());n!==this.runtimeGeneration||r!==Y()||this.upsertAndHydrate(s)}async navigate(t,n){const r=this.state.reducer.bySession.get(t),s=r?[...r.messages.values()]:[],o=new Map;for(const l of s){const d=typeof l.text=="string"?l.text.trim():"";d&&o.set(l.id,d)}const i=this.runtimeGeneration,a=(this.navigationGenerationById.get(t)??0)+1;this.navigationGenerationById.set(t,a),this.navigationCounter=Math.max(this.navigationCounter,a),this.hydrateInflightById.delete(t),this.historyInflightById.delete(t);try{const l=await Ie.navigateSession(t,n,this.scope());if((this.navigationGenerationById.get(t)??0)!==a||i!==this.runtimeGeneration||!this.isResponseEpochCurrent(l))return l;const d=this.sessionFromDetail(l);this.commitNavigationSession(d,yi(l),l.session);const f=l.navigation;if(f&&typeof f.targetEntryId=="string"&&l.hasMoreBefore!==!0){const u=new Set(l.messages.map(b=>b.message.id)),h=s.filter(b=>!u.has(b.id)).map(b=>{const S=(o.get(b.id)??"").replace(/\s+/g," ").slice(0,120)||"[No text]",y=b.role==="assistant"?"assistant":"user";return{id:b.id,role:y,preview:S}}),m=Um(t),g=new Set(h.map(b=>b.id)),x=[...h];for(const b of m?.abandoned??[])!u.has(b.id)&&!g.has(b.id)&&(x.push(b),g.add(b.id));x.length===0?yf(t):ZI(t,m?{...f,previousLeafId:m.previousLeafId}:f,x)}return l}catch(l){throw this.navigationGenerationById.get(t)===a&&(a<=1?this.navigationGenerationById.delete(t):this.navigationGenerationById.set(t,a-1)),l}}async prompt(t,n,r,s,o){const i=this.runtimeGeneration,a=o?.runtimeKey??Y(),l={directory:this.resolveSessionDirectory(t,o?.directory),runtimeKey:a,...o?.streamEpoch?{streamEpoch:o.streamEpoch}:{}};if(a!==Y())throw new Error("Runtime changed before sending message.");let d=this.state.reducer.bySession.get(t);const f=o?.knownEmptyTranscript===!0&&this.hydratedSessionIds.has(t)&&d!==void 0&&d.messages.size===0;if((!d||d.messages.size===0)&&!f){if(await this.hydrate(t,i),i!==this.runtimeGeneration||a!==Y())throw new Error("Runtime changed before sending message.");d=this.state.reducer.bySession.get(t)}const u=o?.operationId??j5(),h={sessionId:t,text:n,operationId:u,messageId:`msg_${u}`,clientId:xb(),...s?.length?{attachments:s}:{}},m=d?{...d,lifecycle:"busy"}:{sessionId:t,directory:this.state.directory??this.state.sessions.find(w=>w.session.id===t)?.session.directory??"",lastSequence:this.state.reducer.lastSequence.get(t)??-1,lifecycle:"busy",messages:new Map,partOrder:new Map,parts:Xl(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};if(r==="prompt"){let w=null;if(d)for(const I of d.messages.values())I.role==="user"&&(w=I.id);m.awaitingPromptEcho={baselineUserMessageId:w}}else m.awaitingPromptEcho=void 0;const g=new Map(this.state.reducer.bySession);g.set(t,m),this.state={...this.state,reducer:{...this.state.reducer,bySession:g}};const x=(this.promptGenerationById.get(t)??0)+1;this.promptGenerationById.set(t,x),this.pendingPromptById.add(t),this.promoteSession(t,"active",{reorder:!0}),this.touchSessionList(t);const b=Date.now(),S=n2(Xs(this.state.catalog,t,"busy"),t,b,{directory:m.directory||this.state.directory||"",lifecycle:"busy"}),y=S!==this.state.catalog;this.state={...this.state,catalog:S};const v=[`session:${t}`,At];y&&v.push(yt),this.emit(v);const C=this.unarchiveForSend(t);try{let w;return r==="steer"?w=await Ie.sendSteer(h,l):r==="followUp"?w=await Ie.sendFollowUp(h,l):w=await Ie.sendPrompt(h,l),this.promptGenerationById.get(t)===x&&this.acceptedPromptGenerationById.set(t,x),yf(t),r==="prompt"&&n.trimStart().startsWith("/")&&this.reconcileAcceptedSlashPrompt(t,x,i),C(),w}catch(w){if(C(w),MS("prompt-send",w),i!==this.runtimeGeneration||a!==Y())throw w;if(Sf(w)&&this.failSessionLoad(t,w),this.promptGenerationById.get(t)===x){this.pendingPromptById.delete(t);const I=this.state.reducer.bySession.get(t);if(I?.lifecycle==="busy"&&I.streamingMessages.size===0){const E=new Map(this.state.reducer.bySession);E.set(t,{...I,lifecycle:"error",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:E}},this.promoteSession(t,"settled"),this.emit([`session:${t}`,At])}}throw w}}async reconcilePendingPromptSnapshot(t,n,r){const o=this.state.reducer.bySession.get(t)?.directory||this.resolveSessionDirectory(t)||this.state.directory;if(!o)return!1;try{const i=await Ie.getSession(t,{directory:o,runtimeKey:Y()});if(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||i.session.id!==t||!this.isResponseEpochCurrent(i)||(this.state.reducer.lastSequence.get(t)??this.state.reducer.bySession.get(t)?.lastSequence??-1)>i.lastSequence)return!1;(i.lifecycle==="busy"||i.lifecycle==="retry")&&typeof i.runStartedAt=="number"&&Mn(i.session.id,i.runStartedAt,i.serverNow);const l=i.lifecycle!=="busy"&&i.lifecycle!=="retry"&&i.isStreaming!==!0;if(l){this.pendingPromptById.delete(t);const d=this.state.reducer.bySession.get(t);if(d?.lifecycle==="busy"||d?.lifecycle==="retry"){const f=new Map(this.state.reducer.bySession);f.set(t,{...d,lifecycle:"idle",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:f}}}}return this.commitSessionDetail(i),l}catch{return!1}}reconcileAcceptedPromptFromList(t){const n=this.promptGenerationById.get(t);if(n!==void 0){if(this.acceptedPromptReconcileInFlight.has(t)){this.acceptedPromptReconcileInFlight.set(t,!0);return}this.acceptedPromptReconcileInFlight.set(t,!1),this.reconcilePendingPromptSnapshot(t,n,this.runtimeGeneration).catch(()=>!1).finally(()=>{const r=this.acceptedPromptReconcileInFlight.get(t)===!0;this.acceptedPromptReconcileInFlight.delete(t);const s=this.promptGenerationById.get(t);r&&this.pendingPromptById.has(t)&&s!==void 0&&this.acceptedPromptGenerationById.get(t)===s&&this.reconcileAcceptedPromptFromList(t)})}}async reconcileAcceptedSlashPrompt(t,n,r){await new Promise(s=>setTimeout(s,750)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||!this.pendingPromptById.has(t))&&await this.reconcilePendingPromptSnapshot(t,n,r)&&(await new Promise(s=>setTimeout(s,2e3)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n)&&await this.reconcilePendingPromptSnapshot(t,n,r))}abort=t=>Ie.abortSession({sessionId:t},this.scope());compact=(t,n)=>Ie.compactSession({sessionId:t,...n?{customInstructions:n}:{}},this.scope());runBash=async(t,n,r)=>{const s=this.scope(),o=this.unarchiveForSend(t);try{const i=await Ie.runBash({sessionId:t,command:n,...r?.excludeFromContext?{excludeFromContext:!0}:{}},s);return o(),i}catch(i){throw o(i),i}};abortBash=t=>Ie.abortBash({sessionId:t},this.scope());setModel=(t,n,r)=>Ie.setSessionModel({sessionId:t,model:{providerId:n,modelId:r}},this.scope());setThinking=(t,n)=>Ie.setSessionThinking({sessionId:t,thinking:n},this.scope());tree=t=>Ie.getSessionTree(t,this.scope());providers=()=>Ie.listProviders({runtimeKey:Y()});upload=t=>Ie.createAttachment(t,this.scope());uploadFile=(t,n)=>Ie.uploadAttachment(t,n,this.scope());deleteUpload=t=>Ie.deleteAttachment(t,this.scope());selected(){const t=this.state.selectedSessionId,n=t?this.state.reducer.bySession.get(t):void 0;return n?yb(n):null}consumeExtensionEditor(t,n){const r=this.state.reducer.bySession.get(t);if(!r)return;const o=(r.extensionEditorOps??(r.extensionEditor?[r.extensionEditor]:[])).filter(l=>l.sequence>n),i=o.length>0?o[o.length-1]:void 0;if(r.extensionEditor===void 0&&r.extensionEditorOps===void 0&&o.length===0)return;const a=new Map(this.state.reducer.bySession);a.set(t,{...r,extensionEditorOps:o.length>0?o:void 0,extensionEditor:i}),this.state={...this.state,reducer:{...this.state.reducer,bySession:a}},this.emit([`session:${t}`])}dismissExtensionDialog(t,n){const r=E6(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`,Bc]))}dropExtensionSurface(t,n){const r=T6(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`]))}sessionFromDetail(t){return ed(t).session}async loadOlderMessages(t){const n=this.historyInflightById.get(t);if(n)return n;const r=this.state.reducer.bySession.get(t);if(!r?.hasMoreBefore||!r.beforeCursor||this.isDeleted(t))return!1;const s=this.runtimeGeneration,o=this.navigationGenerationById.get(t)??0,i=r.beforeCursor,a=Y(),l=Ie.getSessionMessages(t,{before:i},{directory:r.directory,runtimeKey:a}).then(d=>{if(s!==this.runtimeGeneration||a!==Y()||(this.navigationGenerationById.get(t)??0)!==o)return!1;const f=this.state.reducer.bySession.get(t);if(!f||f.beforeCursor!==i||d.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(d))return!1;const u=ed(d).session,h=new Map(u.messages);for(const[y,v]of f.messages)h.set(y,v);const m=new Map(u.partOrder);for(const[y,v]of f.partOrder)m.set(y,v);const g=Xl(u.parts);for(const[y,v]of f.parts)g.set(y,v);const x=new Map(u.toolsByCallId);for(const[y,v]of f.toolsByCallId)x.set(y,v);const b={...f,messages:h,partOrder:m,parts:g,toolsByCallId:x,hasMoreBefore:u.hasMoreBefore===!0,beforeCursor:u.beforeCursor,lastSequence:f.lastSequence},S={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};return S.bySession.set(t,b),this.state={...this.state,reducer:S},this.touchLastAccess(t),this.emit([`session:${t}`]),b.hasMoreBefore===!0}).finally(()=>{this.historyInflightById.get(t)===l&&this.historyInflightById.delete(t)});return this.historyInflightById.set(t,l),l}recordFromPiSession(t,n){return gE(t,this.state.catalog,n)}mergeHydratedSession(t,n){return yE(t,n,{localSendPending:this.pendingPromptById.has(t.sessionId)})}touchLastAccess(t){t&&(this.lastAccessClock+=1,this.lastAccessById.set(t,this.lastAccessClock))}commitNavigationSession(t,n,r){this.cadence.flush();const s=this.state.reducer.bySession.get(t.sessionId),o=s?{...t,lastSequence:Math.max(t.lastSequence,s.lastSequence),...s.model&&!t.model?{model:s.model}:{},...s.thinking&&!t.thinking?{thinking:s.thinking}:{},queue:s.queue.steering>0||s.queue.followUp>0?s.queue:t.queue}:t,i={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};i.bySession.set(o.sessionId,o),i.lastSequence.set(o.sessionId,o.lastSequence),this.hydratedSessionIds.add(o.sessionId),this.touchLastAccess(o.sessionId);const l=this.state.selectedSessionId===o.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let d=this.state.sessionLoadErrorById;if(d.has(o.sessionId)){const g=new Map(d);g.delete(o.sessionId),d=g}const f=Vc(o.lifecycle);let u=this.state.catalog;u.byId.has(o.sessionId)||(u=Cs(u,o.sessionId,o.directory,f)),u=xf(u,o.sessionId,!0),u=Xs(u,o.sessionId,f,o.retry),n&&(u=this.adoptDetailPendingInput(u,o.sessionId,o.directory,{pending:n.pending},n.sequence)),r&&(u=d2(u,o.sessionId,o.directory,r.messageCount));const h=u!==this.state.catalog;this.state={...this.state,reducer:i,error:null,focusPending:l,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:d,catalog:u};const m=[`session:${o.sessionId}`,At];h&&m.push(yt),this.emit(m),this.scheduleIdleEviction()}commitSessionDetail(t,n=[]){this.commitHydratedSession(this.sessionFromDetail(t),n,yi(t),t.session)}commitHydratedSession(t,n=[],r,s){if(this.isDeleted(t.sessionId))return;this.cadence.flush();const o=this.state.reducer.bySession.get(t.sessionId),i=this.mergeHydratedSession(t,o);(i.lifecycle==="busy"||i.lifecycle==="retry")&&P0(i.sessionId,"active");let a={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};a.bySession.set(i.sessionId,i),a.lastSequence.set(i.sessionId,i.lastSequence);for(const S of n){const y=tf(a,S);a=y.state,y.didApply&&this.observeActivity(S)}this.hydratedSessionIds.add(i.sessionId),this.touchLastAccess(i.sessionId);const d=this.state.selectedSessionId===i.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let f=this.state.sessionLoadErrorById;if(f.has(i.sessionId)){const S=new Map(f);S.delete(i.sessionId),f=S}let u=this.applyCatalogFromEvents(n,a);r&&(u=this.adoptDetailPendingInput(u,i.sessionId,i.directory,{pending:r.pending},r.sequence));const h=a.bySession.get(i.sessionId),m=h?.lifecycle,g=m?Vc(m):void 0;u.byId.has(i.sessionId)||(u=Cs(u,i.sessionId,i.directory,g??"idle")),u=xf(u,i.sessionId,!0),g!==void 0&&(u=Xs(u,i.sessionId,g,h?.retry)),s&&(u=d2(u,i.sessionId,i.directory,s.messageCount));const x=u!==this.state.catalog;this.state={...this.state,reducer:a,error:null,focusPending:d,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:f,catalog:u};const b=[`session:${i.sessionId}`,At,Bc];x&&b.push(yt),this.emit(b),this.scheduleIdleEviction()}async hydrate(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.hydrateInflightById.get(t);if(o)return o;const i=this.hydrateUnshared(t,n,r,s).finally(()=>{this.hydrateInflightById.get(t)===i&&this.hydrateInflightById.delete(t)});return this.hydrateInflightById.set(t,i),i}async hydrateUnshared(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.resolveSessionDirectory(t)||this.directory(),i=Y(),l=!!(this.state.reducer.bySession.get(t)&&this.hydratedSessionIds.has(t)),d=this.navigationGenerationById.get(t)??0;if(!s?.force&&this.stream&&l&&!r){this.state.connection==="error"||this.state.connection==="unavailable"?this.reconnect(t,n,i):this.state.connection==="ready"&&this.state.error&&(this.state={...this.state,error:null},this.emitChrome());return}this.clearSessionLoadError(t);const f=this.stream;try{if(this.stream){const w=r??await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||w.session.id!==t||!this.isResponseEpochCurrent(w)||this.isDeleted(t)||(this.navigationGenerationById.get(t)??0)!==d)return;(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),this.commitSessionDetail(w);return}const u=[];let h=!1;const m=this.streamGeneration+1;this.streamGeneration=m;const g=()=>n===this.runtimeGeneration&&i===Y()&&m===this.streamGeneration,x=w=>{g()&&(h?this.apply(w):u.push(w))},b=await q6({directory:o,selectedSessionId:t,runtimeKey:i,...s?.initialHealth?{initialHealth:s.initialHealth}:{},...s?.initialSessions?{initialSessions:s.initialSessions}:{},...s?.initialDetail?{initialDetail:s.initialDetail}:{},onEvent:x,onStreamDisconnect:()=>{g()&&this.reconnect(this.state.selectedSessionId??t,n,i)},onStreamReconnect:()=>this.markStreamReconnected(n,i,m),onEpochChange:w=>{g()&&this.handleVerifiedEpochChange(w)},onAuthRequired:()=>{g()&&this.handleStreamAuthRequired()}});if(!g()){b.stream?.dispose();return}if(b.phase==="failed")throw b.stream?.dispose(),b.errors.at(-1)?.error??new at("DAEMON_PROTOCOL_MISMATCH","The Pi runtime returned an incompatible bootstrap response.");const S=b.selectedSessionTiming;S&&S.sessionId===t&&(S.lifecycle==="busy"||S.lifecycle==="retry")&&typeof S.runStartedAt=="number"&&Mn(S.sessionId,S.runStartedAt,S.serverNow);let y=r?this.sessionFromDetail(r):b.reducerState.bySession.get(t),v=r?yi(r):s?.initialDetail?yi(s.initialDetail):void 0,C=r?.session??s?.initialDetail?.session;if(r&&(r.lifecycle==="busy"||r.lifecycle==="retry")&&typeof r.runStartedAt=="number"&&Mn(r.session.id,r.runStartedAt,r.serverNow),!y)try{const w=r??await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if(!this.isResponseEpochCurrent(w)){b.stream?.dispose();return}(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),v=yi(w),y=this.sessionFromDetail(w),C=w.session}catch(w){if(this.stream=b.stream,h=!0,n===this.runtimeGeneration&&gi(w)){this.handleInvalidSession(t,o,n,u);return}if(n===this.runtimeGeneration&&Sf(w)){u.length>0&&this.commitEvents(u),this.failSessionLoad(t,In(w));return}throw b.stream?.dispose(),this.stream=null,w}if(y.sessionId!==t){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if((this.navigationGenerationById.get(t)??0)!==d){b.stream?.dispose();return}this.stream=b.stream,this.commitHydratedSession(y,u,v,C),h=!0}catch(u){if(n!==this.runtimeGeneration)return;if(gi(u)){this.handleInvalidSession(t,o,n);return}if(Sf(u)){this.failSessionLoad(t,In(u));return}if(mE(u)){try{const h=await Ie.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||h.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(h)||(this.navigationGenerationById.get(t)??0)!==d)return;(h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)}catch(h){if(n!==this.runtimeGeneration)return;this.failSessionLoad(t,In(h))}return}if(f&&this.stream===f&&In(u).code!=="DAEMON_AUTH_FAILED"){this.failSessionLoad(t,In(u));return}this.reportError(u)}}markStreamReconnected(t,n,r){if(!(t!==this.runtimeGeneration||n!==Y()||r!==this.streamGeneration)){if(this.streamReadyRevision+=1,this.state.connection==="ready"&&!this.state.error){(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(this.recoveryAttempt=0,this.runSyncRecovery());return}this.recordClusterConnectionChange("ready"),this.state={...this.state,connection:"ready",error:null},this.emitChrome()}}async reconnect(t,n,r){if(this.recovering||n!==this.runtimeGeneration)return;this.recovering=!0,this.cadence.flush();const s=this.stream,o=this.streamReadyRevision,i=this.streamGeneration+1,a=this.streamCursor(),l=()=>n===this.runtimeGeneration&&r===Y()&&(this.streamGeneration===i||this.streamGeneration===i-1&&o===this.streamReadyRevision);let d=!1;try{let f=!1;const u=await Y6({directory:this.directory(),sessionId:t,runtimeKey:r,lastKnownSequence:a,streamEpoch:this.streamEpoch??void 0,onEvent:h=>{l()&&(!f&&h.name==="session.snapshot"&&h.payload?.snapshot?.resync===!0&&(f=!0,this.queueSyncRecovery({directories:"all-known",residents:this.hydratedSessionIds})),this.apply(h))},onStreamDisconnect:()=>{l()&&this.reconnect(this.state.selectedSessionId??t,n,r)},onStreamReconnect:()=>this.markStreamReconnected(n,r,i),onAuthRequired:()=>{l()&&(d=!0,this.handleStreamAuthRequired())},onEpochChange:h=>{l()&&this.handleVerifiedEpochChange(h)}});if(n!==this.runtimeGeneration||r!==Y()){u.stream?.dispose();return}if(o!==this.streamReadyRevision){u.stream?.dispose();return}if(u.phase==="ready"){typeof u.runStartedAt=="number"&&Mn(t,u.runStartedAt,u.serverNow);let h=!1;typeof u.epoch=="string"&&u.epoch.length>0&&this.streamEpoch!==u.epoch&&(h=this.applyVerifiedEpochChange(u.epoch)!==null),s?.dispose(),this.streamGeneration=i,this.stream=u.stream;const m={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)},g=[],x=[];for(const[v,C]of u.reducerState.bySession.entries()){const w=m.bySession.get(v),I=this.mergeHydratedSession(C,w);m.bySession.set(v,I),m.lastSequence.set(v,I.lastSequence),this.touchLastAccess(v),g.push(v),(w?.lifecycle==="busy"||w?.lifecycle==="retry")&&I.lifecycle!=="busy"&&I.lifecycle!=="retry"&&x.push(v)}for(const v of u.reducerState.bySession.keys())this.hydratedSessionIds.add(v);let b=this.state.catalog;for(const v of g){const C=m.bySession.get(v);C&&(b=Xs(b,v,Vc(C.lifecycle),C.retry))}const S=b!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,reducer:m,connection:"ready",error:null,hydratedSessionIds:new Set(this.hydratedSessionIds),...S?{catalog:b}:{}};const y=[At,Bc];for(const v of g)y.push(`session:${v}`);(S||h)&&y.push(yt),this.emit(y),this.refreshPendingInputList();for(const v of x)this.promoteSession(v,"settled");for(const v of g){if(!this.pendingPromptById.has(v))continue;const C=this.promptGenerationById.get(v);if(C===void 0||this.acceptedPromptGenerationById.get(v)!==C)continue;const w=u.reducerState.bySession.get(v)?.lifecycle;w==="busy"||w==="retry"||this.reconcileAcceptedPromptFromList(v)}this.scheduleIdleEviction(),h&&this.publishSyncRecoveryState()}else d||this.reportError(new at(u.error?.code??"DAEMON_UNAVAILABLE",u.error?.message))}finally{this.recovering=!1}}apply(t){this.cadence.push(t)}observeActivity(t){if(t.name==="session.lifecycle"){const n=t.payload.state==="busy"||t.payload.state==="retry";n&&typeof t.payload.runStartedAt=="number"&&Mn(t.sessionId,t.payload.runStartedAt,t.payload.serverNow),this.promoteSession(t.sessionId,n?"active":"settled",{notification:!n&&(t.payload.state==="idle"||t.payload.state==="error")?{kind:t.payload.state==="error"?"error":"completion",sequence:t.sequence,directory:t.directory}:void 0})}else if(t.name==="session.snapshot"){const n=t.payload.snapshot,r=n.lifecycle==="busy"||n.lifecycle==="retry"||n.isStreaming===!0;r&&typeof n.runStartedAt=="number"&&Mn(t.sessionId,n.runStartedAt,n.serverNow),this.promoteSession(t.sessionId,r?"active":"settled")}else t.name==="assistant.message.start"?this.promoteSession(t.sessionId,"active"):t.name==="session.interrupted"?this.promoteSession(t.sessionId,"settled"):t.name==="session.openUrl"?this.emitOpenRequest(t):t.name==="session.error"&&this.promoteSession(t.sessionId,"settled",{notification:{kind:"error",sequence:t.sequence,directory:t.directory,error:{code:t.payload.code,message:t.payload.message}}})}stripAwaitingPromptEchoMarkers(){let t=null;for(const[n,r]of this.state.reducer.bySession)r.awaitingPromptEcho!==void 0&&(t||(t=new Map(this.state.reducer.bySession)),t.set(n,{...r,awaitingPromptEcho:void 0}));t&&(this.state={...this.state,reducer:{...this.state.reducer,bySession:t}})}notePromptProgress(t){if(t.name==="assistant.message.start"||t.name==="session.lifecycle"&&(t.payload.state==="busy"||t.payload.state==="retry")){this.pendingPromptById.delete(t.sessionId);return}(t.name==="session.error"||t.name==="session.interrupted"||t.name==="session.lifecycle"&&t.payload.state!=="busy"&&t.payload.state!=="retry")&&this.pendingPromptById.delete(t.sessionId)}retainPendingPrompt(t,n){if(!this.pendingPromptById.has(n))return t;const r=t.bySession.get(n);if(!r||r.lifecycle==="busy"||r.lifecycle==="retry")return t;const s=new Map(t.bySession);return s.set(n,{...r,lifecycle:"busy"}),{...t,bySession:s}}promoteSession(t,n,r){const s=this.activityPhaseById.get(t);this.activityPhaseById.set(t,n),P0(t,n),r?.reorder&&PM(t,n);const o=r?.notification;if(!(n==="settled"&&s==="active"&&(r?.notifyIfSettled||o!==void 0)))return;const a=o?.directory??this.state.catalog.byId.get(t)?.directory??this.state.directory??void 0;this.state.selectedSessionId!==t&&Zb(t,a,o?.kind==="error"?{error:o.error??{}}:void 0),o&&Yb({sessionId:t,directory:a,sequence:o.sequence,kind:o.kind,title:this.state.catalog.byId.get(t)?.title})}touchSessionList(t){const n=this.state.sessions.findIndex(i=>i.session.id===t);if(n<0)return;const r=Date.now(),s=this.state.sessions[n];if(!s)return;const o=this.state.sessions.slice();o.splice(n,1),o.unshift({...s,updatedAt:r,session:{...s.session,updatedAt:r}}),this.state={...this.state,sessions:o}}requestProviderCatalogRefresh(t,n=!0){if(n){const i=(this.providerRefreshRevisionByDirectory.get(t)??0)+1;this.providerRefreshRevisionByDirectory.set(t,i)}if(this.providerRefreshTaskByDirectory.has(t))return;const r=this.runtimeGeneration;let s=0;const o=(async()=>{for(;r===this.runtimeGeneration;){const i=this.providerRefreshRevisionByDirectory.get(t)??0;if(i<=s)return;try{await We.getState().loadProviders({directory:t,source:"extension.catalog"})}finally{s=i}}})().catch(()=>{}).finally(()=>{if(this.providerRefreshTaskByDirectory.get(t)!==o)return;this.providerRefreshTaskByDirectory.delete(t);const i=this.providerRefreshRevisionByDirectory.get(t)??0;(r!==this.runtimeGeneration&&i>0||i>s)&&this.requestProviderCatalogRefresh(t,!1)});this.providerRefreshTaskByDirectory.set(t,o)}restoreTranscript(t){if(!t||this.restoringTranscriptById.has(t))return;this.restoringTranscriptById.add(t);const n=this.runtimeGeneration;this.hydrate(t,n,void 0,{force:!0}).finally(()=>{this.restoringTranscriptById.delete(t)})}commitEvents(t){if(t.length===0)return;let n=this.state.reducer,r=!1,s=!1;const o=new Set,i=new Set,a=new Map,l=[],d=[],f=new Map,u=new Map;for(const y of t){if(y.name!=="session.deleted")continue;const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0,C=u.get(v)??new Set;C.add(y.sessionId),u.set(v,C)}let h=null;for(const y of t){const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0;if(!v&&this.streamEpoch!==null||v&&this.retiredStreamEpochs.has(v))continue;if(v&&this.streamEpoch!==null&&v!==this.streamEpoch){if(y.name!=="session.snapshot")continue;this.adoptStreamEpoch(v);const j=this.resetForEpochChange();if(n=Jl(),o.clear(),h)for(const k of j)h.add(k);else h=j;i.clear(),a.clear(),f.clear(),l.length=0,r=!1,s=!1}if(v&&this.adoptStreamEpoch(v),this.deletedSessionIds.has(y.sessionId))continue;if(y.name==="session.deleted"){const j=tf(n,y);if(n=j.state,!j.didApply)continue;r=!0,i.add(y.sessionId),l.push(y),f.set(y.sessionId,y.directory),o.delete(y.sessionId),this.restoringTranscriptById.delete(y.sessionId);continue}if(u.get(v)?.has(y.sessionId))continue;const C=!n.bySession.has(y.sessionId),w=(n.lastSequence.get(y.sessionId)??-1)>=0,I=y.name==="extension.custom.dismiss"?n.bySession.get(y.sessionId)?.extensionSurfaces?.get(y.payload.surfaceId):void 0,E=tf(n,y);if(n=E.state,!E.didApply)continue;if(l.push(y),I&&y.name==="extension.custom.dismiss"&&d.push({sessionId:y.sessionId,reason:y.payload.reason,surface:I}),C&&w&&o.add(y.sessionId),y.name==="session.snapshot"&&o.add(y.sessionId),r=!0,i.add(y.sessionId),y.name==="extension.catalog"){const j=a.get(y.directory)??{providers:!1,resources:!1,commands:!1};a.set(y.directory,{providers:j.providers||y.payload.providers===!0,resources:j.resources||y.payload.resources===!0,commands:j.commands||y.payload.commands===!0})}this.notePromptProgress(y);const T=y.name==="session.error"||y.name==="session.interrupted"||y.name==="session.lifecycle"&&y.payload.state!=="busy"&&y.payload.state!=="retry",A=y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.snapshot";if(T||A){const j=n.bySession.get(y.sessionId);if(j?.awaitingPromptEcho!==void 0&&(T||!uw(j))){const k=new Map(n.bySession);k.set(y.sessionId,{...j,awaitingPromptEcho:void 0}),n={...n,bySession:k}}}if(this.pendingPromptById.has(y.sessionId)&&y.name==="session.snapshot"&&!y.payload.snapshot.isStreaming){n=this.retainPendingPrompt(n,y.sessionId),this.promoteSession(y.sessionId,"active");continue}this.observeActivity(y),this.lastAccessClock+=1,this.lastAccessById.set(y.sessionId,this.lastAccessClock),s=!0}if(!r){h&&(this.state={...this.state,reducer:n,hydratedSessionIds:new Set(this.hydratedSessionIds)},this.emit([At,yt,...[...h].map(y=>`session:${y}`)]),this.queueSyncRecovery({directories:"all-known",residents:h}));return}this.state={...this.state,reducer:n,...h?{hydratedSessionIds:new Set(this.hydratedSessionIds)}:{}};for(const[y,v]of f)this.commitDeletion(y,v);for(const y of l)f2(y)&&Number.isSafeInteger(y.sequence)&&(this.lifecycleSequenceById.get(y.sessionId)??-1)<y.sequence&&this.lifecycleSequenceById.set(y.sessionId,y.sequence);const m=this.applyCatalogFromEvents(l,n),g=m!==this.state.catalog;for(const y of l){if(y.name==="session.archive"){const w=m.byId.get(y.sessionId);w&&w.archived!==y.payload.archived&&this.scheduleRemoteSendRefresh(w.directory||y.directory);continue}if(!(y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.bash"))continue;const C=m.byId.get(y.sessionId);C?.archived&&this.scheduleRemoteSendRefresh(C.directory||y.directory)}const x=[];if(g){const y=this.state.catalog,v=new Map;for(const C of l){if(C.name!=="session.input")continue;const w=v.get(C.sessionId);w?w.push(C):v.set(C.sessionId,[C])}for(const[C,w]of v){const I=m.byId.get(C);if(!I)continue;const E=y.byId.get(C)?.pendingInput,T=I.pendingInput;let A=E;const j=[];for(const k of w){if(k.name!=="session.input")continue;const _=k.payload.pending,M=_===null?null:Kd(_)?_:void 0;if(M===void 0)continue;const L=k.payload.serverNow,O=typeof L=="number"&&Number.isFinite(L)&&L>0?L:void 0,N=A!=null,D=M!=null;!N&&D&&M?j.push({type:"opened",sessionId:C,directory:I.directory??k.directory,pending:M,...O!==void 0?{serverNow:O}:{}}):N&&!D&&j.push({type:"cleared",sessionId:C,directory:I.directory??k.directory,pending:null}),A=M}if(Ea(A,T))for(const k of j)x.push(k);else{const k=E!=null,_=T!=null;!k&&_&&T?x.push({type:"opened",sessionId:C,directory:I.directory,pending:T}):k&&!_&&x.push({type:"cleared",sessionId:C,directory:I.directory,pending:null})}}this.state={...this.state,catalog:m}}const b=new Map;for(const y of l)y.name==="session.input"&&b.set(y.sessionId,y);for(const[y,v]of b){if(v.payload.pending!==null||m.byId.has(y)||this.pendingInputSequenceById.get(y)!==v.sequence)continue;const C=this.openedPendingInputById.get(y);C!==void 0&&x.push({type:"cleared",sessionId:y,directory:C,pending:null})}const S=[];(g||h)&&S.push(yt),l.some(y=>y.name==="extension.dialog"||y.name==="extension.dialog.dismiss"||y.name==="session.snapshot")&&S.push(Bc);for(const y of i)S.push(`session:${y}`);S.length>0&&this.emit(S),this.emitPendingInputTransitions(x);for(const y of d)for(const v of[...this.extensionSurfaceDismissListeners])try{v(y)}catch(C){console.error("[pi-session-store] surface dismiss listener failed",C)}l.some(y=>y.name==="session.input")&&this.requestNeedingSessionMetadataBackfill(l.filter(y=>y.name==="session.input").map(y=>y.sessionId)),s&&this.scheduleIdleEviction();for(const y of o)this.restoreTranscript(y);h&&this.queueSyncRecovery({directories:"all-known",residents:h});for(const[y,v]of a)v.providers&&this.requestProviderCatalogRefresh(y),v.commands&&xl(y),v.resources&&(id(),de(y)===de(this.state.directory??"")&&Hr.getState().loadSkills())}applyCatalogFromEvents(t,n){let r=this.state.catalog;for(const s of t){if(this.deletedSessionIds.has(s.sessionId))continue;const o=n.bySession.get(s.sessionId),i=o?.lifecycle,a=mw(s);if(a!==void 0&&!r.byId.has(s.sessionId)&&(r=Cs(r,s.sessionId,s.directory,a)),i!==void 0&&(this.hydratedSessionIds.has(s.sessionId)||f2(s))&&(r=Xs(r,s.sessionId,Vc(i),o?.retry)),s.name==="session.input"&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=aa(r,s.sessionId,s.directory,s.payload.pending,s.sequence)),s.name==="session.snapshot"){const l=s.payload.snapshot.inputState;l&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=aa(r,s.sessionId,s.directory,l.pending,s.sequence))}if(s.name==="session.updated"){const l=typeof s.payload.title=="string"?s.payload.title.trim():"";if(l){r.byId.has(s.sessionId)||(r=Cs(r,s.sessionId,s.directory,a??"idle"));const d=r.byId.get(s.sessionId);r=Fc(r,s.sessionId,l,d?.updatedAt??Date.now())}else{const d=r.byId.get(s.sessionId);if(d){const f=zh(d.preview??"");r=Fc(r,s.sessionId,f,d.updatedAt)}}}if(s.name==="assistant.message.start"&&s.payload.role==="user"){r=n2(r,s.sessionId,Date.now(),{directory:s.directory,lifecycle:"busy"});const l=r.byId.get(s.sessionId),d=zh(s.payload.text??"");d&&l&&l.title.trim().length===0&&(r=Fc(r,s.sessionId,d,l.updatedAt))}}return r}scheduleIdleEviction(){this.evictionScheduled||this.state.reducer.bySession.size<=wf||(this.evictionScheduled=!0,queueMicrotask(()=>{this.evictionScheduled=!1,this.evictIdleTranscripts()}))}evictIdleTranscripts(){const t=this.state.reducer.bySession;if(t.size<=wf)return;const n=new Set;this.state.selectedSessionId&&n.add(this.state.selectedSessionId);for(const[h,m]of t)(m.lifecycle==="busy"||m.lifecycle==="retry")&&n.add(h),m.extensionDialogs.length>0&&n.add(h),m.extensionSurfaces&&m.extensionSurfaces.size>0&&n.add(h),this.state.catalog.byId.get(h)?.pendingInput!=null&&n.add(h);for(const h of this.pendingPromptById)n.add(h);const r=[];for(const h of t.keys()){if(n.has(h))continue;const m=this.lastAccessById.get(h)??0;r.push([h,m])}r.sort((h,m)=>h[1]-m[1]);let s=null,o=null,i=null,a=null;const l=[];let d=0;for(const[h]of r){if(t.size-d<=wf)break;s||(s=new Map(t)),o||(o=new Set(this.hydratedSessionIds)),i||(i=new Map(this.lastAccessById)),s.delete(h),o.delete(h),i.delete(h),this.activityPhaseById.delete(h),a=a??this.state.catalog,a=xf(a,h,!1),d+=1,l.push(h)}if(!s||!o||!i)return;this.lastAccessById=i;const f=!!a&&a!==this.state.catalog;this.state={...this.state,reducer:{bySession:s,lastSequence:new Map(this.state.reducer.lastSequence)},hydratedSessionIds:o,...a?{catalog:a}:{}};const u=[At];for(const h of l)u.push(`session:${h}`);f&&u.push(yt),this.emit(u)}async upsertAndHydrate(t){const n=this.runtimeGeneration,r=s2(this.state.catalog,this.recordFromPiSession(t.session)),s=r!==this.state.catalog;this.state={...this.state,sessions:[{session:t.session,updatedAt:t.session.updatedAt},...this.state.sessions.filter(i=>i.session.id!==t.session.id)],selectedSessionId:t.session.id,catalog:r};const o=[At];s&&o.push(yt),this.emit(o),await this.hydrate(t.session.id,n,t)}directory(){if(!this.state.directory)throw new at("DAEMON_UNAVAILABLE");return this.state.directory}streamCursor(){let t=-1;for(const n of this.state.reducer.lastSequence.values())n>t&&(t=n);return t>=0?t:void 0}scope(t){return{directory:t||this.directory(),runtimeKey:Y()}}reconnectAfterTransportSwitch(){const t=this.state.selectedSessionId;!this.stream||!t||!this.state.directory||this.reconnect(t,this.runtimeGeneration,Y())}resetForRuntime(){this.catalogCache.flush(),this.resetLiveRuntimeState(),this.state=$c(this.readCachedCatalog(Y())),vf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()}emit(t){if(t.length===0)return;t.includes(yt)&&this.catalogCache.schedule(Y(),this.state.catalog);const n=new Set;for(const s of t){const o=this.listenersByTopic.get(s);if(o)for(const i of o)n.has(i)||(n.add(i),i())}const r=this.listenersByTopic.get(a2);if(r)for(const s of r)n.has(s)||(n.add(s),s())}readCachedCatalog(t){try{return this.catalogCache.read(t)??fp()}catch{return fp()}}emitBroadcast(){const t=new Set;for(const n of this.listenersByTopic.values())for(const r of n)t.has(r)||(t.add(r),r())}emitChrome(){this.emit([At])}}const Eo=new Map,h2=e=>{Eo.set(e,(Eo.get(e)??0)+1)},wE=e=>(Eo.get(e)??0)>0,SE=e=>{const t=Eo.get(e)??0;return t<=0?!1:(t===1?Eo.delete(e):Eo.set(e,t-1),!0)};function gw(){return pd(qe().getState().catalog,{archived:!1})}function Gm(){const e=qe().getState().catalog;return[...pd(e,{archived:!1}),...pd(e,{archived:!0})]}function CE(e){const t=qe().getState();return t.catalog.byId.get(e)?.directory??t.sessions.find(n=>n.session.id===e)?.session.directory??t.directory}function kE(){return lE(qe().getState().catalog).map(e=>({id:e.id,title:e.title.trim()||null,directory:e.directory}))}function UX(e,t){return[]}function qX(e,t){return[]}const Zm=2048,p2=new WeakMap,ME=e=>e==="running"||e==="pending",yw=e=>{if(e==null)return 0;if(typeof e=="string")return e.length;if(typeof e=="number"||typeof e=="boolean")return String(e).length;try{return JSON.stringify(e)?.length??0}catch{return Zm+1}},IE=e=>{if(!e)return e;const t=e.patch??e.diff??e.filediff?.patch??e.filediff?.diff;if(yw(t)<=Zm)return e;const n={...e};if(delete n.patch,delete n.diff,n.filediff&&typeof n.filediff=="object"){const r={...n.filediff};delete r.patch,delete r.diff,n.filediff=r}return n.deferredBody=!0,n},Ym=(e,t)=>{if(e.type==="thinking")return{id:e.id,type:"reasoning",text:e.text,streaming:e.streaming};if(e.type==="attachment")return{id:e.id,type:"file",filename:e.attachment?.name,mime:e.attachment?.mime,size:e.attachment?.size};if(e.type==="file")return{id:e.id,type:"file",filename:e.file?.filename,mime:e.file?.mime,url:e.file?.url};if(e.type==="tool"){const n=ME(e.tool?.state),r=t?.full===!0||n,s=!r&&yw(e.tool?.output)>Zm,o=r?e.tool?.metadata:IE(e.tool?.metadata),i=!!(!r&&(s||o?.deferredBody)),a=e.tool?.render;let l;return a&&(i&&a.resultExpanded!==void 0?l={...a.call!==void 0?{call:a.call}:{},...a.result!==void 0?{result:a.result}:{}}:l=a),{id:e.id,type:"tool",tool:e.tool?.name,callID:e.tool?.toolCallId,state:{status:e.tool?.state==="running"||e.tool?.state==="pending"?"running":e.tool?.state==="error"?"error":e.tool?.state==="cancelled"?"cancelled":"completed",input:e.tool?.input,...s?{}:{output:e.tool?.output},...l!==void 0?{render:l}:{},error:e.tool?.error,time:{start:e.tool?.startedAt,end:e.tool?.endedAt},metadata:o,...i?{deferredBody:!0}:{}}}}return{id:e.id,type:"text",text:e.text}},EE=e=>({id:e.id,directory:e.directory,parentID:e.parentId??null,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.timeArchived??e.updatedAt}:{}}}),_E=(e,t)=>{const n=[];if(e.parts.length>0){const i=e.parts.some(l=>l.type==="thinking"),a=e.parts.some(l=>l.type==="text");!i&&e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),n.push(...e.parts.map(l=>Ym(l))),!a&&e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text})}else e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text});const s=e.role==="assistant"&&!e.streaming?e.error?"error":"stop":void 0;return{info:{id:e.id,sessionID:t,role:e.role,...e.role==="extension"?{customType:e.customType,data:e.data,details:e.details,...e.render?{render:e.render}:{},...e.text?{text:e.text}:{}}:{},...e.parentId?{parentID:e.parentId}:{},time:{created:e.createdAt,...e.streaming?{}:typeof e.durationMs=="number"&&e.durationMs>0?{completed:e.createdAt+e.durationMs}:{completed:e.createdAt}},...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.error?{error:{name:e.error.code,message:e.error.message}}:{},...e.model?{model:{providerID:e.model.providerId,modelID:e.model.modelId},providerID:e.model.providerId,modelID:e.model.modelId}:{},...e.thinkingLevel?{variant:e.thinkingLevel}:{},...e.role==="assistant"&&e.usage?{usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,totalTokens:e.usage.totalTokens,cost:e.usage.cost},cost:e.usage.cost.total}:{},...s?{finish:s}:{}},parts:n}},jE=e=>e?e.messages.map(t=>{const n=p2.get(t);if(n&&n.info.sessionID===e.sessionId)return n;const r=_E(t,e.sessionId);return p2.set(t,r),r}):[],TE=["chat","git","diff","terminal","files","diagram"],AE=["settings","skills","providers","git-identities"],Dr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function vw(e){const t=NE();return{sessionId:LE(t),tab:RE(t),settingsPath:PE(t),diffFile:DE(t)}}function NE(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function LE(e){const t=e.get(Dr.SESSION)??e.get("s");if(t&&t.trim().length>0)return t.trim();if(typeof window<"u"){const n=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i);if(n?.[1])return decodeURIComponent(n[1].trim())}return null}function RE(e){const t=e.get(Dr.TAB);if(!t)return null;const n=t.toLowerCase().trim();return TE.includes(n)?n:null}function PE(e){const t=e.get(Dr.SETTINGS);if(!t)return null;const n=t.toLowerCase().trim();return n.length===0?null:n==="pichamber"||n==="general"||n==="preferences"?"home":(AE.includes(n),n)}function DE(e){const t=e.get(Dr.FILE);if(!t||t.trim().length===0)return null;try{return decodeURIComponent(t.trim())}catch{return t.trim()}}function WX(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);return/^\/(?:session|s)\/[^/?#]+/i.test(window.location.pathname)||e.has(Dr.SESSION)||e.has("s")||e.has(Dr.TAB)||e.has(Dr.SETTINGS)||e.has(Dr.FILE)}catch{return!1}}const Xm=(e,t)=>e?.open===!0&&t===null,KX=e=>e.currentSessionId??(Xm(e.draft,e.currentSessionId)?null:e.piSelectedSessionId),OE=()=>{let e=!1,t,n;return(r,s,o=Object.is)=>{if(e&&Object.is(t,r))return n;const i=s(r);return e&&(typeof o=="function"?o:Object.is)(n,i)?(t=r,n):(e=!0,t=r,n=i,i)}},xw="oc.lastSession.v1",HE=8,Cf=()=>({version:1,runtimes:{}}),Jm=e=>{try{const t=e.getItem(xw);if(!t)return Cf();const n=JSON.parse(t);if(n.version!==1||!n.runtimes||typeof n.runtimes!="object")return Cf();const r={};for(const[s,o]of Object.entries(n.runtimes))!s||!o||typeof o.sessionId!="string"||o.sessionId.length===0||(r[s]={sessionId:o.sessionId,directory:typeof o.directory=="string"&&o.directory.length>0?o.directory:null,updatedAt:typeof o.updatedAt=="number"?o.updatedAt:0});return{version:1,runtimes:r}}catch{return Cf()}},bw=(e,t)=>{const n=Object.entries(t.runtimes).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,HE);try{e.setItem(xw,JSON.stringify({...t,runtimes:Object.fromEntries(n)}))}catch{}};function FE(e,t,n=Gt()){if(!t.sessionId)return;const r=Jm(n),s=Object.values(r.runtimes).reduce((o,i)=>Math.max(o,i.updatedAt),0);r.runtimes[e]={...t,updatedAt:Math.max(Date.now(),s+1)},bw(n,r)}function hp(e,t=Gt()){if(!e)return null;const n=Jm(t).runtimes[e];return n?{sessionId:n.sessionId,directory:n.directory}:null}function BE(e,t=Gt()){if(!e)return;const n=Jm(t);n.runtimes[e]&&(delete n.runtimes[e],bw(t,n))}const VE=120,$E=600,ww=typeof window<"u"&&typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"?window.__PICHAMBER_HARDWARE_KEYBOARD__:null;let md=ww===!0,au=ww!==null,ca=null,kf=!1;const pp=new Set;md&&typeof document<"u"&&document.documentElement.classList.add("oc-hardware-keyboard");const cu=()=>{ca!==null&&(window.clearTimeout(ca),ca=null)},lu=e=>{if(md!==e){md=e,typeof document<"u"&&document.documentElement.classList.toggle("oc-hardware-keyboard",e);for(const t of pp)t()}},zE=()=>{if(typeof window>"u")return()=>{};const e=n=>{au=!0,cu(),lu(n)};if(typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"&&e(window.__PICHAMBER_HARDWARE_KEYBOARD__),kf)return()=>{};kf=!0;const t=n=>{const r=n.detail;e(r?.attached===!0)};return window.addEventListener("oc:hardware-keyboard",t),()=>{window.removeEventListener("oc:hardware-keyboard",t),kf=!1}},m2=e=>{au||!Number.isFinite(e)||(cu(),lu(e>0&&e<VE))},UE=()=>{au||typeof window>"u"||typeof document>"u"||document.documentElement.classList.contains("oc-keyboard-open")||(cu(),ca=window.setTimeout(()=>{ca=null,lu(!0)},$E))},qE=()=>{cu(),!au&&lu(!1)},WE=()=>md,KE=e=>(pp.add(e),()=>{pp.delete(e)});function GE(){return p.useSyncExternalStore(KE,WE,()=>!1)}const zo=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",GX=()=>{p.useEffect(()=>{if(!zo())return;let e=!1;const t=[],n=document.documentElement;n.classList.add("oc-capacitor-app"),window.Capacitor?.getPlatform?.()==="android"&&n.classList.add("oc-platform-android"),Sw(),t.push(zE());const s=o=>{n.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(o))}px`)};return mt(()=>import("./vendor-capacitor-status-bar-CWt0OF5t.js"),__vite__mapDeps([4,5,1,6])).then(async({StatusBar:o,Style:i})=>{if(e)return;const a=window.Capacitor?.getPlatform?.(),l=async()=>{if(a==="android"){const h=document.documentElement.classList.contains("dark"),m=(h?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(h?"#171515":"#fffdf4");await o.setOverlaysWebView({overlay:!1}).catch(()=>{}),await o.setBackgroundColor({color:m}).catch(()=>{}),await o.setStyle({style:h?i.Dark:i.Light}).catch(()=>{}),await o.show().catch(()=>{});return}await o.setStyle({style:i.Default}).catch(()=>{}),await o.setOverlaysWebView({overlay:!0}).catch(()=>{}),await o.show().catch(()=>{})};await l();const d=window.setTimeout(()=>{l()},400);t.push(()=>window.clearTimeout(d));const{App:f}=await mt(async()=>{const{App:h}=await import("./vendor-capacitor-app-NbQ-WiPS.js");return{App:h}},__vite__mapDeps([7,8,5,1,6])),u=await f.addListener("appStateChange",({isActive:h})=>{h&&l()});if(e){u.remove();return}t.push(()=>{u.remove()})}).catch(()=>{}),mt(()=>import("./vendor-capacitor-keyboard-CgrHt8iN.js"),__vite__mapDeps([9,5,1,6])).then(async({Keyboard:o})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const j=await o.addListener("keyboardWillShow",O=>{m2(O.keyboardHeight),n.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),k=await o.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),_=await o.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),n.classList.remove("oc-keyboard-open")}),M=await o.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),L=()=>{j.remove(),k.remove(),_.remove(),M.remove()};if(e){L();return}t.push(L);return}await o.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const a=250,l=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let f=null,u=null,h=0,m=!1,g=0,x=!1;const b=(j,k)=>{n.style.setProperty(j,`${Math.max(0,Math.round(k))}px`)},S=()=>{f!==null&&(window.clearTimeout(f),f=null)},y=(j,k)=>{window.dispatchEvent(new CustomEvent(j,{detail:k}))},v=()=>{const j=[],k=document.querySelector(".oc-mobile-composer");k&&j.push({el:k,factor:1});const _=document.querySelector(".oc-draft-center");return _&&j.push({el:_,factor:.5}),j},C=()=>{for(const{el:j}of v())j.style.transition="",j.style.transform=""},w=await o.addListener("keyboardWillShow",j=>{if(S(),m2(j.keyboardHeight),x=!0,h=j.keyboardHeight,!m){const _=document.querySelector(".oc-mobile-app-shell");g=_&&parseFloat(getComputedStyle(_).paddingBottom)||0}const k=Math.max(0,h-g);n.classList.remove("oc-kb-hide"),u!==null&&(window.clearTimeout(u),u=null),n.classList.add("oc-keyboard-open","oc-kb-animating","oc-kb-caret-hold"),s(h);for(const{el:_,factor:M}of v())_.style.transition=`transform ${a}ms ${d}`,_.style.transform=`translateY(${-k*M}px)`;b("--oc-kb-scroll-inset",k),y("oc:keyboard-settled",{open:!0}),y("oc:keyboard-anim",{phase:"show",slide:k,durationMs:a,easing:d}),f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",h),m=!0,C(),y("oc:keyboard-settled",{open:!0}),u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-caret-hold")},250)},a+20)}),I=()=>{if(!x)return;x=!1,S(),y("oc:keyboard-intent",{open:!1}),u!==null&&(window.clearTimeout(u),u=null),n.classList.remove("oc-kb-caret-hold");const j=Math.max(0,h-g);if(n.classList.remove("oc-keyboard-open"),s(0),b("--oc-kb-scroll-inset",0),m){n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",0),m=!1;for(const{el:k,factor:_}of v())k.style.transition="none",k.style.transform=`translateY(${-j*_}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}y("oc:keyboard-anim",{phase:"hide",slide:j,durationMs:l,easing:d}),n.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:k}of v())k.style.transition=`transform ${l}ms ${d}`,k.style.transform="translateY(0px)";f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating","oc-kb-hide"),C(),y("oc:keyboard-settled",{open:!1})},l+20)},E=await o.addListener("keyboardWillHide",I),T=j=>j instanceof HTMLElement&&(j.tagName==="TEXTAREA"||j.tagName==="INPUT"||j.isContentEditable),A=j=>{x&&T(j.target)&&(T(j.relatedTarget)||window.setTimeout(()=>{x&&(T(document.activeElement)||I())},0))};if(document.addEventListener("focusout",A,!0),e){S(),document.removeEventListener("focusout",A,!0),w.remove(),E.remove();return}t.push(S,()=>{u!==null&&(window.clearTimeout(u),u=null)},()=>document.removeEventListener("focusout",A,!0),()=>{w.remove()},()=>{E.remove()})}).catch(()=>{}),()=>{e=!0,t.forEach(o=>o()),qE(),n.classList.remove("oc-capacitor-app","oc-keyboard-open","oc-kb-animating","oc-kb-hide","oc-kb-caret-hold","oc-platform-android"),n.style.removeProperty("--oc-keyboard-inset"),n.style.removeProperty("--oc-kb-shift"),n.style.removeProperty("--oc-kb-layout"),n.style.removeProperty("--oc-kb-scroll-inset")}},[])},ZX=e=>{const t=p.useRef(!1);p.useEffect(()=>{if(!zo())return;let n=!1;const r=[],s=()=>{t.current&&(t.current=!1,e())},o=()=>{if(document.visibilityState==="hidden"){t.current=!0,Rr("app-lifecycle",{code:"hidden"});return}Rr("app-lifecycle",{code:"visible"}),s()};return document.addEventListener("visibilitychange",o),r.push(()=>document.removeEventListener("visibilitychange",o)),mt(()=>import("./vendor-capacitor-app-NbQ-WiPS.js"),__vite__mapDeps([7,8,5,1,6])).then(async({App:i})=>{if(n)return;const a=await i.addListener("appStateChange",({isActive:d})=>{if(document.documentElement.classList.toggle("oc-native-app-active",d),Rr("app-lifecycle",{code:d?"resume":"pause"}),!d){t.current=!0;return}s()}),l=await i.addListener("resume",()=>{Rr("app-lifecycle",{code:"resume"}),s()});if(n){a.remove(),l.remove();return}r.push(()=>{a.remove()},()=>{l.remove()})}).catch(()=>{}),()=>{n=!0,r.forEach(i=>i())}},[e])},la=[];let Mf=null;const ZE=()=>{for(let e=la.length-1;e>=0;e--)try{if(la[e]())return!0}catch{}return!1},Sw=()=>zo()?(Mf||(Mf=mt(async()=>{const{App:e}=await import("./vendor-capacitor-app-NbQ-WiPS.js");return{App:e}},__vite__mapDeps([7,8,5,1,6])).then(({App:e})=>e.addListener("backButton",()=>{ZE()||e.minimizeApp().catch(()=>{})})).catch(()=>null)),Mf.then(()=>{})):Promise.resolve(),YX=e=>{const t=p.useRef(e);t.current=e,p.useEffect(()=>{if(!zo())return;Sw();const n=()=>t.current();return la.push(n),()=>{const r=la.lastIndexOf(n);r!==-1&&la.splice(r,1)}},[])},Cw=p.createContext(null),Ha=()=>p.useContext(Cw)??qe(),XX=({children:e,directory:t})=>{const n=p.useMemo(()=>qe(),[]),r=lt(o=>o.projects.find(i=>i.id===o.activeProjectId)?.path??null),s=t?.trim()||r;return H.useEffect(()=>{const o=vw(),i=he.getState(),a=Xm(i.newSessionDraft,i.currentSessionId);if(o.sessionId&&!a){const d=n.getState();if(d.selectedSessionId===o.sessionId&&d.connection==="ready")return;n.start({directory:s??void 0,sessionId:o.sessionId});return}if(!s){if(!a&&!zo()){const d=hp(Y());if(d?.sessionId){n.start({sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.connectWithoutProject();return}const l=a?null:n.lastSelectedSessionForDirectory(s);if(l){n.start({directory:s,sessionId:l,sessionDirectoryKnown:!0});return}if(!a&&!zo()){const d=hp(Y());if(d?.sessionId){n.start({directory:s,sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.start({directory:s})},[n,s]),c.jsx(Cw.Provider,{value:n,children:e})},YE=e=>e;function ze(e,t,n="*",r=""){const s=Ha(),o=H.useRef(e);o.current=e;const i=H.useRef(t);i.current=t;const a=H.useRef(null),l=`${n}\0${r}`;a.current?.key!==l&&(a.current={key:l,select:OE()});const d=H.useCallback(()=>{const u=o.current??YE,h=typeof i.current=="function"?i.current:Object.is;return a.current.select(s.getState(),u,h)},[s]),f=H.useMemo(()=>u=>s.subscribe(u,n),[s,n]);return H.useSyncExternalStore(f,d,d)}const kw={type:"idle"},XE={type:"busy"},JE={type:"retry"},g2=new WeakMap,QE=[],e_=[],y2={loading:!1,complete:!0,status:"ready",cursor:void 0,error:null,errorCode:null},v2=[],x2=new WeakMap,Hs="catalog",An="chrome",Kt=e=>`session:${e}`,t_=(e,t)=>{if(e==="busy")return XE;if(e!=="retry")return kw;if(!t)return JE;const n=g2.get(t);if(n)return n;const r={type:"retry",...t};return g2.set(t,r),r};function n_(e){const t=e?.archived??!1,n=e?.directory;return ze(r=>pd(r.catalog,{archived:t,directory:n}),cE,Hs)}function JX(e,t){return du(e)}function QX(e){const t=ze(n=>n.catalog.byId,void 0,Hs);if(e)return t.get(e)?.pendingInput}function Mw(){return ze(e=>Wm(e.catalog),iE,Hs)}function eJ(e=!0){const t=ze(n=>{if(!e)return"";const r=[],s=[];for(const o of n.catalog.byId.values())(o.lifecycle==="busy"||o.lifecycle==="retry")&&r.push(o.id),o.pendingInput!=null&&s.push(o.id);return r.length===0&&s.length===0?"":JSON.stringify([r.sort(),s.sort()])},void 0,Hs);return H.useMemo(()=>{if(!t)return{working:b2,needsInput:b2};const[n,r]=JSON.parse(t);return{working:new Set(n),needsInput:new Set(r)}},[t])}const b2=new Set;function If(e,t){qe().select(t,e||void 0)}function Qm(e,t){const n=fu(e);return H.useMemo(()=>n.map(r=>r.info),[n])}function r_(e,t,n){const r=ze(a=>e?a.reducer.bySession.get(e)??null:null,void 0,e?Kt(e):"*"),s=ze(a=>e?null:a.reducer.bySession,void 0,e?Kt(e):"*"),o=H.useMemo(()=>{if(e||!t||n!==void 0||!s)return null;for(const a of s.values())if(a.messages.has(t))return a;return null},[s,t,e,n]),i=r??o;return H.useMemo(()=>{if(!t||!i)return v2;const a=i.messages.get(t);if(!a)return v2;const l=i.partOrder.get(t)??[];if(l.length>0){const f=[];for(const u of l){const h=i.parts.get(u);if(!h)continue;const m=x2.get(h);if(m){f.push(m);continue}const g=Ym({id:h.id,type:h.type,text:h.text,streaming:h.streaming,...h.tool?{tool:h.tool}:{},...h.attachment?{attachment:h.attachment}:{}},{full:!0});x2.set(h,g),f.push(g)}return f}const d=[];return a.thinking&&d.push({id:`${a.id}:thinking`,type:"reasoning",text:a.thinking,streaming:!1}),a.text&&d.push({id:`${a.id}:text`,type:"text",text:a.text}),d},[t,i])}function du(e,t){const n=ze(s=>s.catalog.byId,void 0,Hs);if(!e)return kw;const r=n.get(e);return t_(r?.lifecycle,r?.retry)}function Iw(){return ze(e=>e.connection,void 0,An)}function s_(e){return ze(t=>e?t.reducer.bySession.get(e)?.compaction??null:null,void 0,e?Kt(e):"*")}function uu(e){return ze(t=>e?t.reducer.bySession.get(e)?.runningCommand??null:null,void 0,e?Kt(e):"*")}const w2=[];function Ew(e){return ze(t=>e?t.reducer.bySession.get(e)?.extensionNotices??w2:w2,(t,n)=>t.length===n.length&&t.every((r,s)=>r.id===n[s]?.id),e?Kt(e):"*")}const S2=[];function o_(e){return ze(t=>e?t.reducer.bySession.get(e)?.bashExecutions??S2:S2,void 0,e?Kt(e):"*")}function i_(e){return ze(t=>!!(e&&t.reducer.bySession.get(e)?.bashExecutions?.length),void 0,e?Kt(e):"*")}function _w(){const e=ze(t=>t.directory,void 0,An);return n_({archived:!1,directory:e||null})}function tJ(e,t){const n=ze(s=>s.catalog.byId,void 0,Hs),r=e?n.get(e)??null:null;return r?Ls(r):void 0}function a_(e){const t=ze(s=>s.catalog.byId,void 0,Hs),n=ze(s=>s.directory,void 0,An);return(e?t.get(e)?.directory:void 0)??n??void 0}function c_(){return ze(e=>e.directory??"",void 0,An)}function l_(e,t){const n=ze(a=>a.hydratedSessionIds,void 0,An),r=ze(a=>a.selectedSessionId,void 0,An),s=ze(a=>a.connection,void 0,An),o=ze(a=>a.error,void 0,An),i=ze(a=>a.sessionLoadErrorById,void 0,An);return H.useMemo(()=>{if(!e||n.has(e))return y2;const l=i.get(e)??(s==="error"&&o?o:null);if(l)return{loading:!1,complete:!1,status:"error",cursor:void 0,error:l.message??"Session load failed",errorCode:l.code};const d=r===e||s==="loading";return{loading:d,complete:!1,status:d?"loading":"ready",cursor:void 0,error:null,errorCode:null}},[s,o,n,r,e,i])}function jw(e,t){const n=ze(r=>r.hydratedSessionIds,void 0,An);return!e||n.has(e)}function d_(e){const t=ze(n=>e?n.reducer.bySession.get(e)??null:null,(n,r)=>Object.is(n,r)?!0:!n||!r?!1:DI(n,r),e?Kt(e):"*");return H.useMemo(()=>{if(!t)return QE;const n=[],r=new Set,s=[];for(const o of t.messages.values())o.role!=="user"||r.has(o.id)||(r.add(o.id),s.push(o));s.sort((o,i)=>o.createdAt-i.createdAt);for(const o of s){const i=t.partOrder.get(o.id)??[],a=i.length>0?i.map(l=>t.parts.get(l)).filter(l=>l?.type==="text").map(l=>l?.text??"").join(""):o.text??"";a&&n.push(a)}return n},[t])}function u_(e){return ze(t=>Ma(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function f_(e){return ze(t=>uw(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function fu(e,t,n){const r=n?.suspendPartUpdates!==!1,s=null,o=ze(a=>e?a.reducer.bySession.get(e)??null:null,(a,l)=>{if(Object.is(a,l)||a&&l&&RI(a,l))return!0;if(!a||!l)return!1;const d=Ma(l);return d?dp(a,l,d):!1},e?Kt(e):"*"),i=H.useRef(null);return H.useMemo(()=>{if(!o)return i.current=null,e_;const a=i.current,l=Ma(o);if(l&&a&&a.sessionId===e&&dp(a.session,o,l))return i.current={sessionId:e,session:o,projection:a.projection,records:a.records},a.records;const d=yb(o,a&&a.sessionId===e?{session:a.session,projection:a.projection}:null),f=jE(d),u=a?.records,h=u&&u.length===f.length&&u.every((m,g)=>m===f[g])?u:f;return i.current={sessionId:e,session:o,projection:d,records:h},h},[s,o,e,r])}function h_(e,t,n){const r=Ha(),s=n&&e?Kt(e):An,o=H.useMemo(()=>l=>r.subscribe(l,s),[r,s]),i=H.useCallback(()=>!n||!e||!t?null:r.getState().reducer.bySession.get(e)?.parts.get(t)??null,[n,t,e,r]),a=H.useSyncExternalStore(o,i,i);return H.useMemo(()=>!n||!a?null:Ym({id:a.id,type:a.type,text:a.text,streaming:a.streaming,...a.tool?{tool:a.tool}:{},...a.attachment?{attachment:a.attachment}:{}},{full:!0}),[n,a])}function p_(e,t){return ze(n=>e?n.reducer.bySession.get(e)?.messages.size??0:0,void 0,e?Kt(e):"*")}function m_(e){const t=Ha(),n=ze(o=>!!(e&&o.reducer.bySession.get(e)?.hasMoreBefore),void 0,e?Kt(e):"*"),r=ze(o=>e?o.reducer.bySession.get(e)?.beforeCursor:void 0,void 0,e?Kt(e):"*"),s=H.useCallback(()=>e?t.loadOlderMessages(e):Promise.resolve(!1),[e,t]);return{hasMoreBefore:n,beforeCursor:r,loadOlder:s}}function g_(e,t,n=!0){const r=Ha();!n||!e||r.ensureHydrated(e)}const Bt=()=>qe();async function y_(e,t,n,r){const s=await Bt().create(e,{...t?{directory:t}:{},...r?.model?{model:r.model}:{},...r?.thinking?{thinking:r.thinking}:{},...r?.select===!1?{select:!1}:{}}),o=Bt().getState().sessions.find(i=>i.session.id===s||i.session.id===Bt().getState().selectedSessionId);return o?EE(o.session):null}async function v_(e,t){return await Bt().remove(e),!0}async function x_(e,t){const n=[],r=[];for(const s of e)try{await Bt().remove(s),n.push(s)}catch{r.push(s)}return{deletedIds:n,failedIds:r}}async function b_(e){try{return await Bt().archive(e,!0),!0}catch{return!1}}const Tw=async(e,t)=>{const n=await Promise.allSettled(e.map(o=>Bt().archive(o,t))),r=[],s=[];return n.forEach((o,i)=>(o.status==="fulfilled"?r:s).push(e[i])),{done:r,failed:s}};async function w_(e,t){const{done:n,failed:r}=await Tw(e,!0);return{archivedIds:n,failedIds:r}}async function S_(e){try{return await Bt().archive(e,!1),!0}catch{return!1}}async function C_(e,t){const{done:n,failed:r}=await Tw(e,!1);return{restoredIds:n,failedIds:r}}async function k_(e,t){await Bt().rename(e,t)}async function M_(e){return null}async function I_(e){return null}async function E_(e,t){const r=(await Bt().navigate(e,t))?.navigation?.editorText;if(typeof r=="string"&&r.length>0)try{Ye.getState().setPendingRevertText(r)}catch{}}async function __(e,t){if(!Um(e))throw new Error("No reverted conversation is available to restore.");await Bt().navigate(e,t)}async function j_(e){const t=Um(e)?.previousLeafId;if(!t)throw new Error("No reverted conversation is available to restore.");await Bt().navigate(e,t)}async function T_(e,t){await Bt().fork(e,t)}async function A_(){const e=Bt().getState();if(e.connection!=="ready")throw e.error??new Error("Pi runtime is unavailable")}async function N_(e,t){await Bt().compact(e,t)}async function Aw(e){await Bt().abortBash(e)}function e1(e){e&&Bt().abort(e)}const L_=e=>{if(typeof e!="string")return"attachment";const n=e.replace(/[\\/]/g,"_").replace(/\.\.+/g,"_").replace(/[\x00-\x1f\x7f]/g,"").replace(/^\.+/,"").trim();return n.length===0?"attachment":n.length>200?n.slice(0,200):n};function C2(e){const t=qe().getState(),n=t.reducer.bySession.get(e),r=t.sessions.find(s=>s.session.id===e)?.session;return{model:n?.model??r?.model,thinking:n?.thinking??r?.thinking}}async function mp(e){const t=e.delivery==="steer"||e.delivery==="followUp"?e.delivery:"prompt",n=e.runtimeKey??Y(),r=()=>{if(n!==Y())throw new Error("Runtime changed before sending message.")};r();const s=qe();let o=!1;if(e.sessionId&&e.providerID&&e.modelID){const l=C2(e.sessionId).model;(!l||l.providerId!==e.providerID||l.modelId!==e.modelID)&&(await s.setModel(e.sessionId,e.providerID,e.modelID),r(),o=!0)}if(e.sessionId&&Ht(e.variant)){const l=C2(e.sessionId).thinking;(o||l!==e.variant)&&(await s.setThinking(e.sessionId,e.variant),r())}const i=[...e.files??[],...(e.additionalParts??[]).flatMap(l=>l.files??[])].filter(l=>l.uploadState!==void 0||l.url.startsWith("data:")),a=[];try{const l=await Promise.all(i.map(async f=>{const u=f.uploadState;if(u?.status==="preparing"||u?.status==="uploading")throw new Error("Attachments are still uploading.");if(u?.status==="failed")throw new Error("Retry or remove failed attachments.");if(u?.status==="ready"&&u.expiresAt>Date.now())return{id:u.attachmentId};if(typeof f.url=="string"&&f.url.startsWith("data:")){const m=await(await fetch(f.url)).blob();r();const g=await s.uploadFile(m,{filename:L_(f.filename),mime:f.mime});return a.push(g.id),{id:g.id}}throw new Error("Attachment data is unavailable. Remove the attachment and add it again.")}));r();const d=l.length>0?l:void 0;await s.prompt(e.sessionId,e.content,t,d,{...e.knownEmptyTranscript?{knownEmptyTranscript:!0}:{},...e.operationId?{operationId:e.operationId}:{},...e.streamEpoch?{streamEpoch:e.streamEpoch}:{},...e.directory?{directory:e.directory}:{},runtimeKey:n})}catch(l){throw typeof l=="object"&&l!==null&&l.name==="PiSendUnconfirmedError"||await Promise.all((n===Y()?a:[]).map(d=>s.deleteUpload(d).catch(()=>{}))),l}}function R_(e){const t=de(e.session?.directory??e.currentDirectory??null);return{directory:t,source:t?"session":void 0}}function nJ(e){return""}const _l={id:null,open:!1,directoryOverride:null,branchIntent:null,worktreeIntent:null,parentID:null},Nw=(e,t,n)=>!!(e.open&&e.id&&e.id===n&&t===null),Lw=e=>de(e.directory??null),Rw=Gt(),Pw="oc.chatInput.lastDraftTarget",P_=()=>{try{const e=Rw.getItem(Pw);if(!e)return null;const t=JSON.parse(e);return{projectId:typeof t?.projectId=="string"?t.projectId:null,directory:de(typeof t?.directory=="string"?t.directory:null)}}catch{return null}},gp=e=>{try{Rw.setItem(Pw,JSON.stringify(e))}catch{}},D_=e=>{const t=Gm().find(s=>s.id===e),n=t?Lw(t):null;if(n)return de(n);const r=CE(e);return r?de(r):null},gd=new Map,Ef=new Map,or=e=>(e??Y()).trim()||"default",yp=e=>({...e}),Js=(e,t)=>{const n=gd.get(e);gd.set(e,{sessionId:n?.sessionId??null,directory:n?.directory??null,draft:n?.draft?yp(n.draft):{..._l},...t})},O_=e=>{const t=or(),n=gd.get(t),r=hp(t);return{runtime:n?.sessionId===e?de(n.directory):null,persisted:r?.sessionId===e?de(r.directory):null}};let hu=null;const k2=()=>hu,H_=e=>{hu=e},M2=()=>{hu=null},F_=(e,t)=>({session:Gm().find(n=>n.id===e)??null,currentDirectory:e===hu?null:de(t)}),I2=(e,t=null)=>e?R_(F_(e,t))?.directory??null:null,vp=async e=>{await We.getState().activateDirectory(de(e))},da=(e,t)=>!e||!t?!1:e.runtimeKey===t.runtimeKey&&de(e.directory)===de(t.directory)&&e.branch===t.branch;async function B_(e,t){const n=t.getState(),r=e.draftSnapshot??n.newSessionDraft;if(!r?.open)return null;if(r.branchIntent){const g=de(r.branchIntent.directory),x=de(r.directoryOverride);if(r.branchIntent.runtimeKey!==Y()||g!==x)throw new Error("The selected branch no longer matches this draft target.");if(!da(r.branchIntent,e.branchCheckoutReceipt))throw new Error("Confirm the selected branch before creating this session.")}if(r.worktreeIntent){const g=e.worktreeCreationReceipt;if(!g||g.runtimeKey!==r.worktreeIntent.runtimeKey||de(g.projectRoot)!==de(r.worktreeIntent.projectRoot)||de(g.sourceDirectory)!==de(r.worktreeIntent.sourceDirectory)||g.startRef!==r.worktreeIntent.startRef||!de(g.path))throw new Error("Create the selected worktree before creating this session.")}const s=r.permissionAutoAcceptEnabled===!0,o=typeof e.agent=="string"&&e.agent.trim().length>0?e.agent.trim():void 0,i=e.worktreeCreationReceipt?.path??r.directoryOverride??null,a=r.selectedProjectId??null,l=r.title||(e.initialPrompt&&!e.initialPrompt.trimStart().startsWith("/")?zh(e.initialPrompt):void 0),d=await n.createSession(l,i,r.parentID??null,{model:e.providerID&&e.modelID?{providerId:e.providerID,modelId:e.modelID}:void 0,thinking:Ht(e.variant)?e.variant:void 0,select:!1},{draftSnapshot:r,closeDraft:!1});if(!d?.id)throw new Error("Failed to create session");const f=de(d.directory??i??null),u=t.getState().newSessionDraft===r&&t.getState().currentSessionId===null;u&&gp({projectId:a,directory:f});const h=r.syntheticParts;u&&vp(f).catch(g=>{console.warn("Failed to activate directory after creating session:",g)});const m=o;return Lt.getState().saveSessionModelSelection(d.id,e.providerID,e.modelID),m&&(Lt.getState().saveSessionAgentSelection(d.id,m),Lt.getState().saveAgentModelForSession(d.id,m,e.providerID,e.modelID),Lt.getState().saveAgentModelVariantForSession(d.id,m,e.providerID,e.modelID,e.variant)),u&&n.setCurrentSession(d.id,f),s&&mt(async()=>{const{usePermissionStore:g}=await import("./permissionStore-zIpxq9Pq.js");return{usePermissionStore:g}},__vite__mapDeps([10,11,1])).then(({usePermissionStore:g})=>g.getState().setSessionAutoAccept(d.id,!0)).catch(g=>{console.warn("Failed to apply draft permission auto-accept to new session:",g)}),{sessionId:d.id,directory:f,agent:m,syntheticParts:h}}let E2=0;const V_=()=>(E2+=1,`draft-${Date.now()}-${E2}`);async function xp(e){return B_(e,he)}const he=Et()((e,t)=>({currentSessionId:null,currentSessionDirectory:null,newSessionDraft:{..._l},abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,webUICreatedSessions:new Set,sessionAbortFlags:new Map,sendingNewSessionDraftId:null,pendingChangesBarDismissed:new Map,setCurrentSession:(n,r)=>{n&&t().closeNewSessionDraft();const s=or();Ef.set(s,n);const o=nt.getState(),i=I2(n),a=qe().getState().directory??o.currentDirectory??null,l=(r?de(r):null)??i,d=l??a,f=l===null,u=lt.getState(),h=d?dr(u.projects,Zn(u.projects,un.getState()),d):null;e({currentSessionId:n,currentSessionDirectory:n?d??null:null}),H_(f&&n?n:null);const m=f?null:d??null;Js(s,{sessionId:n,directory:m}),n&&FE(s,{sessionId:n,directory:m}),n&&qe().select(n,f?void 0:d);try{d&&o.currentDirectory!==d&&o.setDirectory(d,{showOverlay:!1}),h&&u.activeProjectId!==h.id&&u.setActiveProjectIdOnly(h.id)}catch(g){console.warn("Failed to set Pi directory for session switch:",g)}n&&(nu(n),If(d??"",n))},prepareForRuntimeSwitch:n=>{const r=or(n),s=nt.getState().currentDirectory||null,o=t().currentSessionId;Ef.set(r,t().currentSessionId),Js(r,{sessionId:o,directory:s,draft:yp(t().newSessionDraft)})},restoreForRuntimeSwitch:n=>{const r=or(n),s=gd.get(r),o=s?.sessionId??Ef.get(r)??null,i=s?.draft?yp(s.draft):{..._l},a=s?.directory??null;a&&nt.getState().setDirectory(a,{showOverlay:!1}),e({currentSessionId:o,currentSessionDirectory:o?a:null,newSessionDraft:o?{..._l}:i,abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,sendingNewSessionDraftId:null,sessionAbortFlags:new Map,pendingChangesBarDismissed:new Map}),o?If(a??qe().getState().directory??"",o):If("","")},openNewSessionDraft:n=>{n?.automatic||BE(or());const r=lt.getState(),s=r.projects,o=Zn(s,un.getState()),i=r.getActiveProject(),a=de(nt.getState().currentDirectory??null),l=P_(),d="__home__",f=n?.selectedProjectId===d,u=n?.directoryOverride!==void 0?de(n.directoryOverride):null,h=n?.selectedProjectId?f?{id:d,path:u??""}:s.find(T=>T.id===n.selectedProjectId)??null:null,m=dr(s,o,u),g=i||(r.activeProjectId?s.find(T=>T.id===r.activeProjectId)??null:s[0]??null),x=l?.projectId===d,b=l?.projectId?x?{id:d,path:l.directory??""}:s.find(T=>T.id===l.projectId)??null:null,S=dr(s,o,l?.directory??null),y=dr(s,o,a),v=f||h?h:u!==null?m:a?y:x?b:S??b??g,C=u!==null?u:f?u??de(nt.getState().homeDirectory||Gt().getItem("homeDirectory")||"~")??u:h?de(h.path??null):a||(l?.directory?l.directory:de(v?.path??null)),w=f?d:v?.id??null;gp({projectId:w,directory:C});const I={id:V_(),open:!0,selectedProjectId:w,directoryOverride:C,branchIntent:n?.branchIntent&&n.branchIntent.runtimeKey===Y()&&de(n.branchIntent.directory)===C?n.branchIntent:null,worktreeIntent:n?.worktreeIntent&&n.worktreeIntent.runtimeKey===Y()&&de(n.worktreeIntent.sourceDirectory)===C?n.worktreeIntent:null,permissionAutoAcceptEnabled:n?.permissionAutoAcceptEnabled===!0,preserveDirectoryOverride:n?.preserveDirectoryOverride===!0,parentID:n?.parentID??null,title:n?.title,initialPrompt:n?.initialPrompt,syntheticParts:n?.syntheticParts,targetFolderId:n?.targetFolderId};e({newSessionDraft:{...I},currentSessionId:null,currentSessionDirectory:null,error:null}),Js(or(),{sessionId:null,directory:C,draft:I}),n?.initialPrompt&&Ye.getState().setPendingInputText(n.initialPrompt);const E=de(v?.path??null)??C;vp(E),C&&C!==nt.getState().currentDirectory&&nt.getState().setDirectory(C)},closeNewSessionDraft:()=>{const n=t().newSessionDraft;if(!n.open&&n.selectedProjectId==null&&n.directoryOverride==null&&n.branchIntent==null&&n.worktreeIntent==null&&!n.preserveDirectoryOverride&&n.parentID==null&&n.title===void 0&&n.initialPrompt===void 0&&n.syntheticParts===void 0&&n.targetFolderId===void 0&&n.permissionAutoAcceptEnabled===void 0)return;const r={id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0};e({newSessionDraft:r}),Js(or(),{draft:r})},setNewSessionDraftTarget:n=>{let r=null,s=null;e(o=>{r=de(n.directoryOverride??o.newSessionDraft.directoryOverride),s=n.projectId??n.selectedProjectId??o.newSessionDraft.selectedProjectId??null;const i=Object.prototype.hasOwnProperty.call(n,"branchIntent"),a=Object.prototype.hasOwnProperty.call(n,"worktreeIntent"),l=de(o.newSessionDraft.directoryOverride),d=r!==l,f=s!==(o.newSessionDraft.selectedProjectId??null),u=n.branchIntent,h=u&&u.runtimeKey===Y()&&de(u.directory)===r?u:null,m=n.worktreeIntent,g=m&&m.runtimeKey===Y()&&de(m.sourceDirectory)===r?m:null;return{newSessionDraft:{...o.newSessionDraft,selectedProjectId:s,directoryOverride:n.directoryOverride??o.newSessionDraft.directoryOverride,branchIntent:i?h:d||f?null:o.newSessionDraft.branchIntent,worktreeIntent:a?g:d||f?null:o.newSessionDraft.worktreeIntent}}}),gp({projectId:s,directory:r}),vp(r),r&&r!==nt.getState().currentDirectory&&nt.getState().setDirectory(r)},setDraftPreserveDirectoryOverride:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,preserveDirectoryOverride:n}}:r),setDraftPermissionAutoAcceptEnabled:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,permissionAutoAcceptEnabled:n}}:r),acknowledgeSessionAbort:n=>e(r=>{const s=new Map(r.sessionAbortFlags),o=s.get(n);return o&&s.set(n,{...o,acknowledged:!0}),{sessionAbortFlags:s}}),clearAbortPrompt:()=>e({abortPromptSessionId:null,abortPromptExpiresAt:null}),armAbortPrompt:(n=5e3)=>{const{currentSessionId:r}=t();if(!r)return null;const s=Date.now()+n;return e({abortPromptSessionId:r,abortPromptExpiresAt:s}),s},clearError:()=>e({error:null}),setSendingNewSessionDraftId:n=>{t().sendingNewSessionDraftId!==n&&e({sendingNewSessionDraftId:n})},markSessionAsPiChamberCreated:n=>e(r=>{const s=new Set(r.webUICreatedSessions);return s.add(n),{webUICreatedSessions:s}}),isPiChamberCreatedSession:n=>t().webUICreatedSessions.has(n),dismissPendingChangesBar:(n,r)=>{const s=new Map(t().pendingChangesBarDismissed);r===null?s.delete(n):s.set(n,r),e({pendingChangesBarDismissed:s})},sendMessage:async(n,r,s,o,i,a,l,d,f,u)=>{const h=u?.target;if(h&&h.runtimeKey!==Y())throw new Error("Message was not sent because the runtime changed.");const m=h?.sessionId??u?.sessionId??(u?.draftSnapshot?null:t().currentSessionId);if(m){const w=new Map(t().pendingChangesBarDismissed);w.delete(m),e({pendingChangesBarDismissed:w})}const g=t().newSessionDraft,x=typeof o=="string"&&o.trim().length>0?o.trim():void 0;if(f==="shell"){let w=h?.sessionId??u?.sessionId??null;if(!w&&(u?.draftSnapshot?.open||g?.open)){const I=await xp({providerID:r,modelID:s,agent:x,variant:d,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot});if(!I)throw new Error("Failed to create session");w=I.sessionId}if(w??=t().currentSessionId,!w)throw new Error("Select a session to run a shell command.");await qe().runBash(w,n,{excludeFromContext:u?.shellExcludeFromContext===!0});return}if(!h&&!u?.sessionId&&(u?.draftSnapshot?.open||g?.open)){const w=await xp({providerID:r,modelID:s,agent:x,variant:d,initialPrompt:n,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot,initialInputKind:u?.initialInputKind});if(!w)throw new Error("Failed to create session");const I=w.syntheticParts?.length?[...l||[],...w.syntheticParts]:l;h2(w.sessionId);const E=i?.map(T=>({type:"file",mime:T.mimeType,url:T.dataUrl,filename:T.filename,uploadState:T.uploadState}));await mp({sessionId:w.sessionId,directory:w.directory,content:n,providerID:r,modelID:s,agent:w.agent,agentMentionName:a,variant:d,inputMode:f,files:E,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,knownEmptyTranscript:!0,additionalParts:I?.map(T=>({text:T.text,synthetic:T.synthetic,files:T.attachments?.map(A=>({type:"file",mime:A.mimeType,url:A.dataUrl,filename:A.filename,uploadState:A.uploadState}))}))});return}const b=h?.sessionId??u?.sessionId??t().currentSessionId,S=b?Lt.getState().getSessionAgentSelection(b):null,y=x||S||void 0;b&&Lt.getState().saveSessionModelSelection(b,r,s),b&&y&&(Lt.getState().saveSessionAgentSelection(b,y),Lt.getState().saveAgentModelForSession(b,y,r,s),Lt.getState().saveAgentModelVariantForSession(b,y,r,s,d));const v=b?de(h?.directory??u?.directory??t().getDirectoryForSession(b)):null;b&&h2(b);const C=i?.map(w=>({type:"file",mime:w.mimeType,url:w.dataUrl,filename:w.filename,uploadState:w.uploadState}));await mp({runtimeKey:h?.runtimeKey,sessionId:b||"",directory:v,content:n,providerID:r,modelID:s,agent:y,agentMentionName:a,variant:d,inputMode:f,files:C,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,additionalParts:l?.map(w=>({text:w.text,synthetic:w.synthetic,files:w.attachments?.map(I=>({type:"file",mime:I.mimeType,url:I.dataUrl,filename:I.filename,uploadState:I.uploadState}))}))})},createSession:async(n,r,s,o,i)=>{const a=i?.draftSnapshot??t().newSessionDraft,l=a.targetFolderId;try{const d=r??qe().getState().directory,f=await y_(n,d,s??null,o);if(!f)return null;if(i?.closeDraft!==!1&&t().newSessionDraft===a&&t().closeNewSessionDraft(),l){const u=r||f.directory;u&&Vm.getState().addSessionToFolder(u,l,f.id)}return f}catch(d){return console.error("[session-ui-store] createSession failed",d),null}},deleteSession:async(n,r)=>{const s=await v_(n);return s&&t().currentSessionId===n&&t().openNewSessionDraft(),s},deleteSessions:async(n,r)=>{const s=await x_(n),o=t().currentSessionId;return o&&s.deletedIds.includes(o)&&t().openNewSessionDraft(),s},archiveSession:n=>b_(n),archiveSessions:(n,r)=>w_(n),unarchiveSession:n=>S_(n),unarchiveSessions:(n,r)=>C_(n),updateSessionTitle:async(n,r)=>{await k_(n,r)},shareSession:async n=>M_(),unshareSession:async n=>I_(),revertToMessage:async(n,r)=>{await E_(n,r)},restoreToMessage:async(n,r)=>{await __(n,r)},handleSlashUndo:async n=>{const r=qe().getState().reducer.bySession.get(n),o=(r?[...r.messages.values()]:[]).filter(l=>l.role==="user");if(o.length===0)return;const i=o[o.length-1];if(!i)return;String(i.text??"").slice(0,50)+((i.text?.length??0)>50?"...":""),await t().revertToMessage(n,i.id);const{toast:a}=await mt(async()=>{const{toast:l}=await import("./vendor-boot-3SaHYVb1.js").then(d=>d.cq);return{toast:l}},__vite__mapDeps([5,1,6]));a.success("Reverted — conversation rewound. Files on disk were not changed.")},handleSlashRedo:async n=>{await j_(n);const{toast:r}=await mt(async()=>{const{toast:s}=await import("./vendor-boot-3SaHYVb1.js").then(o=>o.cq);return{toast:s}},__vite__mapDeps([5,1,6]));r.success("Restored all messages")},forkFromMessage:async(n,r)=>{await T_(n,r)},getSessionsByDirectory:n=>{const r=de(n);return r?Gm().filter(o=>Lw(o)===r):[]},getDirectoryForSession:n=>{const r=n===t().currentSessionId?t().currentSessionDirectory:null,s=I2(n,r);if(s)return s;try{return qe().getState().catalog.byId.get(n)?.directory??null}catch{return null}},adoptAuthoritativeSessionDirectory:n=>{const r=n??t().currentSessionId;if(!r||r!==k2()||r!==t().currentSessionId)return;const s=D_(r);s&&(M2(),s!==t().currentSessionDirectory&&e({currentSessionDirectory:s}),Js(or(),{sessionId:r,directory:s}))},setSessionDirectory:(n,r)=>{const s=de(r);n===k2()&&M2(),n===t().currentSessionId&&(e({currentSessionDirectory:s}),Js(or(),{sessionId:n,directory:s}))}})),rJ=Object.freeze(Object.defineProperty({__proto__:null,draftBranchCheckoutReceiptMatches:da,getRememberedSessionDirectory:O_,materializeOpenDraftSession:xp,routeMessage:mp,useSessionUIStore:he},Symbol.toStringTag,{value:"Module"}));async function yr(e){let t=null;if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0,method:"clipboard"}}catch(n){t=n instanceof Error?n.message:String(n)}if(typeof document<"u"&&document.body){const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="-1000px",n.style.left="-1000px",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);const r=document.execCommand("copy");if(document.body.removeChild(n),r)return{ok:!0,method:"execCommand"}}return{ok:!1,error:t??"Clipboard access denied in current context"}}async function $_(e,t){if(typeof navigator<"u"&&navigator.clipboard?.write&&typeof ClipboardItem<"u")try{const n={"text/plain":new Blob([e],{type:"text/plain"}),"text/html":new Blob([t],{type:"text/html"})};return typeof ClipboardItem.supports=="function"&&ClipboardItem.supports("text/markdown")&&(n["text/markdown"]=new Blob([e],{type:"text/markdown"})),await navigator.clipboard.write([new ClipboardItem(n)]),{ok:!0,method:"clipboard"}}catch{}return yr(e)}const t1=H.createContext(void 0);function vr(){const e=H.useContext(t1);if(!e)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return e}function Dw(){return H.useContext(t1)}const Ow=async(e,t)=>{if(!IS())throw new Error("Desktop runtime is not available");return lr(e,t)},z_=async e=>{if(xt())try{await Ow("desktop_set_window_title",{title:e})}catch{}},U_=async(e,t)=>{if(xt())try{await Ow("desktop_set_window_theme",{themeMode:e,themeVariant:t})}catch{}},Hw=4.5;function yd(e){if(!e)return null;const t=e.trim();if(t.startsWith("#")){let o=t.slice(1);return(o.length===3||o.length===4)&&(o=o.split("").map(i=>i+i).join("")),/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(o)?{r:parseInt(o.slice(0,2),16),g:parseInt(o.slice(2,4),16),b:parseInt(o.slice(4,6),16),a:o.length===8?parseInt(o.slice(6,8),16)/255:1}:null}const n=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/i);if(!n)return null;const r=n[4],s=r===void 0?1:r.endsWith("%")?parseFloat(r)/100:parseFloat(r);return{r:Number(n[1]),g:Number(n[2]),b:Number(n[3]),a:Math.min(1,Math.max(0,s))}}function bp({r:e,g:t,b:n}){return`#${[e,t,n].map(r=>Math.round(r).toString(16).padStart(2,"0")).join("")}`}function vd(e,t){return{r:e.r*e.a+t.r*(1-e.a),g:e.g*e.a+t.g*(1-e.a),b:e.b*e.a+t.b*(1-e.a),a:1}}function Fw(e,t,n){return{r:Math.round(e.r+(t.r-e.r)*n),g:Math.round(e.g+(t.g-e.g)*n),b:Math.round(e.b+(t.b-e.b)*n),a:1}}function wp({r:e,g:t,b:n}){const r=s=>{const o=s/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4};return .2126*r(e)+.7152*r(t)+.0722*r(n)}function q_(e,t){const[n,r]=[wp(e),wp(t)].sort((s,o)=>o-s);return(n+.05)/(r+.05)}function Sp(e,t){return Math.min(...t.map(n=>q_(vd(e,n),n)))}function Cp(e){return e.map(yd).filter(t=>t!==null).map(t=>({...t,a:1}))}function W_(e,t,n,r=Hw){const s=yd(e),o=yd(n),i=Cp(t);if(!s||!o||i.length===0||Sp(s,i)>=r)return e;const a=vd(s,i[0]),l=vd(o,i[0]);for(let d=1;d<=20;d+=1){const f=Fw(a,l,d/20);if(Sp(f,i)>=r)return bp(f)}return bp(l)}function K_(e,t,n,{min:r=Hw,maxFade:s=.3}={}){const o=yd(e),i=Cp(t),a=Cp([n])[0];if(!o||!a||i.length===0)return e;const l=vd(o,a);let d=null;for(let f=1;f<=30;f+=1){const u=s*f/30,h=Fw(l,a,u);if(Sp(h,i)<r)break;d=h}return d?bp(d):e}const _f=e=>{if(!e||typeof e!="string")return null;const t=e.trim();if(!t.startsWith("#"))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split("").map(a=>a+a).join("")),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;const r=Number.parseInt(n,16);if(Number.isNaN(r))return null;const s=r>>16&255,o=r>>8&255,i=r&255;return`${s} ${o} ${i}`};function G_(e){const{surface:t}=e.colors,n=W_(t.mutedForeground,[t.background,t.muted,t.elevated],t.foreground);return n===t.mutedForeground?e:{...e,colors:{...e.colors,surface:{...t,mutedForeground:n}}}}class Z_{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(t){const n=[],r=G_(t),{surface:s}=r.colors,o=[s.background,s.muted,s.elevated];n.push(...this.generateTailwindVariables(r));const i=K_(s.mutedForeground,o,s.background,{maxFade:.15});return n.push(` --subtle-foreground: ${i} !important;`),n.push(...this.generatePrimaryColors(r.colors.primary)),n.push(...this.generateSurfaceColors(r.colors.surface)),n.push(...this.generateInteractiveColors(r.colors.interactive)),n.push(...this.generateStatusColors(r.colors.status)),n.push(...this.generatePullRequestColors(r)),n.push(...this.generateSyntaxColors(r.colors.syntax)),n.push(...this.generateComponentColors(r.colors,r)),n.push(...this.generateTypographyVariables()),r.config&&n.push(...this.generateConfigVariables(r.config)),n.join(`
23
- `)}generateTailwindVariables(t){const n=[];n.push(` --background: ${t.colors.surface.background} !important;`),n.push(` --foreground: ${t.colors.surface.foreground} !important;`),n.push(` --muted: ${t.colors.surface.muted} !important;`),n.push(` --muted-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --card: ${t.colors.surface.elevated} !important;`),n.push(` --card-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --popover: ${t.colors.surface.elevated} !important;`),n.push(` --popover-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --border: ${t.colors.interactive.border} !important;`),n.push(` --input: ${t.colors.interactive.border} !important;`),n.push(` --primary: ${t.colors.primary.base} !important;`),n.push(` --primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --secondary: ${t.colors.surface.muted} !important;`),n.push(` --secondary-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --accent: ${t.colors.surface.subtle} !important;`),n.push(` --accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --destructive: ${t.colors.status.error} !important;`),n.push(` --destructive-foreground: ${t.colors.status.errorForeground} !important;`),n.push(` --ring: ${t.colors.interactive.focusRing} !important;`);const r=_f(t.colors.surface.muted),s=_f(t.colors.surface.subtle),o=_f(t.colors.interactive.border);n.push(` --sidebar-base: ${t.colors.surface.muted} !important;`),r&&n.push(` --sidebar-base-rgb: ${r} !important;`),n.push(" --sidebar: var(--sidebar-base) !important;"),n.push(` --sidebar-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --sidebar-primary: ${t.colors.primary.base} !important;`),n.push(` --sidebar-primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --sidebar-accent-base: ${t.colors.surface.subtle} !important;`),s&&n.push(` --sidebar-accent-base-rgb: ${s} !important;`),n.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),n.push(` --sidebar-accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --sidebar-border: ${t.colors.interactive.border} !important;`),o&&n.push(` --sidebar-border-rgb: ${o} !important;`),n.push(` --sidebar-ring: ${t.colors.interactive.focusRing} !important;`);const i=t.metadata.variant==="dark",a=i?.15:.5,l=i?.1:.3;if(r)n.push(` --sidebar-overlay-strong: rgb(${r} / ${a}) !important;`),n.push(` --sidebar-overlay-soft: rgb(${r} / ${l}) !important;`);else{const d=t.colors.surface.muted;n.push(` --sidebar-overlay-strong: ${this.opacity(d,a)} !important;`),n.push(` --sidebar-overlay-soft: ${this.opacity(d,l)} !important;`)}return t.colors.charts?.series&&Array.isArray(t.colors.charts.series)&&t.colors.charts.series.forEach((d,f)=>{n.push(` --chart-${f+1}: ${d};`)}),t.colors.loading?(n.push(` --loading-spinner: ${t.colors.loading.spinner||t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.loading.spinnerTrack||t.colors.surface.muted};`)):(n.push(` --loading-spinner: ${t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.surface.muted};`)),n}apply(t){const n=this.generate(t),r=document.createElement("style");r.id="pichamber-theme-variables";let s="";t.metadata.variant==="dark"?(s=`:root {
24
- ${n}
25
- }
26
-
27
- .dark {
28
- ${n}
29
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(s=`:root {
30
- ${n}
31
- }
32
-
33
- :root:not(.dark) {
34
- ${n}
35
- }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),r.textContent=s;const o=document.getElementById("pichamber-theme-variables");o&&o.remove(),document.head.appendChild(r),document.documentElement.setAttribute("data-theme",t.metadata.variant)}generatePrimaryColors(t){const n=[];return n.push(` --primary-base: ${t.base};`),n.push(` --primary-hover: ${t.hover||this.darken(t.base,10)};`),n.push(` --primary-active: ${t.active||this.darken(t.base,20)};`),n.push(` --primary-foreground: ${t.foreground||"#ffffff"};`),n.push(` --primary-muted: ${t.muted||this.opacity(t.base,.5)};`),n.push(` --primary-emphasis: ${t.emphasis||this.lighten(t.base,10)};`),n}generateSurfaceColors(t){const n=[];return n.push(` --surface-background: ${t.background};`),n.push(` --surface-foreground: ${t.foreground};`),n.push(` --surface-muted: ${t.muted};`),n.push(` --surface-muted-foreground: ${t.mutedForeground};`),n.push(` --surface-elevated: ${t.elevated};`),n.push(` --surface-elevated-foreground: ${t.elevatedForeground};`),n.push(` --surface-overlay: ${t.overlay};`),n.push(` --surface-subtle: ${t.subtle};`),n}generateInteractiveColors(t){const n=[];return n.push(` --interactive-border: ${t.border};`),n.push(` --interactive-border-hover: ${t.borderHover};`),n.push(` --interactive-border-focus: ${t.borderFocus};`),n.push(` --interactive-selection: ${t.selection};`),n.push(` --interactive-selection-foreground: ${t.selectionForeground};`),n.push(` --interactive-focus: ${t.focus};`),n.push(` --interactive-focus-ring: ${t.focusRing};`),n.push(` --interactive-cursor: ${t.cursor};`),n.push(` --interactive-hover: ${t.hover};`),n.push(` --interactive-active: ${t.active};`),n}generateStatusColors(t){const n=[];return n.push(` --status-error: ${t.error};`),n.push(` --status-error-foreground: ${t.errorForeground};`),n.push(` --status-error-background: ${t.errorBackground};`),n.push(` --status-error-border: ${t.errorBorder};`),n.push(` --status-warning: ${t.warning};`),n.push(` --status-warning-foreground: ${t.warningForeground};`),n.push(` --status-warning-background: ${t.warningBackground};`),n.push(` --status-warning-border: ${t.warningBorder};`),n.push(` --status-success: ${t.success};`),n.push(` --status-success-foreground: ${t.successForeground};`),n.push(` --status-success-background: ${t.successBackground};`),n.push(` --status-success-border: ${t.successBorder};`),n.push(` --status-info: ${t.info};`),n.push(` --status-info-foreground: ${t.infoForeground};`),n.push(` --status-info-background: ${t.infoBackground};`),n.push(` --status-info-border: ${t.infoBorder};`),n}generatePullRequestColors(t){const n=[],r=t.colors.pr;return n.push(` --pr-open: ${r?.open||t.colors.status.success};`),n.push(` --pr-draft: ${r?.draft||t.colors.surface.mutedForeground};`),n.push(` --pr-blocked: ${r?.blocked||t.colors.status.warning};`),n.push(` --pr-merged: ${r?.merged||(t.metadata.variant==="dark"?"#8957e5":"#8250df")};`),n.push(` --pr-closed: ${r?.closed||t.colors.status.error};`),n}generateSyntaxColors(t){const n=[];n.push(` --syntax-background: ${t.base.background};`),n.push(` --syntax-foreground: ${t.base.foreground};`),n.push(` --syntax-comment: ${t.base.comment};`),n.push(` --syntax-keyword: ${t.base.keyword};`),n.push(` --syntax-string: ${t.base.string};`),n.push(` --syntax-number: ${t.base.number};`),n.push(` --syntax-function: ${t.base.function};`),n.push(` --syntax-variable: ${t.base.variable};`),n.push(` --syntax-type: ${t.base.type};`),n.push(` --syntax-operator: ${t.base.operator};`);const r=this.generateSyntaxTokens(t);for(const[s,o]of Object.entries(r))n.push(` --syntax-${this.kebabCase(s)}: ${o};`);return n}generateSyntaxTokens(t){const n=t.base,r=t.tokens||{};return{commentDoc:r.commentDoc||this.lighten(n.comment,10),stringEscape:r.stringEscape||this.darken(n.string,20),stringInterpolation:r.stringInterpolation||n.variable,stringRegex:r.stringRegex||this.adjustHue(n.string,15),keywordControl:r.keywordControl||n.keyword,keywordOperator:r.keywordOperator||n.operator,keywordImport:r.keywordImport||this.lighten(n.keyword,10),keywordReturn:r.keywordReturn||this.emphasize(n.keyword),functionCall:r.functionCall||this.lighten(n.function,5),functionBuiltin:r.functionBuiltin||this.darken(n.function,10),method:r.method||n.function,methodCall:r.methodCall||this.lighten(n.function,5),variableBuiltin:r.variableBuiltin||this.emphasize(n.variable),variableProperty:r.variableProperty||this.lighten(n.variable,10),variableReadonly:r.variableReadonly||n.number,parameter:r.parameter||n.variable,typePrimitive:r.typePrimitive||this.darken(n.type,10),typeInterface:r.typeInterface||n.type,className:r.className||this.emphasize(n.type),enum:r.enum||n.type,boolean:r.boolean||n.number,null:r.null||this.opacity(n.number,.7),constant:r.constant||n.number,punctuation:r.punctuation||this.opacity(n.foreground,.7),delimiter:r.delimiter||this.opacity(n.foreground,.8),bracket:r.bracket||n.foreground,tag:r.tag||n.keyword,tagAttribute:r.tagAttribute||n.variable,tagAttributeValue:r.tagAttributeValue||n.string,tagBracket:r.tagBracket||this.opacity(n.foreground,.8),decorator:r.decorator||n.function,annotation:r.annotation||n.function,namespace:r.namespace||this.opacity(n.type,.8),module:r.module||this.opacity(n.type,.8),...r}}generateComponentColors(t,n){const r=[];return t.markdown?r.push(...this.generateMarkdownColors(t.markdown,n)):r.push(...this.generateDefaultMarkdownColors(n)),t.chat?r.push(...this.generateChatColors(t.chat,n)):r.push(...this.generateDefaultChatColors(n)),t.tools?r.push(...this.generateToolColors(t.tools,n)):r.push(...this.generateDefaultToolColors(n)),r}generateMarkdownColors(t,n){const r=[],s=n.colors.primary.base,o=n.colors.chat?.background||n.colors.surface.background;return r.push(` --markdown-heading1: ${t.heading1||s};`),r.push(` --markdown-heading2: ${t.heading2||this.opacity(s,.9)};`),r.push(` --markdown-heading3: ${t.heading3||this.opacity(s,.8)};`),r.push(` --markdown-heading4: ${t.heading4||n.colors.surface.foreground};`),r.push(` --markdown-link: ${t.link||s};`),r.push(` --markdown-link-hover: ${t.linkHover||n.colors.primary.hover||this.darken(s,10)};`),r.push(` --markdown-inline-code: ${t.inlineCode||n.colors.syntax.base.string};`),r.push(` --markdown-inline-code-bg: ${t.inlineCodeBackground||o};`),r.push(` --markdown-blockquote: ${t.blockquote||n.colors.surface.mutedForeground};`),r.push(` --markdown-blockquote-border: ${t.blockquoteBorder||n.colors.interactive.border};`),r.push(` --markdown-list-marker: ${t.listMarker||this.opacity(s,.6)};`),r.push(` --markdown-bold: ${t.bold||n.colors.surface.foreground};`),r.push(` --markdown-italic: ${t.italic||this.opacity(n.colors.surface.foreground,.9)};`),r.push(` --markdown-strikethrough: ${t.strikethrough||n.colors.surface.mutedForeground};`),r.push(` --markdown-hr: ${t.hr||n.colors.interactive.border};`),r}generateDefaultMarkdownColors(t){const n=[],r=t.colors.primary.base,s=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r};`),n.push(` --markdown-heading2: ${this.opacity(r,.9)};`),n.push(` --markdown-heading3: ${this.opacity(r,.8)};`),n.push(` --markdown-heading4: ${t.colors.surface.foreground};`),n.push(` --markdown-link: ${r};`),n.push(` --markdown-link-hover: ${t.colors.primary.hover||this.darken(r,10)};`),n.push(` --markdown-inline-code: ${t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s};`),n.push(` --markdown-blockquote: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${this.opacity(r,.6)};`),n.push(` --markdown-bold: ${t.colors.surface.foreground};`),n.push(` --markdown-italic: ${this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${t.colors.interactive.border};`),n}generateChatColors(t,n){const r=[],s=t.background||n.colors.surface.background;return r.push(` --chat-background: ${s};`),r.push(` --chat-user-message: ${t.userMessage||n.colors.surface.foreground};`),r.push(` --chat-user-message-bg: ${t.userMessageBackground||n.colors.surface.elevated};`),r.push(` --chat-assistant-message: ${t.assistantMessage||n.colors.surface.foreground};`),r.push(` --chat-assistant-message-bg: ${t.assistantMessageBackground||n.colors.surface.muted};`),r.push(` --chat-timestamp: ${t.timestamp||n.colors.surface.mutedForeground};`),r.push(` --chat-divider: ${t.divider||n.colors.interactive.border};`),r.push(` --chat-typing: ${t.typing||n.colors.surface.mutedForeground};`),r}generateDefaultChatColors(t){const n=[];return n.push(` --chat-background: ${t.colors.surface.background};`),n.push(` --chat-user-message: ${t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${t.colors.surface.muted};`),n.push(` --chat-timestamp: ${t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${t.colors.interactive.border};`),n.push(` --chat-typing: ${t.colors.surface.mutedForeground};`),n}generateToolColors(t,n){const r=[];return r.push(` --tools-background: ${t?.background||this.opacity(n.colors.surface.muted,.2)};`),r.push(` --tools-border: ${t?.border||this.opacity(n.colors.interactive.border,.3)};`),r.push(` --tools-header-hover: ${t?.headerHover||this.opacity(n.colors.surface.muted,.3)};`),r.push(` --tools-icon: ${t?.icon||n.colors.surface.mutedForeground};`),r.push(` --tools-title: ${t?.title||n.colors.surface.foreground};`),r.push(` --tools-description: ${t?.description||"var(--subtle-foreground)"};`),t?.edit?(r.push(` --tools-edit-added: ${t.edit.added||n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${t.edit.addedBackground||n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${t.edit.removed||n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${t.edit.removedBackground||n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${t.edit.modified||n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${t.edit.modifiedBackground||n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${t.edit.lineNumber||this.opacity(n.colors.surface.mutedForeground,.6)};`)):(r.push(` --tools-edit-added: ${n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${this.opacity(n.colors.surface.mutedForeground,.6)};`)),r}generateDefaultToolColors(t){const n=[];return n.push(` --tools-background: ${this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${t.colors.surface.foreground};`),n.push(" --tools-description: var(--subtle-foreground);"),n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.successBackground),.15)};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.errorBackground),.15)};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.infoBackground),.15)};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`),n}generateConfigVariables(t){const n=[];return t&&(t.fonts&&(t.fonts.sans&&(n.push(` --font-sans: ${t.fonts.sans};`),n.push(` --font-family-sans: ${t.fonts.sans};`)),t.fonts.mono&&(n.push(` --font-mono: ${t.fonts.mono};`),n.push(` --font-family-mono: ${t.fonts.mono};`)),t.fonts.heading&&n.push(` --font-heading: ${t.fonts.heading};`)),t.transitions&&(t.transitions.fast&&n.push(` --transition-fast: ${t.transitions.fast};`),t.transitions.normal&&n.push(` --transition-normal: ${t.transitions.normal};`),t.transitions.slow&&n.push(` --transition-slow: ${t.transitions.slow};`))),n}generateTypographyVariables(){const t=[],n=ES;return t.push(" /* Semantic Typography Variables */"),t.push(" --ui-regular-font-weight: 400;"),t.push(" /* Markdown content - all markdown elements use same size */"),t.push(` --text-markdown: ${n.markdown};`),t.push(" /* Code content - all code elements use same size */"),t.push(` --text-code: ${n.code};`),t.push(" /* UI headers - dialog titles, panel headers */"),t.push(` --text-ui-header: ${n.uiHeader};`),t.push(" /* UI labels - buttons, menus, navigation */"),t.push(` --text-ui-label: ${n.uiLabel};`),t.push(" /* Metadata - timestamps, status, helper text */"),t.push(` --text-meta: ${n.meta};`),t.push(" /* Micro text - badges, shortcuts, indicators */"),t.push(` --text-micro: ${n.micro};`),t.push(" /* Settings page titles - larger than section headers */"),t.push(` --text-settings-page-title: ${n.settingsPageTitle};`),t.push(" /* Heading line height and letter spacing */"),t.push(" --h1-line-height: 1.25rem;"),t.push(" --h2-line-height: 1.25rem;"),t.push(" --h3-line-height: 1.5rem;"),t.push(" --h4-line-height: 1.5rem;"),t.push(" --h5-line-height: 1.5rem;"),t.push(" --h6-line-height: 1.5rem;"),t.push(" --h1-letter-spacing: -0.025em;"),t.push(" --h2-letter-spacing: -0.02em;"),t.push(" --h3-letter-spacing: -0.015em;"),t.push(" --h4-letter-spacing: -0.01em;"),t.push(" --h5-letter-spacing: 0;"),t.push(" --h6-letter-spacing: 0.01em;"),t.push(" /* UI element line height and letter spacing */"),t.push(" --ui-button-line-height: 1.375rem;"),t.push(" --ui-button-letter-spacing: 0.02em;"),t.push(" --ui-button-font-weight: 500;"),t.push(" --ui-label-line-height: 1rem;"),t.push(" --ui-label-letter-spacing: 0.03em;"),t.push(" --ui-label-font-weight: 500;"),t.push(" --ui-caption-line-height: 1rem;"),t.push(" --ui-caption-letter-spacing: 0.025em;"),t.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Markdown line height and letter spacing */"),t.push(" --markdown-body-line-height: 1.5rem;"),t.push(" --markdown-body-letter-spacing: 0;"),t.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-h1-line-height: 1.25rem;"),t.push(" --markdown-h1-letter-spacing: -0.025em;"),t.push(" --markdown-h2-line-height: 1.25rem;"),t.push(" --markdown-h2-letter-spacing: -0.02em;"),t.push(" --markdown-h3-line-height: 1.5rem;"),t.push(" --markdown-h3-letter-spacing: -0.015em;"),t.push(" --markdown-h4-line-height: 1.5rem;"),t.push(" --markdown-h4-letter-spacing: -0.01em;"),t.push(" --markdown-h5-line-height: 1.5rem;"),t.push(" --markdown-h5-letter-spacing: 0;"),t.push(" --markdown-h6-line-height: 1.5rem;"),t.push(" --markdown-h6-letter-spacing: 0.01em;"),t.push(" --markdown-list-line-height: 1.375rem;"),t.push(" --markdown-code-block-line-height: 1rem;"),t.push(" --ui-button-small-line-height: 1.25rem;"),t.push(" --ui-button-small-letter-spacing: 0.02em;"),t.push(" --ui-button-small-font-weight: 500;"),t.push(" --markdown-body-small-line-height: 1.375rem;"),t.push(" --markdown-body-small-letter-spacing: 0;"),t.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-button-large-line-height: 1.5rem;"),t.push(" --ui-button-large-letter-spacing: 0.02em;"),t.push(" --ui-button-large-font-weight: 500;"),t.push(" --markdown-body-large-line-height: 1.625rem;"),t.push(" --markdown-body-large-letter-spacing: 0;"),t.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Code line height and letter spacing */"),t.push(" --code-inline-line-height: 1rem;"),t.push(" --code-inline-letter-spacing: 0;"),t.push(" --code-inline-font-weight: 400;"),t.push(" --code-block-line-height: round(1.4rem, 1px);"),t.push(" --code-block-letter-spacing: 0;"),t.push(" --code-block-font-weight: 400;"),t.push(" --code-line-numbers-line-height: 1.25rem;"),t.push(" --code-line-numbers-letter-spacing: 0;"),t.push(" --code-line-numbers-font-weight: 400;"),t.push(" /* Additional UI element line height and letter spacing */"),t.push(" --ui-badge-line-height: 1rem;"),t.push(" --ui-badge-letter-spacing: 0.025em;"),t.push(" --ui-badge-font-weight: 500;"),t.push(" --ui-tooltip-line-height: 1rem;"),t.push(" --ui-tooltip-letter-spacing: 0.025em;"),t.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-input-line-height: 1.375rem;"),t.push(" --ui-input-letter-spacing: 0.02em;"),t.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-helper-text-line-height: 1rem;"),t.push(" --ui-helper-text-letter-spacing: 0.025em;"),t.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Additional markdown line height and letter spacing */"),t.push(" --markdown-blockquote-line-height: 1.5rem;"),t.push(" --markdown-blockquote-letter-spacing: 0;"),t.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-list-letter-spacing: 0;"),t.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-link-line-height: 1.5rem;"),t.push(" --markdown-link-letter-spacing: 0;"),t.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-code-line-height: round(1.35em, 1px);"),t.push(" --markdown-code-letter-spacing: 0;"),t.push(" --markdown-code-font-weight: 400;"),t.push(" --markdown-code-block-letter-spacing: 0;"),t.push(" --markdown-code-block-font-weight: 400;"),t}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(t,n){return t.startsWith("#")?`${t}${Math.round(n*255).toString(16).padStart(2,"0")}`:t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}removeTransparency(t){return t.startsWith("#")?t.length===9?t.slice(0,7):t.length===5?t.slice(0,4):t:t.startsWith("rgba")?t.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):t}addTransparency(t,n){if(t.startsWith("#")){const r=t.slice(1);if(r.length===3){const s=parseInt(r[0]+r[0],16),o=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16);return`rgba(${s}, ${o}, ${i}, ${n})`}else if(r.length===6){const s=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),i=parseInt(r.slice(4,6),16);return`rgba(${s}, ${o}, ${i}, ${n})`}}return t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}darken(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)-s,i=(r>>8&255)-s,a=(r&255)-s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}lighten(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)+s,i=(r>>8&255)+s,a=(r&255)+s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}adjustHue(t,n){return this.lighten(t,n/10)}emphasize(t){return this.lighten(t,15)}kebabCase(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const _2=(e,t)=>t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e),Y_=e=>typeof e=="string"&&e.trim().length>0,j2=e=>{if(!e||typeof e!="object")return!1;const t=[["metadata","id"],["metadata","name"],["metadata","variant"],["colors","primary","base"],["colors","primary","foreground"],["colors","surface","background"],["colors","surface","foreground"],["colors","surface","muted"],["colors","surface","mutedForeground"],["colors","surface","elevated"],["colors","surface","elevatedForeground"],["colors","surface","subtle"],["colors","interactive","border"],["colors","interactive","selection"],["colors","interactive","selectionForeground"],["colors","interactive","focusRing"],["colors","interactive","hover"],["colors","status","error"],["colors","status","errorForeground"],["colors","status","errorBackground"],["colors","status","errorBorder"],["colors","status","warning"],["colors","status","warningForeground"],["colors","status","warningBackground"],["colors","status","warningBorder"],["colors","status","success"],["colors","status","successForeground"],["colors","status","successBackground"],["colors","status","successBorder"],["colors","status","info"],["colors","status","infoForeground"],["colors","status","infoBackground"],["colors","status","infoBorder"],["colors","syntax","base","background"],["colors","syntax","base","foreground"],["colors","syntax","base","keyword"],["colors","syntax","base","string"],["colors","syntax","base","number"],["colors","syntax","base","function"],["colors","syntax","base","variable"],["colors","syntax","base","type"],["colors","syntax","base","comment"],["colors","syntax","base","operator"],["colors","syntax","highlights","diffAdded"],["colors","syntax","highlights","diffRemoved"],["colors","syntax","highlights","lineNumber"]];for(const r of t)if(!Y_(_2(e,r)))return!1;const n=_2(e,["metadata","variant"]);return n==="light"||n==="dark"},X_=TS,J_=jS,Q_=e=>NS(e==="dark"),ej=typeof window<"u"?p.useLayoutEffect:p.useEffect,tj=()=>{if(typeof document>"u")return;const e=document.documentElement;e.classList.add("oc-theme-switching");const t=window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{e.classList.remove("oc-theme-switching")})});return()=>{window.cancelAnimationFrame(t),e.classList.remove("oc-theme-switching")}},nj=e=>{let t=X_,n=J_,r="system";if(typeof window<"u"){const s=localStorage.getItem("themeMode"),o=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),a=localStorage.getItem("useSystemTheme"),l=localStorage.getItem("selectedThemeId"),d=localStorage.getItem("selectedThemeVariant");if(s==="light"||s==="dark"||s==="system")r=s;else if(a!==null){if(a==="true")r="system";else if(l){const u=Wg(l);u&&(r=u.metadata.variant==="dark"?"dark":"light",u.metadata.variant==="dark"?n=u.metadata.id:t=u.metadata.id)}}else(d==="light"||d==="dark")&&(r=d);typeof o=="string"&&o.trim().length>0&&(t=o.trim()),typeof i=="string"&&i.trim().length>0&&(n=i.trim())}if(e){const s=Wg(e);s&&(s.metadata.variant==="light"?t=s.metadata.id:n=s.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function sJ({children:e,defaultThemeId:t}){const n=H.useMemo(()=>new Z_,[]),[r,s]=H.useState(()=>nj(t)),[o,i]=H.useState(()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches),[a,l]=H.useState([]),[d,f]=H.useState([]),[u,h]=H.useState(!1),m=H.useMemo(()=>xt(),[]),g=H.useRef(0),x=H.useMemo(()=>{const _=[],M=new Set,L=O=>{const N=O.metadata.id;M.has(N)||(M.add(N),_.push(O))};return a.forEach(L),d.forEach(L),_S.forEach(L),_},[a,d]);H.useEffect(()=>{const _=M=>{const L=M.detail;if(!j2(L))return;const O=AS(L);f(N=>{const D=N.findIndex(z=>z.metadata.id===O.metadata.id);if(D<0)return[...N,O];const W=[...N];return W[D]=O,W})};return window.addEventListener("pichamber:theme-hmr",_),()=>window.removeEventListener("pichamber:theme-hmr",_)},[]);const b=H.useCallback(_=>x.find(M=>M.metadata.id===_),[x]),S=H.useCallback((_,M)=>{const L=b(_);return L&&L.metadata.variant===M?L:x.find(N=>N.metadata.variant===M)??Q_(M)},[x,b]),y=H.useMemo(()=>r.themeMode==="light"?S(r.lightThemeId,"light"):r.themeMode==="dark"||o?S(r.darkThemeId,"dark"):S(r.lightThemeId,"light"),[S,r,o]),v=H.useCallback(async()=>{if(typeof window>"u")return;const _=Y(),M=++g.current;h(!0);try{const L=await Rt("/api/pi/themes",{method:"GET",credentials:Yr()?"omit":"include",headers:{Accept:"application/json"}});if(L.status===401||!L.ok)return;const O=await L.json();if(M!==g.current||_!==Y())return;const D=(Array.isArray(O?.themes)?O.themes:[]).filter(j2);l(D)}catch{}finally{M===g.current&&_===Y()&&h(!1)}},[]);H.useEffect(()=>{v()},[v]),H.useEffect(()=>Zt(_=>{_.runtimeKey!==_.previousRuntimeKey&&(g.current+=1,l([]),h(!1),v())}),[v]);const C=H.useCallback(_=>{if(typeof document>"u")return;const M=_.colors.surface.background;document.body.style.backgroundColor=M;let L=document.querySelector('meta[name="theme-color"]');L||(L=document.createElement("meta"),L.setAttribute("name","theme-color"),document.head.appendChild(L)),L.setAttribute("content",M);const O=_.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let N=document.querySelector(`meta[name="theme-color"][media="${O}"]`);N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),N.setAttribute("media",O),document.head.appendChild(N)),N.setAttribute("content",M)},[]),w=H.useRef(!1);ej(()=>{if(typeof window>"u")return;const _=w.current?tj():void 0;w.current=!0,n.apply(y),C(y);const M=document.documentElement;return M.classList.remove("light","dark"),M.classList.add(y.metadata.variant),_},[n,y,C]),H.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const _=window.matchMedia("(prefers-color-scheme: dark)"),M=L=>{i(L.matches)};return i(_.matches),_.addEventListener("change",M),()=>_.removeEventListener("change",M)},[r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;localStorage.setItem("themeMode",r.themeMode),localStorage.setItem("lightThemeId",r.lightThemeId),localStorage.setItem("darkThemeId",r.darkThemeId),localStorage.setItem("useSystemTheme",String(r.themeMode==="system")),localStorage.setItem("selectedThemeId",y.metadata.id),localStorage.setItem("selectedThemeVariant",y.metadata.variant==="light"?"light":"dark");const _=S(r.lightThemeId,"light"),M=S(r.darkThemeId,"dark");localStorage.setItem("splashBgLight",_.colors.surface.background),localStorage.setItem("splashFgLight",_.colors.surface.foreground),localStorage.setItem("splashBgDark",M.colors.surface.background),localStorage.setItem("splashFgDark",M.colors.surface.foreground)},[r,y,S]),H.useEffect(()=>{if(typeof window>"u")return;const _=M=>{M.storageArea===window.localStorage&&(M.key!=="themeMode"&&M.key!=="lightThemeId"&&M.key!=="darkThemeId"||s(L=>{const O=localStorage.getItem("themeMode"),N=O==="light"||O==="dark"||O==="system"?O:L.themeMode,D=localStorage.getItem("lightThemeId"),W=typeof D=="string"&&D.trim().length>0?D.trim():L.lightThemeId,z=localStorage.getItem("darkThemeId"),X=typeof z=="string"&&z.trim().length>0?z.trim():L.darkThemeId;return N===L.themeMode&&W===L.lightThemeId&&X===L.darkThemeId?L:{themeMode:N,lightThemeId:W,darkThemeId:X}}))};return window.addEventListener("storage",_),()=>window.removeEventListener("storage",_)},[]),H.useEffect(()=>{const _=S(r.lightThemeId,"light"),M=S(r.darkThemeId,"dark");$r({themeId:y.metadata.id,themeVariant:y.metadata.variant==="light"?"light":"dark",useSystemTheme:r.themeMode==="system",lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:_.colors.surface.background,splashFgLight:_.colors.surface.foreground,splashBgDark:M.colors.surface.background,splashFgDark:M.colors.surface.foreground})},[y.metadata.id,y.metadata.variant,S,r.themeMode,r.lightThemeId,r.darkThemeId]),H.useEffect(()=>{m&&(async()=>await U_(r.themeMode,y.metadata.variant))()},[y.metadata.variant,m,r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;const _=M=>{const L=M.detail;L&&s(O=>{let N=O.themeMode;L.useSystemTheme===!0?N="system":L.useSystemTheme===!1&&(L.themeVariant==="dark"||L.themeVariant==="light")&&(N=L.themeVariant);let D=O.lightThemeId;typeof L.lightThemeId=="string"&&L.lightThemeId.length>0&&(D=L.lightThemeId.trim());let W=O.darkThemeId;return typeof L.darkThemeId=="string"&&L.darkThemeId.length>0&&(W=L.darkThemeId.trim()),N===O.themeMode&&D===O.lightThemeId&&W===O.darkThemeId?O:{themeMode:N,lightThemeId:D,darkThemeId:W}})};return window.addEventListener("pichamber:settings-synced",_),()=>window.removeEventListener("pichamber:settings-synced",_)},[]);const I=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_);M&&s(L=>M.metadata.variant==="dark"?L.darkThemeId===M.metadata.id&&L.themeMode==="dark"?L:{...L,darkThemeId:M.metadata.id,themeMode:"dark"}:L.lightThemeId===M.metadata.id&&L.themeMode==="light"?L:{...L,lightThemeId:M.metadata.id,themeMode:"light"})},[x]),E=H.useCallback(_=>{r.themeMode!==_&&(s(M=>({...M,themeMode:_})),$r({themeVariant:_==="system"?y.metadata.variant:_,useSystemTheme:_==="system"}))},[y.metadata.variant,r.themeMode]),T=H.useCallback(_=>{if(_){s(L=>L.themeMode==="system"?L:{...L,themeMode:"system"});return}const M=y.metadata.variant==="dark"?"dark":"light";s(L=>L.themeMode===M?L:{...L,themeMode:M})},[y.metadata.variant]),A=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_&&L.metadata.variant==="light");M&&s(L=>L.lightThemeId===M.metadata.id?L:{...L,lightThemeId:M.metadata.id})},[x]),j=H.useCallback(_=>{const M=x.find(L=>L.metadata.id===_&&L.metadata.variant==="dark");M&&s(L=>L.darkThemeId===M.metadata.id?L:{...L,darkThemeId:M.metadata.id})},[x]),k={currentTheme:y,availableThemes:x,setTheme:I,customThemesLoading:u,reloadCustomThemes:v,isSystemPreference:r.themeMode==="system",setSystemPreference:T,themeMode:r.themeMode,setThemeMode:E,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:A,setDarkThemePreference:j};return c.jsx(t1.Provider,{value:k,children:e})}let zc=null;const oJ=()=>{if(typeof window>"u"||zc)return()=>{};let e={showDeletionDialog:re.getState().showDeletionDialog,nativeNotificationsEnabled:re.getState().nativeNotificationsEnabled,notificationMode:re.getState().notificationMode,notifyOnCompletion:re.getState().notifyOnCompletion,notifyOnError:re.getState().notifyOnError,notifyOnInputNeeded:re.getState().notifyOnInputNeeded,summarizeLastMessage:re.getState().summarizeLastMessage,summaryThreshold:re.getState().summaryThreshold,summaryLength:re.getState().summaryLength,maxLastMessageLength:re.getState().maxLastMessageLength,autoDeleteEnabled:re.getState().autoDeleteEnabled,autoSaveEnabled:re.getState().autoSaveEnabled,autoDeleteAfterDays:re.getState().autoDeleteAfterDays,sessionRetentionAction:re.getState().sessionRetentionAction,fontSize:re.getState().fontSize,terminalFontSize:re.getState().terminalFontSize,terminalShell:re.getState().terminalShell,terminalLoginShells:re.getState().terminalLoginShells,editorFontSize:re.getState().editorFontSize,uiFont:re.getState().uiFont,monoFont:re.getState().monoFont,padding:re.getState().padding,cornerRadius:re.getState().cornerRadius,inputBarOffset:re.getState().inputBarOffset,mobileKeyboardMode:re.getState().mobileKeyboardMode,diffLayoutPreference:re.getState().diffLayoutPreference,gitChangesViewMode:re.getState().gitChangesViewMode};const t=re.subscribe(s=>{const o={showDeletionDialog:s.showDeletionDialog,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode,notifyOnCompletion:s.notifyOnCompletion,notifyOnError:s.notifyOnError,notifyOnInputNeeded:s.notifyOnInputNeeded,summarizeLastMessage:s.summarizeLastMessage,summaryThreshold:s.summaryThreshold,summaryLength:s.summaryLength,maxLastMessageLength:s.maxLastMessageLength,autoDeleteEnabled:s.autoDeleteEnabled,autoSaveEnabled:s.autoSaveEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,sessionRetentionAction:s.sessionRetentionAction,fontSize:s.fontSize,terminalFontSize:s.terminalFontSize,terminalShell:s.terminalShell,terminalLoginShells:s.terminalLoginShells,editorFontSize:s.editorFontSize,uiFont:s.uiFont,monoFont:s.monoFont,padding:s.padding,cornerRadius:s.cornerRadius,inputBarOffset:s.inputBarOffset,mobileKeyboardMode:s.mobileKeyboardMode,diffLayoutPreference:s.diffLayoutPreference,gitChangesViewMode:s.gitChangesViewMode},i={};o.showDeletionDialog!==e.showDeletionDialog&&(i.showDeletionDialog=o.showDeletionDialog),o.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&(i.nativeNotificationsEnabled=o.nativeNotificationsEnabled),o.notificationMode!==e.notificationMode&&(i.notificationMode=o.notificationMode),o.notifyOnCompletion!==e.notifyOnCompletion&&(i.notifyOnCompletion=o.notifyOnCompletion),o.notifyOnError!==e.notifyOnError&&(i.notifyOnError=o.notifyOnError),o.notifyOnInputNeeded!==e.notifyOnInputNeeded&&(i.notifyOnInputNeeded=o.notifyOnInputNeeded),o.summarizeLastMessage!==e.summarizeLastMessage&&(i.summarizeLastMessage=o.summarizeLastMessage),o.summaryThreshold!==e.summaryThreshold&&(i.summaryThreshold=o.summaryThreshold),o.summaryLength!==e.summaryLength&&(i.summaryLength=o.summaryLength),o.maxLastMessageLength!==e.maxLastMessageLength&&(i.maxLastMessageLength=o.maxLastMessageLength),o.autoDeleteEnabled!==e.autoDeleteEnabled&&(i.autoDeleteEnabled=o.autoDeleteEnabled),o.autoSaveEnabled!==e.autoSaveEnabled&&(i.autoSaveEnabled=o.autoSaveEnabled),o.autoDeleteAfterDays!==e.autoDeleteAfterDays&&(i.autoDeleteAfterDays=o.autoDeleteAfterDays),o.sessionRetentionAction!==e.sessionRetentionAction&&(i.sessionRetentionAction=o.sessionRetentionAction),o.fontSize!==e.fontSize&&(i.fontSize=o.fontSize),o.terminalFontSize!==e.terminalFontSize&&(i.terminalFontSize=o.terminalFontSize),o.terminalShell!==e.terminalShell&&(i.terminalShell=o.terminalShell),o.terminalLoginShells!==e.terminalLoginShells&&(i.terminalLoginShells=o.terminalLoginShells),o.editorFontSize!==e.editorFontSize&&(i.editorFontSize=o.editorFontSize),o.uiFont!==e.uiFont&&(i.uiFont=o.uiFont),o.monoFont!==e.monoFont&&(i.monoFont=o.monoFont),o.padding!==e.padding&&(i.padding=o.padding),o.cornerRadius!==e.cornerRadius&&(i.cornerRadius=o.cornerRadius),o.inputBarOffset!==e.inputBarOffset&&(i.inputBarOffset=o.inputBarOffset),o.mobileKeyboardMode!==e.mobileKeyboardMode&&(i.mobileKeyboardMode=o.mobileKeyboardMode),o.diffLayoutPreference!==e.diffLayoutPreference&&(i.diffLayoutPreference=o.diffLayoutPreference),o.gitChangesViewMode!==e.gitChangesViewMode&&(i.gitChangesViewMode=o.gitChangesViewMode),e=o,Object.keys(i).length>0&&$r(i)});let n=!1;const r=()=>{n||(n=!0,t(),zc===r&&(zc=null))};return zc=r,r},ao={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Bw={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},rj=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("surface")==="desktop",sj=e=>{if(typeof navigator>"u")return{isExplicitTablet:!1};const t=navigator.userAgent||"",n=navigator.platform||"",r=/iPad/i.test(t)||(/Macintosh|MacIntel/i.test(t)||/MacIntel/i.test(n))&&e>1,s=/Android/i.test(t)&&!/Mobile/i.test(t),o=/Tablet/i.test(t);return{isExplicitTablet:r||s||o}},oj=(e,t,n)=>{if(typeof window>"u")return;const r=document.documentElement;r.classList.remove("device-mobile","device-tablet","device-desktop"),r.classList.add(t==="mobile"?"device-mobile":t==="tablet"?"device-tablet":"device-desktop"),e?(r.classList.add("desktop-runtime"),r.classList.remove("mobile-pointer")):(r.classList.remove("desktop-runtime"),n?r.classList.add("mobile-pointer"):r.classList.remove("mobile-pointer"))};function pu(){const e=window.innerWidth,t=typeof window.matchMedia=="function",n=t?window.matchMedia("(pointer: coarse)"):null,r=t?window.matchMedia("(hover: none)"):null,s=n?.matches??!1,o=r?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,a=xt()||rj(),{isExplicitTablet:l}=sj(i),d=s||o||i>0,f=s||o,u=e>ao.md&&e<=ao.lg,h=e<=ao.md;let m=d&&h,g=d&&!m&&(u||l),x=!d||!g&&e>ao.lg,b="desktop";a?(m=!1,g=!1,x=!0,b="desktop"):dn()?(m=!0,g=!1,x=!1,b="mobile"):m?b="mobile":g?b="tablet":(x=!0,b="desktop"),oj(a,b,d);let S="xs";for(const[y,v]of Object.entries(ao))e>=v&&(S=y);return{isMobile:m,isTablet:g,isDesktop:x,deviceType:b,screenWidth:e,breakpoint:S,hasTouchInput:d,hasTouchOnlyPointer:f}}const ij=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,jl=new Set;let Fr=null,_o,vi=null;const aj=()=>typeof window>"u"?Bw:(Fr||(Fr=pu()),Fr),cj=()=>{for(const e of jl)e()},lj=()=>{_o=void 0;const e=pu();Fr&&ij(Fr,e)||(Fr=e,cj())},Uc=()=>{typeof window>"u"||_o!==void 0||(_o=window.requestAnimationFrame(lj))},xd=(e,t)=>e?typeof e.addEventListener=="function"?(e.addEventListener("change",t),()=>e.removeEventListener("change",t)):typeof e.addListener=="function"?(e.addListener(t),()=>e.removeListener(t)):()=>{}:()=>{},dj=()=>{if(typeof window>"u")return()=>{};Fr=pu(),window.addEventListener("resize",Uc);const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,t=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=xd(e,Uc),r=xd(t,Uc);return()=>{window.removeEventListener("resize",Uc),n(),r(),_o!==void 0&&(window.cancelAnimationFrame(_o),_o=void 0)}},uj=e=>typeof window>"u"?()=>{}:(jl.add(e),vi||(vi=dj()),()=>{jl.delete(e),jl.size===0&&vi&&(vi(),vi=null,Fr=null)}),fj=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),T2=()=>{if(typeof window>"u"||xt())return!1;const e=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return fj()&&e>0&&window.innerWidth>ao.md};function iJ(){const[e,t]=p.useState(()=>T2());return p.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(T2()),r=window.matchMedia?.("(display-mode: standalone)"),s=window.matchMedia?.("(display-mode: fullscreen)");n(),window.addEventListener("resize",n),window.addEventListener("focus",n);const o=a=>{a&&(typeof a.addEventListener=="function"?a.addEventListener("change",n):typeof a.addListener=="function"&&a.addListener(n))},i=a=>{a&&(typeof a.removeEventListener=="function"?a.removeEventListener("change",n):typeof a.removeListener=="function"&&a.removeListener(n))};return o(r),o(s),()=>{window.removeEventListener("resize",n),window.removeEventListener("focus",n),i(r),i(s)}},[]),e}const hj=()=>typeof window>"u"?"portrait":window.matchMedia?.("(orientation: landscape)")?.matches?"landscape":"portrait";function aJ(){const[e,t]=p.useState(hj);return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(orientation: landscape)"),r=()=>t(n.matches?"landscape":"portrait");return r(),xd(n,r)},[]),e}const pj=600,mj=1e3,n1=()=>{if(typeof window>"u")return{enabled:!1,roomyForPanels:!1};const e=window.innerWidth,t=window.innerHeight,n=LS()||Math.min(e,t)>=pj;return{enabled:n,roomyForPanels:n&&e>t&&e>=mj}},gj=(e,t)=>e.enabled===t.enabled&&e.roomyForPanels===t.roomyForPanels,Vw={enabled:!1,roomyForPanels:!1},Tl=new Set;let Br=null,jo,xi=null;const yj=()=>typeof window>"u"?Vw:(Br||(Br=n1()),Br),vj=()=>{for(const e of Tl)e()},xj=()=>{jo=void 0;const e=n1();Br&&gj(Br,e)||(Br=e,vj())},jf=()=>{typeof window>"u"||jo!==void 0||(jo=window.requestAnimationFrame(xj))},bj=()=>{if(typeof window>"u")return()=>{};Br=n1(),window.addEventListener("resize",jf);const e=typeof window.matchMedia=="function"?window.matchMedia("(orientation: landscape)"):null,t=xd(e,jf);return()=>{window.removeEventListener("resize",jf),t(),jo!==void 0&&(window.cancelAnimationFrame(jo),jo=void 0)}},wj=e=>typeof window>"u"?()=>{}:(Tl.add(e),xi||(xi=bj()),()=>{Tl.delete(e),Tl.size===0&&xi&&(xi(),xi=null,Br=null)});function mu(){return p.useSyncExternalStore(wj,yj,()=>Vw)}function Dn(){return p.useSyncExternalStore(uj,aj,()=>Bw)}const r1=e=>{const t=e;return de(t.directory??null)??de(t.project?.worktree??null)};let qc=null;const cJ=()=>{if(typeof window>"u"||typeof document>"u"||qc)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&RS()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),qc===n&&(qc=null))};return qc=n,n},Sj=(e,t)=>{const n={};return Zu(e.favoriteModels,t.favoriteModels)||(n.favoriteModels=e.favoriteModels),Zu(e.hiddenModels,t.hiddenModels)||(n.hiddenModels=e.hiddenModels),Kg(e.collapsedModelProviders,t.collapsedModelProviders)||(n.collapsedModelProviders=e.collapsedModelProviders),Zu(e.recentModels,t.recentModels)||(n.recentModels=e.recentModels),Kg(e.recentAgents,t.recentAgents)||(n.recentAgents=e.recentAgents),DS(e.recentEfforts,t.recentEfforts)||(n.recentEfforts=e.recentEfforts),n},lJ=()=>{if(typeof window>"u")return()=>{};const e=re.subscribe((t,n)=>{const r=Sj(t,n);Object.keys(r).length!==0&&$r(r).catch(()=>{})});return()=>{e(),PS()}};let Tf=null;const s1=()=>(Tf??=mt(()=>import("./MarkdownRendererImpl-Cn63lAmn.js"),__vite__mapDeps([12,5,1,6,13,14,15,16,17,11,8,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43])).catch(e=>{throw Tf=null,e}),Tf),dJ=()=>{s1().catch(()=>{})},$w={add:'<path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" fill="currentColor"/>',"add-circle":'<path d="M11 11V7H13V11H17V13H13V17H11V13H7V11H11ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20Z" fill="currentColor"/>',"ai-agent":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 14.7096 20.9205 17.1697 19.1709 18.9697C17.3551 20.8376 14.8124 22 12 22C9.18756 22 6.64488 20.8376 4.8291 18.9697C3.07949 17.1697 2 14.7096 2 12C2 6.47715 6.47715 2 12 2ZM12 16C10.0022 16 8.20124 16.8375 6.9248 18.1816C8.30642 19.3175 10.0724 20 12 20C13.9274 20 15.6927 19.3173 17.0742 18.1816C15.7978 16.8377 13.9975 16 12 16ZM12 4C7.58172 4 4 7.58172 4 12C4 13.7701 4.57462 15.4044 5.54785 16.7295C7.1822 15.0483 9.46797 14 12 14C14.5318 14 16.8169 15.0485 18.4512 16.7295C19.4246 15.4043 20 13.7703 20 12C20 7.58172 16.4183 4 12 4ZM11.5293 5.31934C11.7058 4.89329 12.2943 4.89329 12.4707 5.31934L12.7236 5.93066C13.1556 6.97343 13.9615 7.80622 14.9746 8.25684L15.6924 8.5752C16.1029 8.75796 16.1028 9.35627 15.6924 9.53906L14.9326 9.87695C13.9448 10.3163 13.1534 11.1193 12.7139 12.1279L12.4668 12.6934C12.2864 13.1074 11.7137 13.1074 11.5332 12.6934L11.2871 12.1279C10.8476 11.1193 10.0552 10.3163 9.06738 9.87695L8.30762 9.53906C7.89719 9.35628 7.89717 8.75795 8.30762 8.5752L9.02539 8.25684C10.0385 7.80623 10.8445 6.97345 11.2764 5.93066L11.5293 5.31934Z" fill="currentColor"/>',"ai-generate-2":'<path d="M20.4668 8.69379L20.7134 8.12811C21.1529 7.11947 21.9445 6.31641 22.9323 5.87708L23.6919 5.53922C24.1027 5.35653 24.1027 4.75881 23.6919 4.57612L22.9748 4.25714C21.9616 3.80651 21.1558 2.97373 20.7238 1.93083L20.4706 1.31953C20.2942 0.893489 19.7058 0.893489 19.5293 1.31953L19.2761 1.93083C18.8442 2.97373 18.0384 3.80651 17.0252 4.25714L16.308 4.57612C15.8973 4.75881 15.8973 5.35653 16.308 5.53922L17.0677 5.87708C18.0555 6.31641 18.8471 7.11947 19.2866 8.12811L19.5331 8.69379C19.7136 9.10792 20.2864 9.10792 20.4668 8.69379ZM5.79993 16H7.95399L8.55399 14.5H11.4459L12.0459 16H14.1999L10.9999 8H8.99993L5.79993 16ZM9.99993 10.8852L10.6459 12.5H9.35399L9.99993 10.8852ZM15 16V8H17V16H15ZM3 3C2.44772 3 2 3.44772 2 4V20C2 20.5523 2.44772 21 3 21H21C21.5523 21 22 20.5523 22 20V11H20V19H4V5H14V3H3Z" fill="currentColor"/>',alarm:'<path d="M12.0001 22.0001C7.02956 22.0001 3.00012 17.9707 3.00012 13.0001C3.00012 8.02956 7.02956 4.00012 12.0001 4.00012C16.9707 4.00012 21.0001 8.02956 21.0001 13.0001C21.0001 17.9707 16.9707 22.0001 12.0001 22.0001ZM12.0001 20.0001C15.8661 20.0001 19.0001 16.8661 19.0001 13.0001C19.0001 9.13412 15.8661 6.00012 12.0001 6.00012C8.13412 6.00012 5.00012 9.13412 5.00012 13.0001C5.00012 16.8661 8.13412 20.0001 12.0001 20.0001ZM13.0001 13.0001H16.0001V15.0001H11.0001V8.00012H13.0001V13.0001ZM1.74707 6.2826L5.2826 2.74707L6.69682 4.16128L3.16128 7.69682L1.74707 6.2826ZM18.7176 2.74707L22.2532 6.2826L20.839 7.69682L17.3034 4.16128L18.7176 2.74707Z" fill="currentColor"/>',alert:'<path d="M12.8659 3.00017L22.3922 19.5002C22.6684 19.9785 22.5045 20.5901 22.0262 20.8662C21.8742 20.954 21.7017 21.0002 21.5262 21.0002H2.47363C1.92135 21.0002 1.47363 20.5525 1.47363 20.0002C1.47363 19.8246 1.51984 19.6522 1.60761 19.5002L11.1339 3.00017C11.41 2.52187 12.0216 2.358 12.4999 2.63414C12.6519 2.72191 12.7782 2.84815 12.8659 3.00017ZM4.20568 19.0002H19.7941L11.9999 5.50017L4.20568 19.0002ZM10.9999 16.0002H12.9999V18.0002H10.9999V16.0002ZM10.9999 9.00017H12.9999V14.0002H10.9999V9.00017Z" fill="currentColor"/>',"align-justify":'<path d="M3 4H21V6H3V4ZM3 19H21V21H3V19ZM3 14H21V16H3V14ZM3 9H21V11H3V9Z" fill="currentColor"/>',apple:'<path d="M15.778 8.20793C15.3053 8.1711 14.7974 8.28434 14.0197 8.58067C14.085 8.55577 13.2775 8.87173 13.0511 8.95077C12.5494 9.12593 12.1364 9.22198 11.6734 9.22198C11.2151 9.22198 10.7925 9.13042 10.3078 8.96683C10.1524 8.91441 9.99616 8.8564 9.80283 8.7809C9.71993 8.74852 9.41997 8.62947 9.3544 8.60379C8.70626 8.34996 8.34154 8.25434 8.03885 8.26181C6.88626 8.2765 5.79557 8.9421 5.16246 10.0442C3.87037 12.2875 4.58583 16.3428 6.47459 19.075C7.4802 20.5189 8.03062 21.035 8.25199 21.0279C8.4743 21.0183 8.63777 20.9713 9.03567 20.8026C9.11485 20.7689 9.11485 20.7689 9.202 20.7317C10.2077 20.3032 10.9118 20.114 11.9734 20.114C12.9944 20.114 13.6763 20.2997 14.6416 20.7159C14.7302 20.7542 14.7302 20.7542 14.8097 20.7884C15.2074 20.9588 15.3509 20.9962 15.6016 20.9902C15.9591 20.9846 16.4003 20.5726 17.3791 19.1362C17.6471 18.7447 17.884 18.3333 18.0895 17.9168C17.9573 17.8077 17.826 17.6917 17.6975 17.5693C16.4086 16.3408 15.6114 14.6845 15.5895 12.6391C15.5756 11.0186 16.1057 9.61487 16.999 8.45797C16.6293 8.3142 16.2216 8.23805 15.778 8.20793ZM15.9334 6.21398C16.6414 6.26198 18.6694 6.47798 19.9894 8.40998C19.8814 8.46998 17.5654 9.81397 17.5894 12.622C17.6254 15.982 20.5294 17.098 20.5654 17.11C20.5414 17.194 20.0974 18.706 19.0294 20.266C18.1054 21.622 17.1454 22.966 15.6334 22.99C14.1454 23.026 13.6654 22.114 11.9734 22.114C10.2694 22.114 9.74138 22.966 8.33738 23.026C6.87338 23.074 5.76938 21.562 4.83338 20.218C2.92538 17.458 1.47338 12.442 3.42938 9.04597C4.40138 7.35397 6.12938 6.28598 8.01338 6.26198C9.44138 6.22598 10.7974 7.22198 11.6734 7.22198C12.5374 7.22198 14.0854 6.06998 15.9334 6.21398ZM14.7934 4.38998C14.0134 5.32598 12.7414 6.05798 11.5054 5.96198C11.3374 4.68998 11.9614 3.35798 12.6814 2.52998C13.4854 1.59398 14.8294 0.897976 15.9454 0.849976C16.0894 2.14598 15.5734 3.45398 14.7934 4.38998Z" fill="currentColor"/>',"arch-linux":'<path fill="currentColor" d="M12 2.2c-1.06 2.6-1.7 4.3-2.88 6.82.72.76 1.6 1.65 3.04 2.66-1.55-.64-2.61-1.29-3.4-1.96-1.5 3.13-3.83 7.57-6.76 12.08 2.3-1.33 4.09-2.15 5.76-2.47-.08-.35-.13-.73-.12-1.13l.01-.08c.06-2.25 1.23-3.98 2.61-3.87 1.38.1 2.45 2 2.39 4.25-.01.39-.06.76-.14 1.1 1.66.33 3.44 1.15 5.72 2.47-1.16-1.8-2.22-3.62-3.16-5.35-.74-.57-1.51-1.3-2.95-2.04.99.26 1.7.57 2.25.92C13.03 13.04 12.2 11.05 12 10.4c-.2.65-1.03 2.64-2.37 5.2.55-.35 1.26-.66 2.25-.92-1.44.74-2.21 1.47-2.95 2.04A78.9 78.9 0 0 1 5.77 22.07c2.28-1.32 4.06-2.14 5.72-2.47-.08-.34-.13-.71-.14-1.1-.06-2.25 1.01-4.15 2.39-4.25 1.38-.11 2.55 1.62 2.61 3.87l.01.08c.01.4-.04.78-.12 1.13 1.67.32 3.46 1.14 5.76 2.47-2.93-4.51-5.26-8.95-6.76-12.08-.79.67-1.85 1.32-3.4 1.96 1.44-1.01 2.32-1.9 3.04-2.66C13.7 6.5 13.06 4.8 12 2.2Z"/>',archive:'<path d="M3 10H2V4.00293C2 3.44903 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.43788 22 4.00293V10H21V20.0015C21 20.553 20.5551 21 20.0066 21H3.9934C3.44476 21 3 20.5525 3 20.0015V10ZM19 10H5V19H19V10ZM4 5V8H20V5H4ZM9 12H15V14H9V12Z" fill="currentColor"/>',"archive-stack":'<path d="M4 5H20V3H4V5ZM20 9H4V7H20V9ZM3 11H10V13H14V11H21V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V11ZM16 13V15H8V13H5V19H19V13H16Z" fill="currentColor"/>',"arrow-down":'<path d="M13.0001 16.1716L18.3641 10.8076L19.7783 12.2218L12.0001 20L4.22192 12.2218L5.63614 10.8076L11.0001 16.1716V4H13.0001V16.1716Z" fill="currentColor"/>',"arrow-down-s":'<path d="M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z" fill="currentColor"/>',"arrow-go-back":'<path d="M5.82843 6.99955L8.36396 9.53509L6.94975 10.9493L2 5.99955L6.94975 1.0498L8.36396 2.46402L5.82843 4.99955H13C17.4183 4.99955 21 8.58127 21 12.9996C21 17.4178 17.4183 20.9996 13 20.9996H4V18.9996H13C16.3137 18.9996 19 16.3133 19 12.9996C19 9.68584 16.3137 6.99955 13 6.99955H5.82843Z" fill="currentColor"/>',"arrow-go-forward":'<path d="M18.1716 6.99955H11C7.68629 6.99955 5 9.68584 5 12.9996C5 16.3133 7.68629 18.9996 11 18.9996H20V20.9996H11C6.58172 20.9996 3 17.4178 3 12.9996C3 8.58127 6.58172 4.99955 11 4.99955H18.1716L15.636 2.46402L17.0503 1.0498L22 5.99955L17.0503 10.9493L15.636 9.53509L18.1716 6.99955Z" fill="currentColor"/>',"arrow-left":'<path d="M7.82843 10.9999H20V12.9999H7.82843L13.1924 18.3638L11.7782 19.778L4 11.9999L11.7782 4.22168L13.1924 5.63589L7.82843 10.9999Z" fill="currentColor"/>',"arrow-left-right":'<path d="M16.0503 12.0498L21 16.9996L16.0503 21.9493L14.636 20.5351L17.172 17.9988L4 17.9996V15.9996L17.172 15.9988L14.636 13.464L16.0503 12.0498ZM7.94975 2.0498L9.36396 3.46402L6.828 5.9988L20 5.99955V7.99955L6.828 7.9988L9.36396 10.5351L7.94975 11.9493L3 6.99955L7.94975 2.0498Z" fill="currentColor"/>',"arrow-left-s":'<path d="M10.8284 12.0007L15.7782 16.9504L14.364 18.3646L8 12.0007L14.364 5.63672L15.7782 7.05093L10.8284 12.0007Z" fill="currentColor"/>',"arrow-right":'<path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z" fill="currentColor"/>',"arrow-right-s":'<path d="M13.1717 12.0007L8.22192 7.05093L9.63614 5.63672L16.0001 12.0007L9.63614 18.3646L8.22192 16.9504L13.1717 12.0007Z" fill="currentColor"/>',"arrow-up":'<path d="M13.0001 7.82843V20H11.0001V7.82843L5.63614 13.1924L4.22192 11.7782L12.0001 4L19.7783 11.7782L18.3641 13.1924L13.0001 7.82843Z" fill="currentColor"/>',"arrow-up-double":'<path d="M12 4.83582L5.79291 11.0429L7.20712 12.4571L12 7.66424L16.7929 12.4571L18.2071 11.0429L12 4.83582ZM12 10.4857L5.79291 16.6928L7.20712 18.107L12 13.3141L16.7929 18.107L18.2071 16.6928L12 10.4857Z" fill="currentColor"/>',"arrow-up-s":'<path d="M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z" fill="currentColor"/>',"attachment-2":'<path d="M14.8287 7.75737L9.1718 13.4142C8.78127 13.8047 8.78127 14.4379 9.1718 14.8284C9.56232 15.219 10.1955 15.219 10.586 14.8284L16.2429 9.17158C17.4144 8.00001 17.4144 6.10052 16.2429 4.92894C15.0713 3.75737 13.1718 3.75737 12.0002 4.92894L6.34337 10.5858C4.39075 12.5384 4.39075 15.7042 6.34337 17.6569C8.29599 19.6095 11.4618 19.6095 13.4144 17.6569L19.0713 12L20.4855 13.4142L14.8287 19.0711C12.095 21.8047 7.66283 21.8047 4.92916 19.0711C2.19549 16.3374 2.19549 11.9053 4.92916 9.17158L10.586 3.51473C12.5386 1.56211 15.7045 1.56211 17.6571 3.51473C19.6097 5.46735 19.6097 8.63317 17.6571 10.5858L12.0002 16.2427C10.8287 17.4142 8.92916 17.4142 7.75759 16.2427C6.58601 15.0711 6.58601 13.1716 7.75759 12L13.4144 6.34316L14.8287 7.75737Z" fill="currentColor"/>',book:'<path d="M3 18.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22H6.5C4.567 22 3 20.433 3 18.5ZM19 20V17H6.5C5.67157 17 5 17.6716 5 18.5C5 19.3284 5.67157 20 6.5 20H19ZM5 15.3368C5.45463 15.1208 5.9632 15 6.5 15H19V4H6C5.44772 4 5 4.44772 5 5V15.3368Z" fill="currentColor"/>',"book-open":'<path d="M13 21V23H11V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H9C10.1947 3 11.2671 3.52375 12 4.35418C12.7329 3.52375 13.8053 3 15 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H13ZM20 19V5H15C13.8954 5 13 5.89543 13 7V19H20ZM11 19V7C11 5.89543 10.1046 5 9 5H4V19H11Z" fill="currentColor"/>',brain:'<path d="M9 4C10.1046 4 11 4.89543 11 6V12.8271C10.1058 12.1373 8.96602 11.7305 7.6644 11.5136L7.3356 13.4864C8.71622 13.7165 9.59743 14.1528 10.1402 14.7408C10.67 15.3147 11 16.167 11 17.5C11 18.8807 9.88071 20 8.5 20C7.11929 20 6 18.8807 6 17.5V17.1493C6.43007 17.2926 6.87634 17.4099 7.3356 17.4864L7.6644 15.5136C6.92149 15.3898 6.1752 15.1144 5.42909 14.7599C4.58157 14.3573 4 13.499 4 12.5C4 11.6653 4.20761 11.0085 4.55874 10.5257C4.90441 10.0504 5.4419 9.6703 6.24254 9.47014L7 9.28078V6C7 4.89543 7.89543 4 9 4ZM12 3.35418C11.2671 2.52376 10.1947 2 9 2C6.79086 2 5 3.79086 5 6V7.77422C4.14895 8.11644 3.45143 8.64785 2.94126 9.34933C2.29239 10.2415 2 11.3347 2 12.5C2 14.0652 2.79565 15.4367 4 16.2422V17.5C4 19.9853 6.01472 22 8.5 22C9.91363 22 11.175 21.3482 12 20.3287C12.825 21.3482 14.0864 22 15.5 22C17.9853 22 20 19.9853 20 17.5V16.2422C21.2044 15.4367 22 14.0652 22 12.5C22 11.3347 21.7076 10.2415 21.0587 9.34933C20.5486 8.64785 19.8511 8.11644 19 7.77422V6C19 3.79086 17.2091 2 15 2C13.8053 2 12.7329 2.52376 12 3.35418ZM18 17.1493V17.5C18 18.8807 16.8807 20 15.5 20C14.1193 20 13 18.8807 13 17.5C13 16.167 13.33 15.3147 13.8598 14.7408C14.4026 14.1528 15.2838 13.7165 16.6644 13.4864L16.3356 11.5136C15.034 11.7305 13.8942 12.1373 13 12.8271V6C13 4.89543 13.8954 4 15 4C16.1046 4 17 4.89543 17 6V9.28078L17.7575 9.47014C18.5581 9.6703 19.0956 10.0504 19.4413 10.5257C19.7924 11.0085 20 11.6653 20 12.5C20 13.499 19.4184 14.3573 18.5709 14.7599C17.8248 15.1144 17.0785 15.3898 16.3356 15.5136L16.6644 17.4864C17.1237 17.4099 17.5699 17.2926 18 17.1493Z" fill="currentColor"/>',"brain-ai-3":'<path d="M19.5 4.7832V7.6709L22 9.11426V14.8867L19.499 16.3311L19.5 19.2178L14.5 22.1045L12 20.6611L9.5 22.1045L4.5 19.2178V16.3311L2 14.8877L2.00098 9.11328L4.5 7.66992V4.78418L9.5 1.89746L11.999 3.34082L14.501 1.89648L19.5 4.7832ZM13 5.07227V7H11V5.07324L9.5 4.20703L6.49902 5.93848V8.8252L4 10.2676V13.7334L6.5 15.1768V18.0635L9.5 19.7959L11 18.9287V17H13V18.9297L14.5 19.7959L17.5 18.0625V15.1768L20 13.7324V10.2695L17.499 8.8252L17.5 5.9375L14.501 4.20605L13 5.07227ZM14.2646 13.1602C14.3529 12.9473 14.6472 12.9473 14.7354 13.1602L14.8623 13.4648C15.0783 13.986 15.4807 14.4027 15.9873 14.6279L16.3457 14.7871C16.5511 14.8784 16.5511 15.1773 16.3457 15.2686L15.9658 15.4375C15.4721 15.6571 15.0761 16.0586 14.8564 16.5625L14.7334 16.8447C14.6432 17.0517 14.3569 17.0517 14.2666 16.8447L14.1436 16.5625C13.9239 16.0586 13.5279 15.6571 13.0342 15.4375L12.6543 15.2686C12.4489 15.1773 12.4489 14.8784 12.6543 14.7871L13.0127 14.6279C13.5193 14.4027 13.9217 13.986 14.1377 13.4648L14.2646 13.1602ZM9.58789 7.7793C9.74239 7.40671 10.2577 7.4067 10.4121 7.7793L10.6338 8.31445C11.0118 9.22695 11.7161 9.95624 12.6025 10.3506L13.2305 10.6289C13.5899 10.7887 13.5897 11.3117 13.2305 11.4717L12.5654 11.7676C11.7013 12.152 11.0086 12.8548 10.624 13.7373L10.4082 14.2324C10.2504 14.5948 9.74973 14.5948 9.5918 14.2324L9.37598 13.7373C8.99143 12.8548 8.29875 12.152 7.43457 11.7676L6.76953 11.4717C6.41033 11.3117 6.41022 10.7887 6.76953 10.6289L7.39746 10.3506C8.2839 9.95624 8.98832 9.22697 9.36621 8.31445L9.58789 7.7793Z" fill="currentColor"/>',brush:'<path d="M15.4565 9.67503L15.3144 9.53297C14.6661 8.90796 13.8549 8.43369 12.9235 8.18412C10.0168 7.40527 7.22541 9.05273 6.43185 12.0143C6.38901 12.1742 6.36574 12.3537 6.3285 12.8051C6.17423 14.6752 5.73449 16.0697 4.5286 17.4842C6.78847 18.3727 9.46572 18.9986 11.5016 18.9986C13.9702 18.9986 16.1644 17.3394 16.8126 14.9202C17.3306 12.9869 16.7513 11.0181 15.4565 9.67503ZM13.2886 6.21301L18.2278 2.37142C18.6259 2.0618 19.1922 2.09706 19.5488 2.45367L22.543 5.44787C22.8997 5.80448 22.9349 6.37082 22.6253 6.76891L18.7847 11.7068C19.0778 12.8951 19.0836 14.1721 18.7444 15.4379C17.8463 18.7897 14.8142 20.9986 11.5016 20.9986C8 20.9986 3.5 19.4967 1 17.9967C4.97978 14.9967 4.04722 13.1865 4.5 11.4967C5.55843 7.54658 9.34224 5.23935 13.2886 6.21301ZM16.7015 8.09161C16.7673 8.15506 16.8319 8.21964 16.8952 8.28533L18.0297 9.41984L20.5046 6.23786L18.7589 4.4921L15.5769 6.96698L16.7015 8.09161Z" fill="currentColor"/>',bug:'<path d="M13 19.9C15.2822 19.4367 17 17.419 17 15V12C17 11.299 16.8564 10.6219 16.5846 10H7.41538C7.14358 10.6219 7 11.299 7 12V15C7 17.419 8.71776 19.4367 11 19.9V14H13V19.9ZM5.5358 17.6907C5.19061 16.8623 5 15.9534 5 15H2V13H5V12C5 11.3573 5.08661 10.7348 5.2488 10.1436L3.0359 8.86602L4.0359 7.13397L6.05636 8.30049C6.11995 8.19854 6.18609 8.09835 6.25469 8H17.7453C17.8139 8.09835 17.88 8.19854 17.9436 8.30049L19.9641 7.13397L20.9641 8.86602L18.7512 10.1436C18.9134 10.7348 19 11.3573 19 12V13H22V15H19C19 15.9534 18.8094 16.8623 18.4642 17.6907L20.9641 19.134L19.9641 20.866L17.4383 19.4077C16.1549 20.9893 14.1955 22 12 22C9.80453 22 7.84512 20.9893 6.56171 19.4077L4.0359 20.866L3.0359 19.134L5.5358 17.6907ZM8 6C8 3.79086 9.79086 2 12 2C14.2091 2 16 3.79086 16 6H8Z" fill="currentColor"/>',"centos-fill":'<path d="M12 13.0607L16.47 17.531L12 22L7.53 17.53L12 13.0607ZM3.99968 16.1207L7.87868 19.9997L4 20L3.99968 16.1207ZM19.9997 16.1207L20 20L16.1207 19.9997L19.9997 16.1207ZM17.53 7.53L22 12L17.531 16.47L13.0607 12L17.53 7.53ZM6.47 7.53L10.9393 12L6.469 16.469L2 12L6.47 7.53ZM12 2L16.469 6.469L12 10.9393L7.53 6.47L12 2ZM7.87868 3.99968L3.99968 7.87868L4 4L7.87868 3.99968ZM20 4L19.9997 7.87868L16.1207 3.99968L20 4Z" fill="currentColor"/>',"chat-1":'<path d="M10 3H14C18.4183 3 22 6.58172 22 11C22 15.4183 18.4183 19 14 19V22.5C9 20.5 2 17.5 2 11C2 6.58172 5.58172 3 10 3ZM12 17H14C17.3137 17 20 14.3137 20 11C20 7.68629 17.3137 5 14 5H10C6.68629 5 4 7.68629 4 11C4 14.61 6.46208 16.9656 12 19.4798V17Z" fill="currentColor"/>',"chat-3":'<path d="M7.29117 20.8242L2 22L3.17581 16.7088C2.42544 15.3056 2 13.7025 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.6944 21.5746 7.29117 20.8242ZM7.58075 18.711L8.23428 19.0605C9.38248 19.6745 10.6655 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 13.3345 4.32549 14.6175 4.93949 15.7657L5.28896 16.4192L4.63416 19.3658L7.58075 18.711Z" fill="currentColor"/>',"chat-4":'<path d="M5.76282 17H20V5H4V18.3851L5.76282 17ZM6.45455 19L2 22.5V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V18C22 18.5523 21.5523 19 21 19H6.45455Z" fill="currentColor"/>',"chat-ai-3":'<path d="M12 1.99996C12.8632 1.99996 13.701 2.10973 14.5 2.31539L14 4.25192C13.3608 4.0874 12.6906 3.99997 12 3.99997C7.58174 3.99997 4.00002 7.58172 4 12C4 13.3344 4.3255 14.6174 4.93945 15.7656L5.28906 16.4189L4.63379 19.3662L7.58105 18.7109L8.23438 19.0605C9.38255 19.6745 10.6656 20 12 20C16.4183 20 20 16.4183 20 12C20 11.6771 19.9805 11.3587 19.9434 11.0459L21.9297 10.8095C21.976 11.1999 22 11.5972 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.69425 21.5746 7.29102 20.8242L2 22L3.17578 16.709C2.42541 15.3057 2 13.7025 2 12C2.00002 6.47714 6.47717 1.99996 12 1.99996ZM19.5293 1.3193C19.7058 0.893513 20.2942 0.8935 20.4707 1.3193L20.7236 1.93063C21.1555 2.97343 21.9615 3.80614 22.9746 4.2568L23.6914 4.57614C24.1022 4.75882 24.1022 5.35635 23.6914 5.53903L22.9326 5.87692C21.945 6.3162 21.1534 7.11943 20.7139 8.1279L20.4668 8.69333C20.2863 9.10747 19.7136 9.10747 19.5332 8.69333L19.2861 8.1279C18.8466 7.11942 18.0551 6.3162 17.0674 5.87692L16.3076 5.53903C15.8974 5.35618 15.8974 4.75895 16.3076 4.57614L17.0254 4.2568C18.0384 3.80614 18.8445 2.97343 19.2764 1.93063L19.5293 1.3193Z" fill="currentColor"/>',"chat-history":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.298 22 8.69525 21.5748 7.29229 20.8248L2 22L3.17629 16.7097C2.42562 15.3063 2 13.7028 2 12C2 6.47715 6.47715 2 12 2ZM12 4C7.58172 4 4 7.58172 4 12C4 13.3347 4.32563 14.6181 4.93987 15.7664L5.28952 16.4201L4.63445 19.3663L7.58189 18.7118L8.23518 19.061C9.38315 19.6747 10.6659 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4ZM13 7V12H17V14H11V7H13Z" fill="currentColor"/>',"chat-new":'<path d="M14 3V5H4V18.3851L5.76282 17H20V10H22V18C22 18.5523 21.5523 19 21 19H6.45455L2 22.5V4C2 3.44772 2.44772 3 3 3H14ZM19 3V0H21V3H24V5H21V8H19V5H16V3H19Z" fill="currentColor"/>',check:'<path d="M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" fill="currentColor"/>',checkbox:'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5ZM11.0026 16L6.75999 11.7574L8.17421 10.3431L11.0026 13.1716L16.6595 7.51472L18.0737 8.92893L11.0026 16Z" fill="currentColor"/>',"checkbox-blank":'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5Z" fill="currentColor"/>',"checkbox-blank-circle-fill":'<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" fill="currentColor"/>',"checkbox-circle":'<path d="M4 12C4 7.58172 7.58172 4 12 4C16.4183 4 20 7.58172 20 12C20 16.4183 16.4183 20 12 20C7.58172 20 4 16.4183 4 12ZM12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2ZM17.4571 9.45711L16.0429 8.04289L11 13.0858L8.20711 10.2929L6.79289 11.7071L11 15.9142L17.4571 9.45711Z" fill="currentColor"/>',"checkbox-multiple":'<path d="M6.99979 7V3C6.99979 2.44772 7.4475 2 7.99979 2H20.9998C21.5521 2 21.9998 2.44772 21.9998 3V16C21.9998 16.5523 21.5521 17 20.9998 17H17V20.9925C17 21.5489 16.551 22 15.9925 22H3.00728C2.45086 22 2 21.5511 2 20.9925L2.00276 8.00748C2.00288 7.45107 2.4518 7 3.01025 7H6.99979ZM8.99979 7H15.9927C16.549 7 17 7.44892 17 8.00748V15H19.9998V4H8.99979V7ZM15 9H4.00255L4.00021 20H15V9ZM8.50242 18L4.96689 14.4645L6.3811 13.0503L8.50242 15.1716L12.7451 10.9289L14.1593 12.3431L8.50242 18Z" fill="currentColor"/>',clipboard:'<path d="M7 4V2H17V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7ZM7 6H5V20H19V6H17V8H7V6ZM9 4V6H15V4H9Z" fill="currentColor"/>',close:'<path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z" fill="currentColor"/>',"close-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z" fill="currentColor"/>',cloud:'<path d="M12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 18.3137 20.3137 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 5.13401 8.13401 2 12 2ZM12 4C9.23858 4 7 6.23858 7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C19.2091 19 21 17.2091 21 15C21 12.79 19.21 11 17 11C15.233 11 13.7337 12.1457 13.2042 13.7347L11.3064 13.1021C12.1005 10.7185 14.35 9 17 9C17 6.23858 14.7614 4 12 4Z" fill="currentColor"/>',"cloud-off":'<path d="M3.51472 2.10051L22.6066 21.1924L21.1924 22.6066L19.1782 20.5924C18.503 20.8556 17.7684 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 8.22228 5.12683 7.47418 5.36094 6.77527L2.10051 3.51472L3.51472 2.10051ZM7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C17.1858 19 17.3687 18.9873 17.5478 18.9628L7.03043 8.44519C7.01032 8.62736 7 8.81247 7 9ZM12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 16.0883 22.7103 17.1089 22.2037 17.9889L20.7111 16.4955C20.8974 16.0335 21 15.5287 21 15C21 12.79 19.21 11 17 11C16.4711 11 15.9661 11.1027 15.5039 11.2892L14.0111 9.7964C14.8912 9.28978 15.9118 9 17 9C17 6.23858 14.7614 4 12 4C10.9295 4 9.93766 4.33639 9.12428 4.90922L7.69418 3.48056C8.88169 2.55284 10.3763 2 12 2Z" fill="currentColor"/>',code:'<path d="M23 12L15.9289 19.0711L14.5147 17.6569L20.1716 12L14.5147 6.34317L15.9289 4.92896L23 12ZM3.82843 12L9.48528 17.6569L8.07107 19.0711L1 12L8.07107 4.92896L9.48528 6.34317L3.82843 12Z" fill="currentColor"/>',"code-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM20 12L16.4645 15.5355L15.0503 14.1213L17.1716 12L15.0503 9.87868L16.4645 8.46447L20 12ZM6.82843 12L8.94975 14.1213L7.53553 15.5355L4 12L7.53553 8.46447L8.94975 9.87868L6.82843 12ZM11.2443 17H9.11597L12.7557 7H14.884L11.2443 17Z" fill="currentColor"/>',"code-sslash":'<path d="M24 12L18.3431 17.6569L16.9289 16.2426L21.1716 12L16.9289 7.75736L18.3431 6.34315L24 12ZM2.82843 12L7.07107 16.2426L5.65685 17.6569L0 12L5.65685 6.34315L7.07107 7.75736L2.82843 12ZM9.78845 21H7.66009L14.2116 3H16.3399L9.78845 21Z" fill="currentColor"/>',"collapse-vertical":'<path d="M11.9995 13.4995 16.9492 18.4493 15.535 19.8635 12.9995 17.3279 12.9995 22.9995H10.9995L10.9995 17.3279 8.46643 19.861 7.05222 18.4468 11.9995 13.4995ZM10.9995.999512 10.9995 6.67035 8.46448 4.13535 7.05026 5.54956 12 10.4995 16.9497 5.54977 15.5355 4.13555 12.9995 6.67157V.999512L10.9995.999512Z" fill="currentColor"/>',command:'<path d="M10 8H14V6.5C14 4.567 15.567 3 17.5 3C19.433 3 21 4.567 21 6.5C21 8.433 19.433 10 17.5 10H16V14H17.5C19.433 14 21 15.567 21 17.5C21 19.433 19.433 21 17.5 21C15.567 21 14 19.433 14 17.5V16H10V17.5C10 19.433 8.433 21 6.5 21C4.567 21 3 19.433 3 17.5C3 15.567 4.567 14 6.5 14H8V10H6.5C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5V8ZM8 8V6.5C8 5.67157 7.32843 5 6.5 5C5.67157 5 5 5.67157 5 6.5C5 7.32843 5.67157 8 6.5 8H8ZM8 16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19C7.32843 19 8 18.3284 8 17.5V16ZM16 8H17.5C18.3284 8 19 7.32843 19 6.5C19 5.67157 18.3284 5 17.5 5C16.6716 5 16 5.67157 16 6.5V8ZM16 16V17.5C16 18.3284 16.6716 19 17.5 19C18.3284 19 19 18.3284 19 17.5C19 16.6716 18.3284 16 17.5 16H16ZM10 10V14H14V10H10Z" fill="currentColor"/>',"compass-3":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM16.5 7.5L14 14L7.5 16.5L10 10L16.5 7.5ZM12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z" fill="currentColor"/>',cursor:'<path d="M15.3873 13.4975L17.9403 20.5117L13.2418 22.2218L10.6889 15.2076L6.79004 17.6529L8.4086 1.63318L19.9457 12.8646L15.3873 13.4975ZM15.3768 19.3163L12.6618 11.8568L15.6212 11.4459L9.98201 5.9561L9.19088 13.7863L11.7221 12.1988L14.4371 19.6583L15.3768 19.3163Z" fill="currentColor"/>',debian:'<path fill="currentColor" d="M13.7 3.1c-2.8-.8-6.2.2-7.7 2.4 1.9-1.5 4.6-2 6.7-1.2 2.9 1.1 4.3 4.1 3.2 6.8-.9 2.2-3.1 3.6-5.3 3.4-1.8-.1-3.3-1.2-3.8-2.7-.5-1.4 0-2.9 1.2-3.7 1-.7 2.4-.7 3.3.1.7.6.9 1.6.5 2.4-.3.6-.9 1-1.5.9-.5 0-.9-.4-1-.8-.1-.4.1-.8.4-1 .3-.2.6-.1.8.1-.1-.5-.7-.8-1.2-.6-.7.2-1.1.9-1 1.6.1 1 1 1.7 2 1.8 1.2.1 2.4-.6 2.9-1.7.7-1.5.2-3.3-1.1-4.3-1.6-1.3-4-1.3-5.7-.1-2.1 1.5-2.9 4.2-2 6.6 1 2.7 3.6 4.5 6.6 4.7 3.8.2 7.4-2.1 8.8-5.6 1.7-4.2-.6-7.8-4.1-9.1Z"/>',"delete-bin":'<path d="M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM18 8H6V20H18V8ZM9 11H11V17H9V11ZM13 11H15V17H13V11ZM9 4V6H15V4H9Z" fill="currentColor"/>',docker:'<path fill="currentColor" d="M13.98 11.08h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm5.06-2.3h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm2.53-2.3h2.12v-1.9H8.92v1.9ZM3.86 11.08h2.12v-1.9H3.86v1.9Zm17.9-.13c-.46-.3-1.52-.42-2.31-.27-.1-.78-.54-1.46-1.34-2.08l-.46-.3-.31.45c-.62.93-.79 2.46-.12 3.47-.3.16-.89.38-1.68.36H2.11c-.27 1.57.18 3.63 1.36 5.05 1.15 1.38 2.88 2.08 5.15 2.08 4.92 0 8.57-2.27 10.28-6.39.67.01 2.11 0 2.85-1.42.05-.09.23-.46.3-.61l-.29-.34Z"/>',"donut-chart":'<path d="M10.9999 2.04938L11 4.06188C7.05371 4.55396 4 7.92036 4 12C4 16.4183 7.58172 20 12 20C13.8487 20 15.5509 19.3729 16.9055 18.3199L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L18.3199 16.9055C19.1801 15.799 19.756 14.4606 19.9381 12.9999L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L19.9381 11C19.4869 7.38162 16.6192 4.51364 13.001 4.062L13.0011 2.04948Z" fill="currentColor"/>',"donut-chart-fill":'<path d="M10.9999 2.04938L11 5.07088C7.6077 5.55612 5 8.47352 5 12C5 15.866 8.13401 19 12 19C13.5723 19 15.0236 18.4816 16.1922 17.6064L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L17.6064 16.1922C18.2926 15.2759 18.7595 14.1859 18.9291 13L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L18.9291 10.9998C18.4905 7.93452 16.0661 5.50992 13.001 5.07103L13.0011 2.04948Z" fill="currentColor"/>',download:'<path d="M3 19H21V21H3V19ZM13 13.1716L19.0711 7.1005L20.4853 8.51472L12 17L3.51472 8.51472L4.92893 7.1005L11 13.1716V2H13V13.1716Z" fill="currentColor"/>',"download-cloud":'<path d="M1 14.5C1 12.1716 2.22429 10.1291 4.06426 8.9812C4.56469 5.044 7.92686 2 12 2C16.0731 2 19.4353 5.044 19.9357 8.9812C21.7757 10.1291 23 12.1716 23 14.5C23 17.9216 20.3562 20.7257 17 20.9811L7 21C3.64378 20.7257 1 17.9216 1 14.5ZM16.8483 18.9868C19.1817 18.8093 21 16.8561 21 14.5C21 12.927 20.1884 11.4962 18.8771 10.6781L18.0714 10.1754L17.9517 9.23338C17.5735 6.25803 15.0288 4 12 4C8.97116 4 6.42647 6.25803 6.0483 9.23338L5.92856 10.1754L5.12288 10.6781C3.81156 11.4962 3 12.927 3 14.5C3 16.8561 4.81833 18.8093 7.1517 18.9868L7.325 19H16.675L16.8483 18.9868ZM13 12H16L12 17L8 12H11V8H13V12Z" fill="currentColor"/>',draggable:'<path d="M8.5 7C9.32843 7 10 6.32843 10 5.5C10 4.67157 9.32843 4 8.5 4C7.67157 4 7 4.67157 7 5.5C7 6.32843 7.67157 7 8.5 7ZM8.5 13.5C9.32843 13.5 10 12.8284 10 12C10 11.1716 9.32843 10.5 8.5 10.5C7.67157 10.5 7 11.1716 7 12C7 12.8284 7.67157 13.5 8.5 13.5ZM10 18.5C10 19.3284 9.32843 20 8.5 20C7.67157 20 7 19.3284 7 18.5C7 17.6716 7.67157 17 8.5 17C9.32843 17 10 17.6716 10 18.5ZM15.5 7C16.3284 7 17 6.32843 17 5.5C17 4.67157 16.3284 4 15.5 4C14.6716 4 14 4.67157 14 5.5C14 6.32843 14.6716 7 15.5 7ZM17 12C17 12.8284 16.3284 13.5 15.5 13.5C14.6716 13.5 14 12.8284 14 12C14 11.1716 14.6716 10.5 15.5 10.5C16.3284 10.5 17 11.1716 17 12ZM15.5 20C16.3284 20 17 19.3284 17 18.5C17 17.6716 16.3284 17 15.5 17C14.6716 17 14 17.6716 14 18.5C14 19.3284 14.6716 20 15.5 20Z" fill="currentColor"/>',edit:'<path d="M6.41421 15.89L16.5563 5.74785L15.1421 4.33363L5 14.4758V15.89H6.41421ZM7.24264 17.89H3V13.6473L14.435 2.21231C14.8256 1.82179 15.4587 1.82179 15.8492 2.21231L18.6777 5.04074C19.0682 5.43126 19.0682 6.06443 18.6777 6.45495L7.24264 17.89ZM3 19.89H21V21.89H3V19.89Z" fill="currentColor"/>',equalizer:'<path d="M6.17071 18C6.58254 16.8348 7.69378 16 9 16C10.3062 16 11.4175 16.8348 11.8293 18H22V20H11.8293C11.4175 21.1652 10.3062 22 9 22C7.69378 22 6.58254 21.1652 6.17071 20H2V18H6.17071ZM12.1707 11C12.5825 9.83481 13.6938 9 15 9C16.3062 9 17.4175 9.83481 17.8293 11H22V13H17.8293C17.4175 14.1652 16.3062 15 15 15C13.6938 15 12.5825 14.1652 12.1707 13H2V11H12.1707ZM6.17071 4C6.58254 2.83481 7.69378 2 9 2C10.3062 2 11.4175 2.83481 11.8293 4H22V6H11.8293C11.4175 7.16519 10.3062 8 9 8C7.69378 8 6.58254 7.16519 6.17071 6H2V4H6.17071ZM9 6C9.55228 6 10 5.55228 10 5C10 4.44772 9.55228 4 9 4C8.44772 4 8 4.44772 8 5C8 5.55228 8.44772 6 9 6ZM15 13C15.5523 13 16 12.5523 16 12C16 11.4477 15.5523 11 15 11C14.4477 11 14 11.4477 14 12C14 12.5523 14.4477 13 15 13ZM9 20C9.55228 20 10 19.5523 10 19C10 18.4477 9.55228 18 9 18C8.44772 18 8 18.4477 8 19C8 19.5523 8.44772 20 9 20Z" fill="currentColor"/>',"error-warning":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM11 7H13V13H11V7Z" fill="currentColor"/>',"expand-up-down":'<path d="M18.2072 9.0428 12.0001 2.83569 5.793 9.0428 7.20721 10.457 12.0001 5.66412 16.793 10.457 18.2072 9.0428ZM5.79285 14.9572 12 21.1643 18.2071 14.9572 16.7928 13.543 12 18.3359 7.20706 13.543 5.79285 14.9572Z" fill="currentColor"/>',"external-link":'<path d="M10 6V8H5V19H16V14H18V20C18 20.5523 17.5523 21 17 21H4C3.44772 21 3 20.5523 3 20V7C3 6.44772 3.44772 6 4 6H10ZM21 3V11H19L18.9999 6.413L11.2071 14.2071L9.79289 12.7929L17.5849 5H13V3H21Z" fill="currentColor"/>',eye:'<path d="M12.0003 3C17.3924 3 21.8784 6.87976 22.8189 12C21.8784 17.1202 17.3924 21 12.0003 21C6.60812 21 2.12215 17.1202 1.18164 12C2.12215 6.87976 6.60812 3 12.0003 3ZM12.0003 19C16.2359 19 19.8603 16.052 20.7777 12C19.8603 7.94803 16.2359 5 12.0003 5C7.7646 5 4.14022 7.94803 3.22278 12C4.14022 16.052 7.7646 19 12.0003 19ZM12.0003 16.5C9.51498 16.5 7.50026 14.4853 7.50026 12C7.50026 9.51472 9.51498 7.5 12.0003 7.5C14.4855 7.5 16.5003 9.51472 16.5003 12C16.5003 14.4853 14.4855 16.5 12.0003 16.5ZM12.0003 14.5C13.381 14.5 14.5003 13.3807 14.5003 12C14.5003 10.6193 13.381 9.5 12.0003 9.5C10.6196 9.5 9.50026 10.6193 9.50026 12C9.50026 13.3807 10.6196 14.5 12.0003 14.5Z" fill="currentColor"/>',"eye-off":'<path d="M17.8827 19.2968C16.1814 20.3755 14.1638 21.0002 12.0003 21.0002C6.60812 21.0002 2.12215 17.1204 1.18164 12.0002C1.61832 9.62282 2.81932 7.5129 4.52047 5.93457L1.39366 2.80777L2.80788 1.39355L22.6069 21.1925L21.1927 22.6068L17.8827 19.2968ZM5.9356 7.3497C4.60673 8.56015 3.6378 10.1672 3.22278 12.0002C4.14022 16.0521 7.7646 19.0002 12.0003 19.0002C13.5997 19.0002 15.112 18.5798 16.4243 17.8384L14.396 15.8101C13.7023 16.2472 12.8808 16.5002 12.0003 16.5002C9.51498 16.5002 7.50026 14.4854 7.50026 12.0002C7.50026 11.1196 7.75317 10.2981 8.19031 9.60442L5.9356 7.3497ZM12.9139 14.328L9.67246 11.0866C9.5613 11.3696 9.50026 11.6777 9.50026 12.0002C9.50026 13.3809 10.6196 14.5002 12.0003 14.5002C12.3227 14.5002 12.6309 14.4391 12.9139 14.328ZM20.8068 16.5925L19.376 15.1617C20.0319 14.2268 20.5154 13.1586 20.7777 12.0002C19.8603 7.94818 16.2359 5.00016 12.0003 5.00016C11.1544 5.00016 10.3329 5.11773 9.55249 5.33818L7.97446 3.76015C9.22127 3.26959 10.5793 3.00016 12.0003 3.00016C17.3924 3.00016 21.8784 6.87992 22.8189 12.0002C22.5067 13.6998 21.8038 15.2628 20.8068 16.5925ZM11.7229 7.50857C11.8146 7.50299 11.9071 7.50016 12.0003 7.50016C14.4855 7.50016 16.5003 9.51488 16.5003 12.0002C16.5003 12.0933 16.4974 12.1858 16.4919 12.2775L11.7229 7.50857Z" fill="currentColor"/>',fedora:'<path fill="currentColor" d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2Zm2.9 5.2h-1.35c-.83 0-1.5.67-1.5 1.5v1.35h2.35v2h-2.35v4.15a2.8 2.8 0 0 1-2.8 2.8 2.8 2.8 0 0 1-2.8-2.8c0-1.55 1.25-2.8 2.8-2.8h.8v2h-.8a.8.8 0 1 0 .8.8V8.7a3.5 3.5 0 0 1 3.5-3.5h1.35v2Z"/>',file:'<path d="M9 2.00318V2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9 2.00318ZM5.82918 8H9V4.83086L5.82918 8ZM11 4V9C11 9.55228 10.5523 10 10 10H5V20H19V4H11Z" fill="currentColor"/>',"file-add":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 11V8H13V11H16V13H13V16H11V13H8V11H11Z" fill="currentColor"/>',"file-check":'<path d="M12 20V22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9998 7V14H19V8H15V4H5V20H12ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-check-fill":'<path d="M20.9998 7L16 2H3.9985C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H12.3414C12.1203 21.3744 12 20.7013 12 20C12 16.6863 14.6863 14 18 14C19.0928 14 20.1174 14.2922 20.9999 14.8026L20.9998 7ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-code":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM17.6569 12L14.1213 15.5355L12.7071 14.1213L14.8284 12L12.7071 9.87868L14.1213 8.46447L17.6569 12ZM6.34315 12L9.87868 8.46447L11.2929 9.87868L9.17157 12L11.2929 14.1213L9.87868 15.5355L6.34315 12Z" fill="currentColor"/>',"file-copy":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6Z" fill="currentColor"/>',"file-copy-2":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6ZM7 11H13V13H7V11ZM7 15H13V17H7V15Z" fill="currentColor"/>',"file-download":'<path d="M13 12H16L12 16L8 12H11V8H13V12ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-edit":'<path d="M21 6.75736L19 8.75736V4H10V9H5V20H19V17.2426L21 15.2426V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V6.75736ZM21.7782 8.80761L23.1924 10.2218L15.4142 18L13.9979 17.9979L14 16.5858L21.7782 8.80761Z" fill="currentColor"/>',"file-image":'<path d="M15 8V4H5V20H19V8H15ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 9.5C11 10.3284 10.3284 11 9.5 11C8.67157 11 8 10.3284 8 9.5C8 8.67157 8.67157 8 9.5 8C10.3284 8 11 8.67157 11 9.5ZM17.5 17L13.5 10L8 17H17.5Z" fill="currentColor"/>',"file-list-2":'<path d="M20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22ZM19 20V4H5V20H19ZM8 7H16V9H8V7ZM8 11H16V13H8V11ZM8 15H13V17H8V15Z" fill="currentColor"/>',"file-music":'<path d="M16 8V10H13V14.5C13 15.8807 11.8807 17 10.5 17C9.11929 17 8 15.8807 8 14.5C8 13.1193 9.11929 12 10.5 12C10.6712 12 10.8384 12.0172 11 12.05V8H15V4H5V20H19V8H16ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-pdf":'<path d="M12 16H8V8H12C14.2091 8 16 9.79086 16 12C16 14.2091 14.2091 16 12 16ZM10 10V14H12C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10H10ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-search":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM13.529 14.4464C11.9951 15.3524 9.98633 15.1464 8.66839 13.8284C7.1063 12.2663 7.1063 9.73367 8.66839 8.17157C10.2305 6.60948 12.7631 6.60948 14.3252 8.17157C15.6432 9.48951 15.8492 11.4983 14.9432 13.0322L17.1537 15.2426L15.7395 16.6569L13.529 14.4464ZM12.911 12.4142C13.6921 11.6332 13.6921 10.3668 12.911 9.58579C12.13 8.80474 10.8637 8.80474 10.0826 9.58579C9.30156 10.3668 9.30156 11.6332 10.0826 12.4142C10.8637 13.1953 12.13 13.1953 12.911 12.4142Z" fill="currentColor"/>',"file-text":'<path d="M21 8V20.9932C21 21.5501 20.5552 22 20.0066 22H3.9934C3.44495 22 3 21.556 3 21.0082V2.9918C3 2.45531 3.4487 2 4.00221 2H14.9968L21 8ZM19 9H14V4H5V20H19V9ZM8 7H11V9H8V7ZM8 11H16V13H8V11ZM8 15H16V17H8V15Z" fill="currentColor"/>',"file-transfer":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM12 11V8L16 12L12 16V13H8V11H12Z" fill="currentColor"/>',"file-video":'<path d="M15 4V8H19V20H5V4H15ZM3.9985 2C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H20.0066C20.5551 22 21 21.5489 21 20.9925L20.9997 7L16 2H3.9985ZM15.0008 11.667L10.1219 8.41435C10.0562 8.37054 9.979 8.34717 9.9 8.34717C9.6791 8.34717 9.5 8.52625 9.5 8.74717V15.2524C9.5 15.3314 9.5234 15.4086 9.5672 15.4743C9.6897 15.6581 9.9381 15.7078 10.1219 15.5852L15.0008 12.3326C15.0447 12.3033 15.0824 12.2656 15.1117 12.2217C15.2343 12.0379 15.1846 11.7895 15.0008 11.667Z" fill="currentColor"/>',flask:'<path d="M15.9994 2V4H14.9994V7.24291C14.9994 8.40051 15.2506 9.54432 15.7357 10.5954L20.017 19.8714C20.3641 20.6236 20.0358 21.5148 19.2836 21.8619C19.0865 21.9529 18.8721 22 18.655 22H5.34375C4.51532 22 3.84375 21.3284 3.84375 20.5C3.84375 20.2829 3.89085 20.0685 3.98181 19.8714L8.26306 10.5954C8.74816 9.54432 8.99939 8.40051 8.99939 7.24291V4H7.99939V2H15.9994ZM13.3873 10.0012H10.6115C10.5072 10.3644 10.3823 10.7221 10.2371 11.0724L10.079 11.4335L6.12439 20H17.8734L13.9198 11.4335C13.7054 10.9691 13.5276 10.4902 13.3873 10.0012ZM10.9994 7.24291C10.9994 7.49626 10.9898 7.7491 10.9706 8.00087H13.0282C13.0189 7.87982 13.0119 7.75852 13.0072 7.63704L12.9994 7.24291V4H10.9994V7.24291Z" fill="currentColor"/>',folder:'<path d="M4 5V19H20V7H11.5858L9.58579 5H4ZM12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-3":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 7V19H20V7H4Z" fill="currentColor"/>',"folder-3-fill":'<path d="M22 8V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7H21C21.5523 7 22 7.44772 22 8ZM12.4142 5H2V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-6":'<path d="M2 4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21L3 21C2.45 21 2 20.55 2 20V4ZM10.5858 6L9.58579 5H4V7H9.58579L10.5858 6ZM4 9V19L20 19V7H12.4142L10.4142 9H4Z" fill="currentColor"/>',"folder-add":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 5V19H20V7H11.5858L9.58579 5H4ZM11 12V9H13V12H16V14H13V17H11V14H8V12H11Z" fill="currentColor"/>',"folder-open":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H19V7H11.5858L9.58579 5H4V16.998L5.5 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3ZM19.9384 13H7.06155L5.56155 19H18.4384L19.9384 13Z" fill="currentColor"/>',"folder-open-fill":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H4V18.996L6 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3Z" fill="currentColor"/>',"folder-received":'<path d="M22 13H20V7H11.5858L9.58579 5H4V19H13V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V13ZM20 17H23V19H20V22.5L15 18L20 13.5V17Z" fill="currentColor"/>',folders:'<path d="M6 7V4C6 3.44772 6.44772 3 7 3H13.4142L15.4142 5H21C21.5523 5 22 5.44772 22 6V16C22 16.5523 21.5523 17 21 17H18V20C18 20.5523 17.5523 21 17 21H3C2.44772 21 2 20.5523 2 20V8C2 7.44772 2.44772 7 3 7H6ZM6 9H4V19H16V17H6V9ZM8 5V15H20V7H14.5858L12.5858 5H8Z" fill="currentColor"/>',fullscreen:'<path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z" fill="currentColor"/>',"fullscreen-exit":'<path d="M18 7H22V9H16V3H18V7ZM8 9H2V7H6V3H8V9ZM18 17V21H16V15H22V17H18ZM8 15V21H6V17H2V15H8Z" fill="currentColor"/>',"git-branch":'<path d="M7.10508 15.2101C8.21506 15.6501 9 16.7334 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V11.9996C7.83566 11.3719 8.87439 11 10 11H14C15.3835 11 16.5482 10.0635 16.8949 8.78991C15.7849 8.34988 15 7.26661 15 6C15 4.34315 16.3431 3 18 3C19.6569 3 21 4.34315 21 6C21 7.3332 20.1303 8.46329 18.9274 8.85392C18.5222 11.2085 16.4703 13 14 13H10C8.61653 13 7.45179 13.9365 7.10508 15.2101ZM6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17ZM6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5ZM18 5C17.4477 5 17 5.44772 17 6C17 6.55228 17.4477 7 18 7C18.5523 7 19 6.55228 19 6C19 5.44772 18.5523 5 18 5Z" fill="currentColor"/>',"git-commit":'<path d="M15.874 13C15.4299 14.7252 13.8638 16 12 16C10.1362 16 8.57006 14.7252 8.12602 13H3V11H8.12602C8.57006 9.27477 10.1362 8 12 8C13.8638 8 15.4299 9.27477 15.874 11H21V13H15.874ZM12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" fill="currentColor"/>',"git-merge":'<path d="M7.10508 8.78991C7.45179 10.0635 8.61653 11 10 11H14C16.4703 11 18.5222 12.7915 18.9274 15.1461C20.1303 15.5367 21 16.6668 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.7334 15.7849 15.6501 16.8949 15.2101C16.5482 13.9365 15.3835 13 14 13H10C8.87439 13 7.83566 12.6281 7 12.0004V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.26661 8.21506 8.34988 7.10508 8.78991ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-pull-request":'<path d="M15 5H17C18.1046 5 19 5.89543 19 7V15.1707C20.1652 15.5825 21 16.6938 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.6938 15.8348 15.5825 17 15.1707V7H15V10L10.5 6L15 2V5ZM5 8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-repository":'<path d="M13 21V23.5L10 21.5L7 23.5V21H6.5C4.567 21 3 19.433 3 17.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V20C21 20.5523 20.5523 21 20 21H13ZM13 19H19V16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19H7V17H13V19ZM19 14V4H6V14.0354C6.1633 14.0121 6.33024 14 6.5 14H19ZM7 5H9V7H7V5ZM7 8H9V10H7V8ZM7 11H9V13H7V11Z" fill="currentColor"/>',github:'<path d="M5.88401 18.6533C5.58404 18.4526 5.32587 18.1975 5.0239 17.8369C4.91473 17.7065 4.47283 17.1524 4.55811 17.2583C4.09533 16.6833 3.80296 16.417 3.50156 16.3089C2.9817 16.1225 2.7114 15.5499 2.89784 15.0301C3.08428 14.5102 3.65685 14.2399 4.17672 14.4263C4.92936 14.6963 5.43847 15.1611 6.12425 16.0143C6.03025 15.8974 6.46364 16.441 6.55731 16.5529C6.74784 16.7804 6.88732 16.9182 6.99629 16.9911C7.20118 17.1283 7.58451 17.1874 8.14709 17.1311C8.17065 16.7489 8.24136 16.3783 8.34919 16.0358C5.38097 15.3104 3.70116 13.3952 3.70116 9.63971C3.70116 8.40085 4.0704 7.28393 4.75917 6.3478C4.5415 5.45392 4.57433 4.37284 5.06092 3.15636C5.1725 2.87739 5.40361 2.66338 5.69031 2.57352C5.77242 2.54973 5.81791 2.53915 5.89878 2.52673C6.70167 2.40343 7.83573 2.69705 9.31449 3.62336C10.181 3.41879 11.0885 3.315 12.0012 3.315C12.9129 3.315 13.8196 3.4186 14.6854 3.62277C16.1619 2.69 17.2986 2.39649 18.1072 2.52651C18.1919 2.54013 18.2645 2.55783 18.3249 2.57766C18.6059 2.66991 18.8316 2.88179 18.9414 3.15636C19.4279 4.37256 19.4608 5.45344 19.2433 6.3472C19.9342 7.28337 20.3012 8.39208 20.3012 9.63971C20.3012 13.3968 18.627 15.3048 15.6588 16.032C15.7837 16.447 15.8496 16.9105 15.8496 17.4121C15.8496 18.0765 15.8471 18.711 15.8424 19.4225C15.8412 19.6127 15.8397 19.8159 15.8375 20.1281C16.2129 20.2109 16.5229 20.5077 16.6031 20.9089C16.7114 21.4504 16.3602 21.9773 15.8186 22.0856C14.6794 22.3134 13.8353 21.5538 13.8353 20.5611C13.8353 20.4708 13.836 20.3417 13.8375 20.1145C13.8398 19.8015 13.8412 19.599 13.8425 19.4094C13.8471 18.7019 13.8496 18.0716 13.8496 17.4121C13.8496 16.7148 13.6664 16.2602 13.4237 16.051C12.7627 15.4812 13.0977 14.3973 13.965 14.2999C16.9314 13.9666 18.3012 12.8177 18.3012 9.63971C18.3012 8.68508 17.9893 7.89571 17.3881 7.23559C17.1301 6.95233 17.0567 6.54659 17.199 6.19087C17.3647 5.77663 17.4354 5.23384 17.2941 4.57702L17.2847 4.57968C16.7928 4.71886 16.1744 5.0198 15.4261 5.5285C15.182 5.69438 14.8772 5.74401 14.5932 5.66413C13.7729 5.43343 12.8913 5.315 12.0012 5.315C11.111 5.315 10.2294 5.43343 9.40916 5.66413C9.12662 5.74359 8.82344 5.69492 8.57997 5.53101C7.8274 5.02439 7.2056 4.72379 6.71079 4.58376C6.56735 5.23696 6.63814 5.77782 6.80336 6.19087C6.94565 6.54659 6.87219 6.95233 6.61423 7.23559C6.01715 7.8912 5.70116 8.69376 5.70116 9.63971C5.70116 12.8116 7.07225 13.9683 10.023 14.2999C10.8883 14.3971 11.2246 15.4769 10.5675 16.0482C10.3751 16.2156 10.1384 16.7802 10.1384 17.4121V20.5611C10.1384 21.5474 9.30356 22.2869 8.17878 22.09C7.63476 21.9948 7.27093 21.4766 7.36613 20.9326C7.43827 20.5204 7.75331 20.2116 8.13841 20.1276V19.1381C7.22829 19.1994 6.47656 19.0498 5.88401 18.6533Z" fill="currentColor"/>',"github-fill":'<path d="M12.001 2C6.47598 2 2.00098 6.475 2.00098 12C2.00098 16.425 4.86348 20.1625 8.83848 21.4875C9.33848 21.575 9.52598 21.275 9.52598 21.0125C9.52598 20.775 9.51348 19.9875 9.51348 19.15C7.00098 19.6125 6.35098 18.5375 6.15098 17.975C6.03848 17.6875 5.55098 16.8 5.12598 16.5625C4.77598 16.375 4.27598 15.9125 5.11348 15.9C5.90098 15.8875 6.46348 16.625 6.65098 16.925C7.55098 18.4375 8.98848 18.0125 9.56348 17.75C9.65098 17.1 9.91348 16.6625 10.201 16.4125C7.97598 16.1625 5.65098 15.3 5.65098 11.475C5.65098 10.3875 6.03848 9.4875 6.67598 8.7875C6.57598 8.5375 6.22598 7.5125 6.77598 6.1375C6.77598 6.1375 7.61348 5.875 9.52598 7.1625C10.326 6.9375 11.176 6.825 12.026 6.825C12.876 6.825 13.726 6.9375 14.526 7.1625C16.4385 5.8625 17.276 6.1375 17.276 6.1375C17.826 7.5125 17.476 8.5375 17.376 8.7875C18.0135 9.4875 18.401 10.375 18.401 11.475C18.401 15.3125 16.0635 16.1625 13.8385 16.4125C14.201 16.725 14.5135 17.325 14.5135 18.2625C14.5135 19.6 14.501 20.675 14.501 21.0125C14.501 21.275 14.6885 21.5875 15.1885 21.4875C19.259 20.1133 21.9999 16.2963 22.001 12C22.001 6.475 17.526 2 12.001 2Z" fill="currentColor"/>',global:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM9.71002 19.6674C8.74743 17.6259 8.15732 15.3742 8.02731 13H4.06189C4.458 16.1765 6.71639 18.7747 9.71002 19.6674ZM10.0307 13C10.1811 15.4388 10.8778 17.7297 12 19.752C13.1222 17.7297 13.8189 15.4388 13.9693 13H10.0307ZM19.9381 13H15.9727C15.8427 15.3742 15.2526 17.6259 14.29 19.6674C17.2836 18.7747 19.542 16.1765 19.9381 13ZM4.06189 11H8.02731C8.15732 8.62577 8.74743 6.37407 9.71002 4.33256C6.71639 5.22533 4.458 7.8235 4.06189 11ZM10.0307 11H13.9693C13.8189 8.56122 13.1222 6.27025 12 4.24799C10.8778 6.27025 10.1811 8.56122 10.0307 11ZM14.29 4.33256C15.2526 6.37407 15.8427 8.62577 15.9727 11H19.9381C19.542 7.8235 17.2836 5.22533 14.29 4.33256Z" fill="currentColor"/>',hammer:'<path d="M20 2C20.5523 2 21 2.44772 21 3V8C21 8.55228 20.5523 9 20 9H15V22C15 22.5523 14.5523 23 14 23H10C9.44772 23 9 22.5523 9 22V9H3.5C2.94772 9 2.5 8.55228 2.5 8V5.61803C2.5 5.23926 2.714 4.893 3.05279 4.72361L8.5 2H20ZM15 4H8.97214L4.5 6.23607V7H11V21H13V7H15V4ZM19 4H17V7H19V4Z" fill="currentColor"/>',history:'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12H4C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C9.25022 4 6.82447 5.38734 5.38451 7.50024L8 7.5V9.5H2V3.5H4L3.99989 5.99918C5.82434 3.57075 8.72873 2 12 2ZM13 7L12.9998 11.585L16.2426 14.8284L14.8284 16.2426L10.9998 12.413L11 7H13Z" fill="currentColor"/>',home:'<path d="M21 20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V9.48907C3 9.18048 3.14247 8.88917 3.38606 8.69972L11.3861 2.47749C11.7472 2.19663 12.2528 2.19663 12.6139 2.47749L20.6139 8.69972C20.8575 8.88917 21 9.18048 21 9.48907V20ZM19 19V9.97815L12 4.53371L5 9.97815V19H19Z" fill="currentColor"/>',hourglass:'<path d="M6 4H4V2H20V4H18V6C18 7.61543 17.1838 8.91468 16.1561 9.97667C15.4532 10.703 14.598 11.372 13.7309 12C14.598 12.628 15.4532 13.297 16.1561 14.0233C17.1838 15.0853 18 16.3846 18 18V20H20V22H4V20H6V18C6 16.3846 6.81616 15.0853 7.8439 14.0233C8.54682 13.297 9.40202 12.628 10.2691 12C9.40202 11.372 8.54682 10.703 7.8439 9.97667C6.81616 8.91468 6 7.61543 6 6V4ZM8 4V6C8 6.88457 8.43384 7.71032 9.2811 8.58583C10.008 9.33699 10.9548 10.0398 12 10.7781C13.0452 10.0398 13.992 9.33699 14.7189 8.58583C15.5662 7.71032 16 6.88457 16 6V4H8ZM12 13.2219C10.9548 13.9602 10.008 14.663 9.2811 15.4142C8.43384 16.2897 8 17.1154 8 18V20H16V18C16 17.1154 15.5662 16.2897 14.7189 15.4142C13.992 14.663 13.0452 13.9602 12 13.2219Z" fill="currentColor"/>',image:'<path d="M2.9918 21C2.44405 21 2 20.5551 2 20.0066V3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918ZM20 15V5H4V19L14 9L20 15ZM20 17.8284L14 11.8284L6.82843 19H20V17.8284ZM8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11Z" fill="currentColor"/>',"image-download":'<path d="M21 15V19H24L20 23L16 19H19V15H21ZM21.0078 3C21.5555 3 21.9999 3.44482 22 3.99316V13H20V5H4V18.999L14 9L17 12V14.8291L14 11.8281L6.82715 19H14V21H2.99219C2.44451 21 2.00013 20.5552 2 20.0068V3.99316C2.00013 3.44463 2.45577 3 2.99219 3H21.0078ZM8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7Z" fill="currentColor"/>',"inbox-archive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM13 10V14H16L12 18L8 14H11V10H13ZM18.7639 5H5.23656L4.23744 7H19.7639L18.7639 5Z" fill="currentColor"/>',"inbox-unarchive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM12 10L16 14H13V18H11V14H8L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',"inbox-unarchive-fill":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM12 10L8 14H11V18H13V14H16L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',information:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 7H13V9H11V7ZM11 11H13V17H11V11Z" fill="currentColor"/>',"layout-column":'<path d="M11 5H5V19H11V5ZM13 5V19H19V5H13ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3Z" fill="currentColor"/>',"layout-left":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM7 5H4V19H7V5ZM20 5H9V19H20V5Z" fill="currentColor"/>',"layout-right":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM15 5H4V19H15V5ZM20 5H17V19H20V5Z" fill="currentColor"/>',"list-check-2":'<path d="M11 4H21V6H11V4ZM11 8H17V10H11V8ZM11 14H21V16H11V14ZM11 18H17V20H11V18ZM3 4H9V10H3V4ZM5 6V8H7V6H5ZM3 14H9V20H3V14ZM5 16V18H7V16H5Z" fill="currentColor"/>',"list-check-3":'<path d="M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z" fill="currentColor"/>',"list-unordered":'<path d="M8 4H21V6H8V4ZM4.5 6.5C3.67157 6.5 3 5.82843 3 5C3 4.17157 3.67157 3.5 4.5 3.5C5.32843 3.5 6 4.17157 6 5C6 5.82843 5.32843 6.5 4.5 6.5ZM4.5 13.5C3.67157 13.5 3 12.8284 3 12C3 11.1716 3.67157 10.5 4.5 10.5C5.32843 10.5 6 11.1716 6 12C6 12.8284 5.32843 13.5 4.5 13.5ZM4.5 20.4C3.67157 20.4 3 19.7284 3 18.9C3 18.0716 3.67157 17.4 4.5 17.4C5.32843 17.4 6 18.0716 6 18.9C6 19.7284 5.32843 20.4 4.5 20.4ZM8 11H21V13H8V11ZM8 18H21V20H8V18Z" fill="currentColor"/>',loader:'<path d="M11.9995 2C12.5518 2 12.9995 2.44772 12.9995 3V6C12.9995 6.55228 12.5518 7 11.9995 7C11.4472 7 10.9995 6.55228 10.9995 6V3C10.9995 2.44772 11.4472 2 11.9995 2ZM11.9995 17C12.5518 17 12.9995 17.4477 12.9995 18V21C12.9995 21.5523 12.5518 22 11.9995 22C11.4472 22 10.9995 21.5523 10.9995 21V18C10.9995 17.4477 11.4472 17 11.9995 17ZM20.6597 7C20.9359 7.47829 20.772 8.08988 20.2937 8.36602L17.6956 9.86602C17.2173 10.1422 16.6057 9.97829 16.3296 9.5C16.0535 9.02171 16.2173 8.41012 16.6956 8.13398L19.2937 6.63397C19.772 6.35783 20.3836 6.52171 20.6597 7ZM7.66935 14.5C7.94549 14.9783 7.78161 15.5899 7.30332 15.866L4.70525 17.366C4.22695 17.6422 3.61536 17.4783 3.33922 17C3.06308 16.5217 3.22695 15.9101 3.70525 15.634L6.30332 14.134C6.78161 13.8578 7.3932 14.0217 7.66935 14.5ZM20.6597 17C20.3836 17.4783 19.772 17.6422 19.2937 17.366L16.6956 15.866C16.2173 15.5899 16.0535 14.9783 16.3296 14.5C16.6057 14.0217 17.2173 13.8578 17.6956 14.134L20.2937 15.634C20.772 15.9101 20.9359 16.5217 20.6597 17ZM7.66935 9.5C7.3932 9.97829 6.78161 10.1422 6.30332 9.86602L3.70525 8.36602C3.22695 8.08988 3.06308 7.47829 3.33922 7C3.61536 6.52171 4.22695 6.35783 4.70525 6.63397L7.30332 8.13398C7.78161 8.41012 7.94549 9.02171 7.66935 9.5Z" fill="currentColor"/>',"loader-4":'<path d="M18.364 5.63604L16.9497 7.05025C15.683 5.7835 13.933 5 12 5C8.13401 5 5 8.13401 5 12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12H21C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C14.4853 3 16.7353 4.00736 18.364 5.63604Z" fill="currentColor"/>',lock:'<path d="M19 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C15.866 2 19 5.13401 19 9V10ZM5 12V20H19V12H5ZM11 14H13V18H11V14ZM17 10V9C17 6.23858 14.7614 4 12 4C9.23858 4 7 6.23858 7 9V10H17Z" fill="currentColor"/>',"lock-unlock":'<path d="M7 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C14.7405 2 17.1131 3.5748 18.2624 5.86882L16.4731 6.76344C15.6522 5.12486 13.9575 4 12 4C9.23858 4 7 6.23858 7 9V10ZM5 12V20H19V12H5ZM10 15H14V17H10V15Z" fill="currentColor"/>',"menu-2":'<path d="M3 4H21V6H3V4ZM3 11H15V13H3V11ZM3 18H21V20H3V18Z" fill="currentColor"/>',"menu-fold-2":'<path d="M4.40347 3.90332L2.98926 5.31753L6.17124 8.49951L2.98926 11.6815L4.40347 13.0957L8.99967 8.49951L4.40347 3.90332ZM20.9997 19.9995V17.9995H2.99967V19.9995H20.9997ZM20.9997 12.9995V10.9995H11.9997V12.9995H20.9997ZM20.9997 5.99951V3.99951H11.9997V5.99951H20.9997Z" fill="currentColor"/>',"menu-search":'<path d="M15.5 5C13.567 5 12 6.567 12 8.5C12 10.433 13.567 12 15.5 12C17.433 12 19 10.433 19 8.5C19 6.567 17.433 5 15.5 5ZM10 8.5C10 5.46243 12.4624 3 15.5 3C18.5376 3 21 5.46243 21 8.5C21 9.6575 20.6424 10.7315 20.0317 11.6175L22.7071 14.2929L21.2929 15.7071L18.6175 13.0317C17.7315 13.6424 16.6575 14 15.5 14C12.4624 14 10 11.5376 10 8.5ZM3 4H8V6H3V4ZM3 11H8V13H3V11ZM21 18V20H3V18H21Z" fill="currentColor"/>',mic:'<path d="M11.9998 3C10.3429 3 8.99976 4.34315 8.99976 6V10C8.99976 11.6569 10.3429 13 11.9998 13C13.6566 13 14.9998 11.6569 14.9998 10V6C14.9998 4.34315 13.6566 3 11.9998 3ZM11.9998 1C14.7612 1 16.9998 3.23858 16.9998 6V10C16.9998 12.7614 14.7612 15 11.9998 15C9.23833 15 6.99976 12.7614 6.99976 10V6C6.99976 3.23858 9.23833 1 11.9998 1ZM3.05469 11H5.07065C5.55588 14.3923 8.47329 17 11.9998 17C15.5262 17 18.4436 14.3923 18.9289 11H20.9448C20.4837 15.1716 17.1714 18.4839 12.9998 18.9451V23H10.9998V18.9451C6.82814 18.4839 3.51584 15.1716 3.05469 11Z" fill="currentColor"/>',more:'<path d="M4.5 10.5C3.675 10.5 3 11.175 3 12C3 12.825 3.675 13.5 4.5 13.5C5.325 13.5 6 12.825 6 12C6 11.175 5.325 10.5 4.5 10.5ZM19.5 10.5C18.675 10.5 18 11.175 18 12C18 12.825 18.675 13.5 19.5 13.5C20.325 13.5 21 12.825 21 12C21 11.175 20.325 10.5 19.5 10.5ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2":'<path d="M12 3C11.175 3 10.5 3.675 10.5 4.5C10.5 5.325 11.175 6 12 6C12.825 6 13.5 5.325 13.5 4.5C13.5 3.675 12.825 3 12 3ZM12 18C11.175 18 10.5 18.675 10.5 19.5C10.5 20.325 11.175 21 12 21C12.825 21 13.5 20.325 13.5 19.5C13.5 18.675 12.825 18 12 18ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2-fill":'<path d="M12 3C10.9 3 10 3.9 10 5C10 6.1 10.9 7 12 7C13.1 7 14 6.1 14 5C14 3.9 13.1 3 12 3ZM12 17C10.9 17 10 17.9 10 19C10 20.1 10.9 21 12 21C13.1 21 14 20.1 14 19C14 17.9 13.1 17 12 17ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',"more-fill":'<path d="M5 10C3.9 10 3 10.9 3 12C3 13.1 3.9 14 5 14C6.1 14 7 13.1 7 12C7 10.9 6.1 10 5 10ZM19 10C17.9 10 17 10.9 17 12C17 13.1 17.9 14 19 14C20.1 14 21 13.1 21 12C21 10.9 20.1 10 19 10ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',nixos:'<path fill="currentColor" d="m7.1 4.2 2.05 3.55-1.18 2.04L4.75 4.2H7.1Zm4.9-2.1 2.05 3.55h2.36L14.36 2.1H12Zm4.9 2.1-4.73 8.2h2.36l4.73-8.2H16.9Zm2.84 4.9h-4.1l-1.18 2.04h6.46l-1.18-2.04Zm-2.84 10.7-2.05-3.55 1.18-2.04 3.22 5.59H16.9ZM12 21.9l-2.05-3.55H7.59l2.05 3.55H12Zm-4.9-2.1 4.73-8.2H9.47l-4.73 8.2H7.1ZM4.26 14.9h4.1l1.18-2.04H3.08l1.18 2.04Z"/>',"node-tree":'<path d="M10 2C10.5523 2 11 2.44772 11 3V7C11 7.55228 10.5523 8 10 8H8V10H13V9C13 8.44772 13.4477 8 14 8H20C20.5523 8 21 8.44772 21 9V13C21 13.5523 20.5523 14 20 14H14C13.4477 14 13 13.5523 13 13V12H8V18H13V17C13 16.4477 13.4477 16 14 16H20C20.5523 16 21 16.4477 21 17V21C21 21.5523 20.5523 22 20 22H14C13.4477 22 13 21.5523 13 21V20H7C6.44772 20 6 19.5523 6 19V8H4C3.44772 8 3 7.55228 3 7V3C3 2.44772 3.44772 2 4 2H10ZM19 18H15V20H19V18ZM19 10H15V12H19V10ZM9 4H5V6H9V4Z" fill="currentColor"/>',"notification-3":'<path d="M20 17H22V19H2V17H4V10C4 5.58172 7.58172 2 12 2C16.4183 2 20 5.58172 20 10V17ZM18 17V10C18 6.68629 15.3137 4 12 4C8.68629 4 6 6.68629 6 10V17H18ZM9 21H15V23H9V21Z" fill="currentColor"/>',palette:'<path d="M12 2C17.5222 2 22 5.97778 22 10.8889C22 13.9556 19.5111 16.4444 16.4444 16.4444H14.4778C13.5556 16.4444 12.8111 17.1889 12.8111 18.1111C12.8111 18.5333 12.9778 18.9222 13.2333 19.2111C13.5 19.5111 13.6667 19.9 13.6667 20.3333C13.6667 21.2556 12.9 22 12 22C6.47778 22 2 17.5222 2 12C2 6.47778 6.47778 2 12 2ZM10.8111 18.1111C10.8111 16.0843 12.451 14.4444 14.4778 14.4444H16.4444C18.4065 14.4444 20 12.851 20 10.8889C20 7.1392 16.4677 4 12 4C7.58235 4 4 7.58235 4 12C4 16.19 7.2226 19.6285 11.324 19.9718C10.9948 19.4168 10.8111 18.7761 10.8111 18.1111ZM7.5 12C6.67157 12 6 11.3284 6 10.5C6 9.67157 6.67157 9 7.5 9C8.32843 9 9 9.67157 9 10.5C9 11.3284 8.32843 12 7.5 12ZM16.5 12C15.6716 12 15 11.3284 15 10.5C15 9.67157 15.6716 9 16.5 9C17.3284 9 18 9.67157 18 10.5C18 11.3284 17.3284 12 16.5 12ZM12 9C11.1716 9 10.5 8.32843 10.5 7.5C10.5 6.67157 11.1716 6 12 6C12.8284 6 13.5 6.67157 13.5 7.5C13.5 8.32843 12.8284 9 12 9Z" fill="currentColor"/>',pencil:'<path d="M15.7279 9.57627L14.3137 8.16206L5 17.4758V18.89H6.41421L15.7279 9.57627ZM17.1421 8.16206L18.5563 6.74785L17.1421 5.33363L15.7279 6.74785L17.1421 8.16206ZM7.24264 20.89H3V16.6473L16.435 3.21231C16.8256 2.82179 17.4587 2.82179 17.8492 3.21231L20.6777 6.04074C21.0682 6.43126 21.0682 7.06443 20.6777 7.45495L7.24264 20.89Z" fill="currentColor"/>',"pencil-ai":'<path d="M16.4356 3.21188C16.8261 2.82185 17.4592 2.82157 17.8496 3.21188L20.6777 6.04099C21.0681 6.43152 21.0682 7.06457 20.6777 7.45505L7.2422 20.8896H3.00001V16.6475L16.4356 3.21188ZM5.00001 17.4756V18.8896H6.41407L15.7276 9.57615L14.3135 8.16208L5.00001 17.4756ZM4.5293 1.3193C4.70583 0.893505 5.29418 0.893508 5.47071 1.3193L5.72364 1.93063C6.15555 2.97342 6.96155 3.80613 7.97462 4.2568L8.69239 4.57614C9.10267 4.75896 9.10262 5.35616 8.69239 5.53903L7.93263 5.87692C6.94497 6.3162 6.15339 7.11943 5.71387 8.1279L5.4668 8.69334C5.28636 9.10747 4.71366 9.10747 4.53321 8.69334L4.28614 8.1279C3.84661 7.11943 3.05506 6.3162 2.06739 5.87692L1.30762 5.53903C0.897483 5.35617 0.897435 4.75896 1.30762 4.57614L2.0254 4.2568C3.03845 3.80614 3.84446 2.97344 4.27637 1.93063L4.5293 1.3193ZM15.7276 6.74802L17.1426 8.16208L18.5567 6.74802L17.1426 5.33395L15.7276 6.74802Z" fill="currentColor"/>',pichamber:'<g transform="translate(12 12) scale(0.22) translate(-50 -50)"><path d="M50 3 91 27 50 51 9 27Z" fill="currentColor" fill-opacity="0.08"/><path d="M9 27 50 51V97L9 73Z" fill="currentColor" fill-opacity="0.15"/><path d="M50 51 91 27V73L50 97Z" fill="currentColor" fill-opacity="0.24"/><path d="M50 3 91 27V73L50 97 9 73V27Z" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></g>',"picture-in-picture-2":'<path d="M21 3C21.5523 3 22 3.44772 22 4V11H20V5H4V19H10V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM21 13C21.5523 13 22 13.4477 22 14V20C22 20.5523 21.5523 21 21 21H13C12.4477 21 12 20.5523 12 20V14C12 13.4477 12.4477 13 13 13H21ZM20 15H14V19H20V15ZM6.70711 6.29289L8.95689 8.54289L11 6.5V12H5.5L7.54289 9.95689L5.29289 7.70711L6.70711 6.29289Z" fill="currentColor"/>',"pie-chart":'<path d="M9 2.4578V4.58152C6.06817 5.76829 4 8.64262 4 12C4 16.4183 7.58172 20 12 20C15.3574 20 18.2317 17.9318 19.4185 15H21.5422C20.2679 19.0571 16.4776 22 12 22C6.47715 22 2 17.5228 2 12C2 7.52236 4.94289 3.73207 9 2.4578ZM12 2C17.5228 2 22 6.47715 22 12C22 12.3375 21.9833 12.6711 21.9506 13H11V2.04938C11.3289 2.01672 11.6625 2 12 2ZM13 4.06189V11H19.9381C19.4869 7.38128 16.6187 4.51314 13 4.06189Z" fill="currentColor"/>',play:'<path d="M16.3944 12.0001L10 7.7371V16.263L16.3944 12.0001ZM19.376 12.4161L8.77735 19.4818C8.54759 19.635 8.23715 19.5729 8.08397 19.3432C8.02922 19.261 8 19.1645 8 19.0658V4.93433C8 4.65818 8.22386 4.43433 8.5 4.43433C8.59871 4.43433 8.69522 4.46355 8.77735 4.5183L19.376 11.584C19.6057 11.7372 19.6678 12.0477 19.5146 12.2774C19.478 12.3323 19.4309 12.3795 19.376 12.4161Z" fill="currentColor"/>',"play-list-add":'<path d="M2 18H12V20H2V18ZM2 11H22V13H2V11ZM2 4H22V6H2V4ZM18 18V15H20V18H23V20H20V23H18V20H15V18H18Z" fill="currentColor"/>',"plug-2":'<path d="M13 18V20H19V22H13C11.8954 22 11 21.1046 11 20V18H8C5.79086 18 4 16.2091 4 14V7C4 6.44772 4.44772 6 5 6H7V2H9V6H15V2H17V6H19C19.5523 6 20 6.44772 20 7V14C20 16.2091 18.2091 18 16 18H13ZM8 16H16C17.1046 16 18 15.1046 18 14V11H6V14C6 15.1046 6.89543 16 8 16ZM18 8H6V9H18V8ZM12 14.5C11.4477 14.5 11 14.0523 11 13.5C11 12.9477 11.4477 12.5 12 12.5C12.5523 12.5 13 12.9477 13 13.5C13 14.0523 12.5523 14.5 12 14.5ZM11 2H13V5H11V2Z" fill="currentColor"/>',pushpin:'<path d="M13.8273 1.69L22.3126 10.1753L20.8984 11.5895L20.1913 10.8824L15.9486 15.125L15.2415 18.6606L13.8273 20.0748L9.58466 15.8321L4.63492 20.7819L3.2207 19.3677L8.17045 14.4179L3.92781 10.1753L5.34202 8.76107L8.87756 8.05396L13.1202 3.81132L12.4131 3.10422L13.8273 1.69ZM14.5344 5.22554L9.86358 9.89637L7.0417 10.4607L13.5418 16.9609L14.1062 14.139L18.7771 9.46818L14.5344 5.22554Z" fill="currentColor"/>',"pushpin-2":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18ZM9 5V11.6056L7.4037 14H16.5963L15 11.6056V5H9Z" fill="currentColor"/>',"pushpin-2-fill":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18Z" fill="currentColor"/>',puzzle:'<path d="M7 5C7 2.79086 8.79086 1 11 1C13.2091 1 15 2.79086 15 5H18C18.5523 5 19 5.44772 19 6V9C21.2091 9 23 10.7909 23 13C23 15.2091 21.2091 17 19 17V20C19 20.5523 18.5523 21 18 21H4C3.44772 21 3 20.5523 3 20V6C3 5.44772 3.44772 5 4 5H7ZM11 3C9.89543 3 9 3.89543 9 5C9 5.23554 9.0403 5.45952 9.11355 5.66675C9.22172 5.97282 9.17461 6.31235 8.98718 6.57739C8.79974 6.84243 8.49532 7 8.17071 7H5V19H17V15.8293C17 15.5047 17.1576 15.2003 17.4226 15.0128C17.6877 14.8254 18.0272 14.7783 18.3332 14.8865C18.5405 14.9597 18.7645 15 19 15C20.1046 15 21 14.1046 21 13C21 11.8954 20.1046 11 19 11C18.7645 11 18.5405 11.0403 18.3332 11.1135C18.0272 11.2217 17.6877 11.1746 17.4226 10.9872C17.1576 10.7997 17 10.4953 17 10.1707V7H13.8293C13.5047 7 13.2003 6.84243 13.0128 6.57739C12.8254 6.31235 12.7783 5.97282 12.8865 5.66675C12.9597 5.45952 13 5.23555 13 5C13 3.89543 12.1046 3 11 3Z" fill="currentColor"/>',question:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM13 13.3551V14H11V12.5C11 11.9477 11.4477 11.5 12 11.5C12.8284 11.5 13.5 10.8284 13.5 10C13.5 9.17157 12.8284 8.5 12 8.5C11.2723 8.5 10.6656 9.01823 10.5288 9.70577L8.56731 9.31346C8.88637 7.70919 10.302 6.5 12 6.5C13.933 6.5 15.5 8.067 15.5 10C15.5 11.5855 14.4457 12.9248 13 13.3551Z" fill="currentColor"/>',"record-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12C15 13.6569 13.6569 15 12 15Z" fill="currentColor"/>',refresh:'<path d="M5.46257 4.43262C7.21556 2.91688 9.5007 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C9.84982 4 7.89777 4.84827 6.46023 6.22842L5.46257 4.43262ZM18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 9.86386 2.66979 7.88416 3.8108 6.25944L7 12H4C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',restart:'<path d="M18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',"robot-2":'<path d="M13.5 2C13.5 2.44425 13.3069 2.84339 13 3.11805V5H18C19.6569 5 21 6.34315 21 8V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V8C3 6.34315 4.34315 5 6 5H11V3.11805C10.6931 2.84339 10.5 2.44425 10.5 2C10.5 1.17157 11.1716 0.5 12 0.5C12.8284 0.5 13.5 1.17157 13.5 2ZM6 7C5.44772 7 5 7.44772 5 8V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V8C19 7.44772 18.5523 7 18 7H13H11H6ZM2 10H0V16H2V10ZM22 10H24V16H22V10ZM9 14.5C9.82843 14.5 10.5 13.8284 10.5 13C10.5 12.1716 9.82843 11.5 9 11.5C8.17157 11.5 7.5 12.1716 7.5 13C7.5 13.8284 8.17157 14.5 9 14.5ZM15 14.5C15.8284 14.5 16.5 13.8284 16.5 13C16.5 12.1716 15.8284 11.5 15 11.5C14.1716 11.5 13.5 12.1716 13.5 13C13.5 13.8284 14.1716 14.5 15 14.5Z" fill="currentColor"/>',rocket:'<path d="M4.99958 12.9999C4.99958 7.91198 7.90222 3.5636 11.9996 1.81799C16.0969 3.5636 18.9996 7.91198 18.9996 12.9999C18.9996 13.8229 18.9236 14.6264 18.779 15.4027L20.7194 17.2353C20.8845 17.3913 20.9238 17.6389 20.815 17.8383L18.3196 22.4133C18.1873 22.6557 17.8836 22.7451 17.6412 22.6128C17.5993 22.59 17.5608 22.5612 17.5271 22.5274L15.2925 20.2928C15.1049 20.1053 14.8506 19.9999 14.5854 19.9999H9.41379C9.14857 19.9999 8.89422 20.1053 8.70668 20.2928L6.47209 22.5274C6.27683 22.7227 5.96025 22.7227 5.76498 22.5274C5.73122 22.4937 5.70246 22.4552 5.67959 22.4133L3.18412 17.8383C3.07537 17.6389 3.11464 17.3913 3.27975 17.2353L5.22014 15.4027C5.07551 14.6264 4.99958 13.8229 4.99958 12.9999ZM6.47542 19.6957L7.29247 18.8786C7.85508 18.316 8.61814 17.9999 9.41379 17.9999H14.5854C15.381 17.9999 16.1441 18.316 16.7067 18.8786L17.5237 19.6957L18.5056 17.8955L17.4058 16.8568C16.9117 16.3901 16.6884 15.7045 16.8128 15.0364C16.9366 14.3722 16.9996 13.6911 16.9996 12.9999C16.9996 9.13037 15.0045 5.69965 11.9996 4.04033C8.99462 5.69965 6.99958 9.13037 6.99958 12.9999C6.99958 13.6911 7.06255 14.3722 7.18631 15.0364C7.31078 15.7045 7.08746 16.3901 6.59338 16.8568L5.49353 17.8955L6.47542 19.6957ZM11.9996 12.9999C10.895 12.9999 9.99958 12.1045 9.99958 10.9999C9.99958 9.89537 10.895 8.99994 11.9996 8.99994C13.1041 8.99994 13.9996 9.89537 13.9996 10.9999C13.9996 12.1045 13.1041 12.9999 11.9996 12.9999Z" fill="currentColor"/>',"save-3":'<path d="M18 19H19V6.82843L17.1716 5H16V9H7V5H5V19H6V12H18V19ZM4 3H18L20.7071 5.70711C20.8946 5.89464 21 6.149 21 6.41421V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM8 14V19H16V14H8Z" fill="currentColor"/>',"scan-2":'<path d="M5.67127 4.25705L13.4142 12L12 13.4142L8.55382 9.96803C8.20193 10.5635 8 11.2582 8 12C8 14.2091 9.79086 16 12 16C14.2091 16 16 14.2091 16 12C16 9.87494 14.3429 8.13693 12.2503 8.00771L10.4459 6.20323C10.9416 6.07067 11.4625 6 12 6C15.3137 6 18 8.68629 18 12C18 15.3137 15.3137 18 12 18C8.68629 18 6 15.3137 6 12C6 10.7042 6.41079 9.50428 7.10925 8.52347L5.68014 7.09436C4.62708 8.44904 4 10.1513 4 12C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C10.8915 4 9.83557 4.22547 8.8757 4.63306L7.37443 3.13179C8.75768 2.40883 10.3311 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 8.87842 3.43029 6.09091 5.67127 4.25705Z" fill="currentColor"/>',search:'<path d="M18.031 16.6168L22.3137 20.8995L20.8995 22.3137L16.6168 18.031C15.0769 19.263 13.124 20 11 20C6.032 20 2 15.968 2 11C2 6.032 6.032 2 11 2C15.968 2 20 6.032 20 11C20 13.124 19.263 15.0769 18.031 16.6168ZM16.0247 15.8748C17.2475 14.6146 18 12.8956 18 11C18 7.1325 14.8675 4 11 4C7.1325 4 4 7.1325 4 11C4 14.8675 7.1325 18 11 18C12.8956 18 14.6146 17.2475 15.8748 16.0247L16.0247 15.8748Z" fill="currentColor"/>',"send-plane":'<path d="M21.7267 2.95694L16.2734 22.0432C16.1225 22.5716 15.7979 22.5956 15.5563 22.1126L11 13L1.9229 9.36919C1.41322 9.16532 1.41953 8.86022 1.95695 8.68108L21.0432 2.31901C21.5716 2.14285 21.8747 2.43866 21.7267 2.95694ZM19.0353 5.09647L6.81221 9.17085L12.4488 11.4255L15.4895 17.5068L19.0353 5.09647Z" fill="currentColor"/>',"send-plane-2":'<path d="M3.5 1.34558C3.58425 1.34558 3.66714 1.36687 3.74096 1.40747L22.2034 11.5618C22.4454 11.6949 22.5337 11.9989 22.4006 12.2409C22.3549 12.324 22.2865 12.3924 22.2034 12.4381L3.74096 22.5924C3.499 22.7255 3.19497 22.6372 3.06189 22.3953C3.02129 22.3214 3 22.2386 3 22.1543V1.84558C3 1.56944 3.22386 1.34558 3.5 1.34558ZM5 4.38249V10.9999H10V12.9999H5V19.6174L18.8499 11.9999L5 4.38249Z" fill="currentColor"/>',server:'<path d="M5 11H19V5H5V11ZM21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20C20.5523 3 21 3.44772 21 4ZM19 13H5V19H19V13ZM7 15H10V17H7V15ZM7 7H10V9H7V7Z" fill="currentColor"/>',"settings-3":'<path d="M3.33946 17.0002C2.90721 16.2515 2.58277 15.4702 2.36133 14.6741C3.3338 14.1779 3.99972 13.1668 3.99972 12.0002C3.99972 10.8345 3.3348 9.824 2.36353 9.32741C2.81025 7.71651 3.65857 6.21627 4.86474 4.99001C5.7807 5.58416 6.98935 5.65534 7.99972 5.072C9.01009 4.48866 9.55277 3.40635 9.4962 2.31604C11.1613 1.8846 12.8847 1.90004 14.5031 2.31862C14.4475 3.40806 14.9901 4.48912 15.9997 5.072C17.0101 5.65532 18.2187 5.58416 19.1346 4.99007C19.7133 5.57986 20.2277 6.25151 20.66 7.00021C21.0922 7.7489 21.4167 8.53025 21.6381 9.32628C20.6656 9.82247 19.9997 10.8336 19.9997 12.0002C19.9997 13.166 20.6646 14.1764 21.6359 14.673C21.1892 16.2839 20.3409 17.7841 19.1347 19.0104C18.2187 18.4163 17.0101 18.3451 15.9997 18.9284C14.9893 19.5117 14.4467 20.5941 14.5032 21.6844C12.8382 22.1158 11.1148 22.1004 9.49633 21.6818C9.55191 20.5923 9.00929 19.5113 7.99972 18.9284C6.98938 18.3451 5.78079 18.4162 4.86484 19.0103C4.28617 18.4205 3.77172 17.7489 3.33946 17.0002ZM8.99972 17.1964C10.0911 17.8265 10.8749 18.8227 11.2503 19.9659C11.7486 20.0133 12.2502 20.014 12.7486 19.9675C13.1238 18.8237 13.9078 17.8268 14.9997 17.1964C16.0916 16.5659 17.347 16.3855 18.5252 16.6324C18.8146 16.224 19.0648 15.7892 19.2729 15.334C18.4706 14.4373 17.9997 13.2604 17.9997 12.0002C17.9997 10.74 18.4706 9.5632 19.2729 8.6665C19.1688 8.4405 19.0538 8.21822 18.9279 8.00021C18.802 7.78219 18.667 7.57148 18.5233 7.36842C17.3457 7.61476 16.0911 7.43414 14.9997 6.80405C13.9083 6.17395 13.1246 5.17768 12.7491 4.03455C12.2509 3.98714 11.7492 3.98646 11.2509 4.03292C10.8756 5.17671 10.0916 6.17364 8.99972 6.80405C7.9078 7.43447 6.65245 7.61494 5.47428 7.36803C5.18485 7.77641 4.93463 8.21117 4.72656 8.66637C5.52881 9.56311 5.99972 10.74 5.99972 12.0002C5.99972 13.2604 5.52883 14.4372 4.72656 15.3339C4.83067 15.5599 4.94564 15.7822 5.07152 16.0002C5.19739 16.2182 5.3324 16.4289 5.47612 16.632C6.65377 16.3857 7.90838 16.5663 8.99972 17.1964ZM11.9997 15.0002C10.3429 15.0002 8.99972 13.6571 8.99972 12.0002C8.99972 10.3434 10.3429 9.00021 11.9997 9.00021C13.6566 9.00021 14.9997 10.3434 14.9997 12.0002C14.9997 13.6571 13.6566 15.0002 11.9997 15.0002ZM11.9997 13.0002C12.552 13.0002 12.9997 12.5525 12.9997 12.0002C12.9997 11.4479 12.552 11.0002 11.9997 11.0002C11.4474 11.0002 10.9997 11.4479 10.9997 12.0002C10.9997 12.5525 11.4474 13.0002 11.9997 13.0002Z" fill="currentColor"/>',"shield-keyhole":'<path d="M12 1L20.2169 2.82598C20.6745 2.92766 21 3.33347 21 3.80217V13.7889C21 15.795 19.9974 17.6684 18.3282 18.7812L12 23L5.6718 18.7812C4.00261 17.6684 3 15.795 3 13.7889V3.80217C3 3.33347 3.32553 2.92766 3.78307 2.82598L12 1ZM12 3.04879L5 4.60434V13.7889C5 15.1263 5.6684 16.3752 6.7812 17.1171L12 20.5963L17.2188 17.1171C18.3316 16.3752 19 15.1263 19 13.7889V4.60434L12 3.04879ZM12 7C13.1046 7 14 7.89543 14 9C14 9.73984 13.5983 10.3858 13.0011 10.7318L13 15H11L10.9999 10.7324C10.4022 10.3866 10 9.74025 10 9C10 7.89543 10.8954 7 12 7Z" fill="currentColor"/>',"split-cells-horizontal":'<path d="M20 3C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20ZM11 5H5V19H11V15H13V19H19V5H13V9H11V5ZM15 9L18 12L15 15V13H9V15L6 12L9 9V11H15V9Z" fill="currentColor"/>',stack:'<path d="M20.0833 15.1999L21.2854 15.9212C21.5221 16.0633 21.5989 16.3704 21.4569 16.6072C21.4146 16.6776 21.3557 16.7365 21.2854 16.7787L12.5144 22.0412C12.1977 22.2313 11.8021 22.2313 11.4854 22.0412L2.71451 16.7787C2.47772 16.6366 2.40093 16.3295 2.54301 16.0927C2.58523 16.0223 2.64413 15.9634 2.71451 15.9212L3.9166 15.1999L11.9999 20.0499L20.0833 15.1999ZM20.0833 10.4999L21.2854 11.2212C21.5221 11.3633 21.5989 11.6704 21.4569 11.9072C21.4146 11.9776 21.3557 12.0365 21.2854 12.0787L11.9999 17.6499L2.71451 12.0787C2.47772 11.9366 2.40093 11.6295 2.54301 11.3927C2.58523 11.3223 2.64413 11.2634 2.71451 11.2212L3.9166 10.4999L11.9999 15.3499L20.0833 10.4999ZM12.5144 1.30864L21.2854 6.5712C21.5221 6.71327 21.5989 7.0204 21.4569 7.25719C21.4146 7.32757 21.3557 7.38647 21.2854 7.42869L11.9999 12.9999L2.71451 7.42869C2.47772 7.28662 2.40093 6.97949 2.54301 6.7427C2.58523 6.67232 2.64413 6.61343 2.71451 6.5712L11.4854 1.30864C11.8021 1.11864 12.1977 1.11864 12.5144 1.30864ZM11.9999 3.33233L5.88723 6.99995L11.9999 10.6676L18.1126 6.99995L11.9999 3.33233Z" fill="currentColor"/>',star:'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26ZM12.0006 15.968L16.2473 18.3451L15.2988 13.5717L18.8719 10.2674L14.039 9.69434L12.0006 5.27502L9.96214 9.69434L5.12921 10.2674L8.70231 13.5717L7.75383 18.3451L12.0006 15.968Z" fill="currentColor"/>',"star-fill":'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26Z" fill="currentColor"/>',"sticky-note":'<path d="M21 15L15 20.996L4.00221 21C3.4487 21 3 20.5551 3 20.0066V3.9934C3 3.44476 3.44495 3 3.9934 3H20.0066C20.5552 3 21 3.45576 21 4.00247V15ZM19 5H5V19H13V14C13 13.4872 13.386 13.0645 13.8834 13.0067L14 13L19 12.999V5ZM18.171 14.999L15 15V18.169L18.171 14.999Z" fill="currentColor"/>',stop:'<path d="M7 7V17H17V7H7ZM6 5H18C18.5523 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5Z" fill="currentColor"/>',subtract:'<path d="M5 11V13H19V11H5Z" fill="currentColor"/>',survey:'<path d="M17 2V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7V2H17ZM7 6H5V20H19V6H17V8H7V6ZM9 16V18H7V16H9ZM9 13V15H7V13H9ZM9 10V12H7V10H9ZM15 4H9V6H15V4Z" fill="currentColor"/>',task:'<path d="M19 4H5V20H19V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H19.9997C20.5519 2 20.9996 2.44772 20.9997 3L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11.2929 13.1213L15.5355 8.87868L16.9497 10.2929L11.2929 15.9497L7.40381 12.0607L8.81802 10.6464L11.2929 13.1213Z" fill="currentColor"/>',terminal:'<path d="M10.9999 12L3.92886 19.0711L2.51465 17.6569L8.1715 12L2.51465 6.34317L3.92886 4.92896L10.9999 12ZM10.9999 19H20.9999V21H10.9999V19Z" fill="currentColor"/>',"terminal-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM12 15H18V17H12V15ZM8.66685 12L5.83842 9.17157L7.25264 7.75736L11.4953 12L7.25264 16.2426L5.83842 14.8284L8.66685 12Z" fill="currentColor"/>',text:'<path d="M13 6V21H11V6H5V4H19V6H13Z" fill="currentColor"/>',"text-wrap":'<path d="M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z" fill="currentColor"/>',time:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM13 12H17V14H11V7H13V12Z" fill="currentColor"/>',tools:'<path d="M5.32943 3.27158C6.56252 2.8332 7.9923 3.10749 8.97927 4.09446C10.1002 5.21537 10.3019 6.90741 9.5843 8.23385L20.293 18.9437L18.8788 20.3579L8.16982 9.64875C6.84325 10.3669 5.15069 10.1654 4.02952 9.04421C3.04227 8.05696 2.7681 6.62665 3.20701 5.39332L5.44373 7.63C6.02952 8.21578 6.97927 8.21578 7.56505 7.63C8.15084 7.04421 8.15084 6.09446 7.56505 5.50868L5.32943 3.27158ZM15.6968 5.15512L18.8788 3.38736L20.293 4.80157L18.5252 7.98355L16.7574 8.3371L14.6361 10.4584L13.2219 9.04421L15.3432 6.92289L15.6968 5.15512ZM8.97927 13.2868L10.3935 14.7011L5.09018 20.0044C4.69966 20.3949 4.06649 20.3949 3.67597 20.0044C3.31334 19.6417 3.28744 19.0699 3.59826 18.6774L3.67597 18.5902L8.97927 13.2868Z" fill="currentColor"/>',"ubuntu-fill":'<path d="M22.001 12C22.001 17.5224 17.524 22 12.001 22C6.47798 22 2.00098 17.5224 2.00098 12C2.00098 6.4771 6.47833 2 12.001 2C17.524 2 22.001 6.4771 22.001 12ZM5.20128 10.6642C4.46363 10.6642 3.86613 11.2623 3.86613 12C3.86613 12.7372 4.46363 13.3349 5.20128 13.3349C5.93848 13.3349 6.53628 12.7372 6.53628 12C6.53628 11.2622 5.93848 10.6642 5.20128 10.6642ZM14.7337 16.7325C14.0954 17.1015 13.8763 17.9175 14.2454 18.5558C14.6137 19.1942 15.4296 19.4137 16.0682 19.0448C16.7067 18.6759 16.9257 17.8595 16.5571 17.2208C16.1884 16.5832 15.3721 16.3644 14.7337 16.7325V16.7325ZM8.10133 12C8.10133 10.6808 8.75663 9.5152 9.75958 8.80915L8.78348 7.174C7.61518 7.955 6.74598 9.1485 6.38498 10.545C6.80648 10.8895 7.07613 11.4131 7.07613 12C7.07613 12.586 6.80643 13.1097 6.38493 13.4543C6.74583 14.8516 7.61503 16.0448 8.78343 16.826L9.75953 15.1903C8.75653 14.4848 8.10128 13.32 8.10128 12L8.10133 12ZM12.001 8.09975C14.0385 8.09975 15.7098 9.66175 15.8853 11.654L17.788 11.6261C17.6942 10.1551 17.0518 8.83495 16.0645 7.86435C15.5568 8.05565 14.9705 8.02685 14.4637 7.7342C13.9559 7.4412 13.6376 6.9472 13.5506 6.4104C13.0571 6.27455 12.538 6.2005 12.001 6.2005C11.0782 6.2005 10.2053 6.41685 9.43058 6.80035L10.3582 8.46275C10.8577 8.23045 11.4141 8.09975 12.001 8.09975ZM12.001 15.8995C11.4141 15.8995 10.8576 15.7691 10.3585 15.537L9.43063 17.1991C10.2055 17.5831 11.0782 17.8004 12.001 17.8004C12.538 17.8004 13.0575 17.7255 13.5506 17.5888C13.6376 17.0526 13.9561 16.5586 14.4638 16.2652C14.971 15.9726 15.5569 15.9435 16.0646 16.1349C17.0519 15.1642 17.6942 13.8441 17.7881 12.3732L15.8846 12.3456C15.7099 14.338 14.0386 15.8996 12.0011 15.8996L12.001 15.8995ZM14.7334 7.26675C15.372 7.6349 16.1883 7.4169 16.5566 6.77845C16.9257 6.1396 16.7071 5.32395 16.0683 4.95505C15.4296 4.58605 14.6138 4.8048 14.2447 5.44345C13.8763 6.08195 14.0954 6.89795 14.7334 7.2667V7.26675Z" fill="currentColor"/>',unpin:'<path d="M20.9701 17.1716 19.5559 18.5858 16.0214 15.0513 15.9476 15.1251 15.2405 18.6606 13.8263 20.0748 9.58369 15.8322 4.63394 20.7819 3.21973 19.3677 8.16947 14.418 3.92683 10.1753 5.34105 8.7611 8.87658 8.05399 8.95029 7.98028 5.41373 4.44371 6.82794 3.0295 20.9701 17.1716ZM10.3645 9.39449 9.86261 9.8964 7.04072 10.4608 13.5409 16.9609 14.1052 14.139 14.6071 13.6371 10.3645 9.39449ZM18.7761 9.46821 17.4356 10.8087 18.8498 12.2229 20.1903 10.8824 20.8974 11.5895 22.3116 10.1753 13.8263 1.69003 12.4121 3.10425 13.1192 3.81135 11.7787 5.15185 13.1929 6.56607 14.5334 5.22557 18.7761 9.46821Z" fill="currentColor"/>',user:'<path d="M4 22C4 17.5817 7.58172 14 12 14C16.4183 14 20 17.5817 20 22H18C18 18.6863 15.3137 16 12 16C8.68629 16 6 18.6863 6 22H4ZM12 13C8.685 13 6 10.315 6 7C6 3.685 8.685 1 12 1C15.315 1 18 3.685 18 7C18 10.315 15.315 13 12 13ZM12 11C14.21 11 16 9.21 16 7C16 4.79 14.21 3 12 3C9.79 3 8 4.79 8 7C8 9.21 9.79 11 12 11Z" fill="currentColor"/>',voiceprint:'<path d="M5 7H7V17H5V7ZM1 10H3V14H1V10ZM9 2H11V20H9V2ZM13 4H15V22H13V4ZM17 7H19V17H17V7ZM21 10H23V14H21V10Z" fill="currentColor"/>',window:'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM20 11H4V19H20V11ZM20 5H4V9H20V5ZM11 6V8H9V6H11ZM7 6V8H5V6H7Z" fill="currentColor"/>',windows:'<path d="M21.001 2.5V21.5L3.00098 19.5V4.5L21.001 2.5ZM19.001 12.999L12.001 13V18.487L19.001 19.2655V12.999ZM5.00098 17.7099L10.001 18.265V13L5.00098 12.999V17.7099ZM19.001 10.999V4.73453L12.001 5.512V11L19.001 10.999ZM10.001 5.734L5.00098 6.29009V10.999L10.001 11V5.734Z" fill="currentColor"/>'},A2="pichamber-icon-sprite";let Af=!1;function Cj(){if(Af||typeof document>"u")return;const e=document.body;if(!e)return;if(document.getElementById(A2)){Af=!0;return}const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.id=A2,n.setAttribute("aria-hidden","true"),n.style.display="none",n.innerHTML=Object.entries($w).map(([r,s])=>`<symbol id="oc-${r}" viewBox="0 0 24 24">${s}</symbol>`).join(""),e.insertBefore(n,e.firstChild),Af=!0}const $=p.memo(({name:e,className:t,...n})=>(typeof document<"u"&&Cj(),c.jsx("svg",{className:R("remixicon",t),viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",...n,children:c.jsx("use",{href:`#oc-${e}`})})));$.displayName="Icon";let Wc=0;function kj(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function gu({...e}){return c.jsx(AC,{...e})}function Mj({asChild:e,children:t,...n}){const r=kj(e,t);return c.jsx(HC,{"data-slot":"dialog-trigger",...n,...r})}function Ij({...e}){return c.jsx(DC,{...e})}const zw=H.forwardRef(({className:e,...t},n)=>(H.useEffect(()=>(Wc+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Wc=Math.max(0,Wc-1),Wc===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),c.jsx(OC,{ref:n,"data-slot":"dialog-overlay",className:R("oc-glass-backdrop fixed inset-0 z-50 bg-black/25 dark:bg-black/40","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",e),...t})));zw.displayName="DialogOverlay";function yu({className:e,children:t,showCloseButton:n=!0,...r}){return c.jsxs(Ij,{children:[c.jsx(zw,{className:"rounded-none"}),c.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none p-4",children:c.jsxs(NC,{"data-slot":"dialog-content","data-state-slot":"dialog",className:R("relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]","data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]",e),...r,children:[t,n&&c.jsxs(LC,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[open]:bg-interactive-active data-[open]:text-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx($,{name:"close"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})})]})}function vu({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Ej({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",e),...t})}function xu({className:e,...t}){return c.jsx(RC,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",e),...t})}function o1({className:e,...t}){return c.jsx(PC,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",e),...t})}function _j(...e){return t=>{for(const n of e)n&&(typeof n=="function"?n(t):n.current=t)}}function jj(e,t){const n={...t};for(const r in e){const s=t[r],o=e[r];/^on[A-Z]/.test(r)&&typeof s=="function"&&typeof o=="function"?n[r]=(...i)=>{o(...i),s(...i)}:r==="className"&&typeof s=="string"&&typeof o=="string"?n[r]=`${o} ${s}`:r==="style"&&typeof s=="object"&&typeof o=="object"?n[r]={...o,...s}:n[r]=o}return n}const Tj=H.forwardRef(function({children:t,...n},r){if(!H.isValidElement(t))return null;const s=t;return H.cloneElement(s,{...jj(s.props,n),ref:_j(r,s.ref)})}),Aj=["bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","text-[var(--primary-base)]","border border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","active:bg-[color-mix(in_srgb,var(--primary-base)_22%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--primary-base)_30%,transparent)]"].join(" "),Nj=["bg-[color-mix(in_srgb,var(--status-error)_7%,var(--background))]","text-[var(--status-error)]","border border-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-error)_11%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-error)_16%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-error)_20%,transparent)]"].join(" "),Lj=["bg-[color-mix(in_srgb,var(--status-info)_4%,var(--background))]","text-[var(--status-info)]","border border-[color-mix(in_srgb,var(--status-info)_8%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-info)_7%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-info)_10%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-info)_7%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-info)_12%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-info)_10%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-info)_14%,transparent)]"].join(" "),Rj=D5(["group relative inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] typography-ui-label font-medium tracking-[0.01em] shrink-0 select-none","transition-[background-color,border-color,color,opacity] duration-150 ease-out outline-none","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive","disabled:pointer-events-none disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],{variants:{variant:{default:Aj,solid:R("bg-[var(--primary-base)] text-[var(--primary-foreground)] border border-transparent hover:bg-[var(--primary-hover)] active:opacity-90","disabled:bg-[var(--surface-elevated)] disabled:text-foreground disabled:border-border/60"),destructive:R(Nj,"focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40"),info:Lj,neutral:"bg-interactive-hover text-foreground border border-border/60 hover:bg-interactive-active",outline:"bg-[var(--surface-elevated)] text-foreground border border-border/60 hover:bg-interactive-hover hover:text-foreground",chip:R("border border-border/60 bg-transparent text-foreground hover:bg-interactive-hover hover:text-foreground","aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-pressed:text-[var(--primary-base)]","aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-pressed:hover:text-[var(--primary-base)]","dark:aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-checked:text-[var(--primary-base)]","aria-checked:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-checked:hover:text-[var(--primary-base)]","dark:aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-checked:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]"),secondary:"bg-interactive-hover text-foreground hover:bg-interactive-active",ghost:"text-foreground hover:bg-interactive-hover hover:text-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-3.5 has-[>svg]:px-3",sm:"h-8 gap-1.5 px-2.5 has-[>svg]:px-2 rounded-[9px] supports-[corner-shape:squircle]:rounded-[50px]",xs:"h-6 gap-1 px-2 typography-meta has-[>svg]:px-1.5 rounded-[7px] supports-[corner-shape:squircle]:rounded-[50px]",lg:"h-10 px-4 has-[>svg]:px-3.5 rounded-[12px] supports-[corner-shape:squircle]:rounded-[50px]",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function be({className:e,variant:t,size:n,asChild:r=!1,type:s,...o}){const i=r?Tj:"button",a=r?s===void 0?{}:{type:s}:{type:s??"button"};return c.jsx(i,{"data-slot":"button",className:R(Rj({variant:t,size:n,className:e})),...a,...o})}const i1="oc-glass-popover oc-glass-floating app-region-no-drag transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1",Pj="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",Dj="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",Oj="bg-border -mx-1 my-0.5 h-px",bu=H.createContext(null),Hj=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function Uw(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function Fa({...e}){const[t,n]=H.useState(null),r=H.useMemo(()=>({portalContainer:t,setPortalContainer:n}),[t]);return c.jsx(bu.Provider,{value:r,children:c.jsx(FC,{...e})})}function Ba({asChild:e,children:t,onPointerDownCapture:n,onFocusCapture:r,...s}){const o=H.useContext(bu),i=H.useCallback(l=>{if(!o)return;const d=l instanceof HTMLElement?l:null;o.setPortalContainer(Hj(d))},[o]),a=Uw(e,t);return c.jsx(BC,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:l=>{i(l.currentTarget),n?.(l)},onFocusCapture:l=>{i(l.currentTarget),r?.(l)},...s,...a})}function Va({className:e,sideOffset:t=4,align:n,side:r,alignOffset:s,portalToBody:o=!1,positionerClassName:i,style:a,children:l,onCloseAutoFocus:d,...f}){const u=H.useContext(bu);return c.jsx(O5,{container:o?void 0:u?.portalContainer||void 0,children:c.jsx(H5,{sideOffset:t,align:n,side:r,alignOffset:s,className:R("app-region-no-drag z-50",i),children:c.jsx(F5,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...a},className:R(i1,e),...f,children:l})})})}function ur({className:e,inset:t,variant:n="default",asChild:r,children:s,onSelect:o,onClick:i,...a}){const l=Uw(r,s),d=f=>{i?.(f),f.defaultPrevented||o?.(f)};return c.jsx(VC,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:R(Pj,e),...a,onClick:d,...l})}function Fj({...e}){return c.jsx(zC,{"data-slot":"dropdown-menu-radio-group",...e})}function Bj({className:e,children:t,...n}){return c.jsxs(UC,{"data-slot":"dropdown-menu-radio-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[checked]:bg-interactive-selection data-[checked]:text-interactive-selection-foreground relative flex cursor-pointer items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",e),...n,children:[c.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:c.jsx(qC,{children:c.jsx($,{name:"check",className:"size-3"})})}),t]})}function uJ({className:e,inset:t,...n}){return c.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":t,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",e),...n})}function Vj({className:e,...t}){return c.jsx($C,{"data-slot":"dropdown-menu-separator",className:R(Oj,e),...t})}function fJ({...e}){return c.jsx(WC,{...e})}function hJ({className:e,inset:t,children:n,...r}){return c.jsxs(KC,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:R(Dj,e),...r,children:[n,c.jsx($,{name:"arrow-right-s",className:"ml-auto size-3.5"})]})}function pJ({className:e,children:t,...n}){const r=H.useContext(bu);return c.jsx(O5,{container:r?.portalContainer||void 0,children:c.jsx(H5,{className:"z-50",children:c.jsx(F5,{"data-slot":"dropdown-menu-sub-content",style:{color:"var(--surface-elevated-foreground)"},className:R(i1,e),...n,children:t})})})}const $j={local:"This computer",lan:"Local network",tailscale:"Tailscale",relay:"PiChamber Relay",tunnel:"Tunnel",direct:"Direct"},a1={checking:{label:"Checking",tone:"info",description:"Probing the server for reachability."},connected:{label:"Connected",tone:"success",description:"The server answered and accepted the saved credential."},reachable:{label:"Reachable",tone:"info",description:"The server answered, but sign-in state is not verified."},offline:{label:"Offline",tone:"error",description:"The server did not answer."},"sign-in-required":{label:"Sign-in required",tone:"warning",description:"The server rejected the saved credential."},"update-required":{label:"Update required",tone:"error",description:"The server version is too old to connect."},"update-recommended":{label:"Update recommended",tone:"warning",description:"The server works, but a newer version is available."},incompatible:{label:"Incompatible",tone:"error",description:"The server version cannot work with this app."},"wrong-service":{label:"Wrong service",tone:"error",description:"The address answered, but it is not a PiChamber server."},unknown:{label:"Unknown",tone:"muted",description:"This server has not been probed yet."}},qw=e=>{switch(e){case"ok":return"connected";case"auth":return"sign-in-required";case"update-required":return"update-required";case"update-recommended":return"update-recommended";case"incompatible":return"incompatible";case"wrong-service":return"wrong-service";case"unreachable":return"offline";case"reachable":return"reachable"}},zj=(e,t)=>e?{status:qw(e.status),latencyMs:Math.max(0,Math.round(e.latencyMs)),refreshing:t}:{status:t?"checking":"unknown",latencyMs:null,refreshing:t},Uj=e=>e==="offline"||e==="wrong-service"||e==="incompatible",qj=e=>{try{return new URL(e).hostname.toLowerCase()}catch{return null}},Wj=e=>/^10\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^192\.168\./.test(e)||/^169\.254\./.test(e),Kj=e=>Wj(e)?!0:e.endsWith(".local")||e.endsWith(".lan")||e.endsWith(".home")||e.endsWith(".internal"),Gj=e=>{const t=qj(e);return t?t.endsWith(".ts.net")?"tailscale":t.endsWith(".trycloudflare.com")||t.endsWith(".cfargotunnel.com")?"tunnel":Kj(t)?"lan":"direct":"direct"},Kc=(e,t)=>({kind:e,label:$j[e],address:t}),Zj=(e,t)=>e.kind===t.kind&&(e.address||null)===(t.address||null),Nf=(e,t)=>{try{return e?e(t):t}catch{return t}},Yj=(e,t)=>{const n=zj(t.probe,t.probing===!0),r=t.redactUrl?Nf(t.redactUrl,e.label):e.label;let s;if(t.isLocal){const a=(t.localOrigin||e.apiUrl||e.url||"").trim();s=[Kc("local",a?Nf(t.redactUrl,a):null)]}else if(e.relay&&!e.apiUrl)s=[Kc("relay",null)];else{const a=Nf(t.redactUrl,e.apiUrl||e.url),l=Kc(Gj(e.apiUrl||e.url),a);s=e.relay?[l,Kc("relay",null)]:[l]}let o=null;t.probe&&qw(t.probe.status)==="connected"&&(t.probe.via==="relay"?o=s.find(a=>a.kind==="relay")||s[0]||null:o=s.find(a=>a.kind!=="relay")||s[0]||null);const i=!!e.relay&&!e.apiUrl&&!t.isLocal;return{id:e.id,label:r,isCurrent:t.isCurrent,isDefault:t.isDefault,isLocal:t.isLocal,routes:s,activeRoute:o,status:n.status,latencyMs:n.latencyMs,canEdit:!t.isLocal&&!i,canRemove:!t.isLocal,canOpenInNewWindow:!0}},Xj=e=>[...e].sort((t,n)=>Number(n.isCurrent)-Number(t.isCurrent)||Number(n.isDefault)-Number(t.isDefault)||t.label.localeCompare(n.label)),Jj=e=>e.activeRoute?.address?e.activeRoute.address:e.routes.find(t=>t.address)?.address||null,Al=e=>`${e.kind}::${e.address??""}`,Qj=e=>{if(e.routes.length===0)return null;const t=e.activeRoute;if(t){const n=e.routes.find(r=>Zj(r,t));if(n)return n}return e.routes[0]??null},eT=(e,t)=>e.routes.find(n=>Al(n)===t)??null,tT=(e,t)=>{const n=a1[e].tone;return R("h-2 w-2 rounded-full flex-shrink-0",n==="success"&&"bg-status-success",n==="warning"&&"bg-status-warning",n==="error"&&"bg-status-error",n==="info"&&"bg-status-info",n==="muted"&&"bg-muted-foreground/40",t&&"animate-pulse")},nT=(e,t)=>{const n=a1[e].tone;return R(t?"typography-meta block truncate":"typography-micro truncate",n==="success"&&"text-[var(--status-success)]",n==="warning"&&"text-[var(--status-warning)]",n==="error"&&"text-[var(--status-error)]",n==="info"&&"text-[var(--status-info)]",n==="muted"&&"text-muted-foreground")},rT="typography-micro truncate text-muted-foreground";function sT({item:e,onSelectRoute:t}){const n=Qj(e);return n?typeof t=="function"&&e.routes.length>1?c.jsx("span",{className:"flex min-w-0 items-center gap-1.5",children:c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsxs("button",{type:"button","data-route-picker":"",className:"inline-flex min-w-0 max-w-full items-center gap-0.5 rounded typography-micro text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":`Connection route for ${e.label}: ${n.label}`,children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-subtle-foreground",children:"·"}),c.jsx("span",{className:"truncate",children:n.label}),c.jsx($,{name:"arrow-down-s",className:"size-3 shrink-0 opacity-70","aria-hidden":"true"})]})}),c.jsx(Va,{align:"start",portalToBody:!0,children:c.jsx(Fj,{value:Al(n),onValueChange:s=>{const o=eT(e,s);o&&t?.(e,o)},children:e.routes.map(s=>c.jsx(Bj,{value:Al(s),children:s.label},Al(s)))})})]})}):c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-subtle-foreground",children:"·"}),c.jsx("span",{className:rT,children:n.label})]}):null}const oT=({item:e,layout:t="comfortable",guardDefaultByStatus:n=!1,switchLabel:r="Switch",refreshing:s=!1,pending:o=!1,actionsDisabled:i=!1,onSwitch:a,onSetDefault:l,onOpenInNewWindow:d,onEdit:f,onRemove:u,onSelectRoute:h})=>{const[m,g]=H.useState(!1);H.useEffect(()=>{g(!1)},[e.id]);const x=a1[e.status],b=Uj(e.status),S=Jj(e),y=t==="touch",v=i||o,C=typeof a=="function",w=e.canOpenInNewWindow&&typeof d=="function",I=e.canEdit&&typeof f=="function",E=e.canRemove&&typeof u=="function",T=C||w||I||E,A=v||n&&!e.isDefault&&b,j=v||e.isCurrent,k=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:R(tT(e.status,s||e.status==="checking"),y&&"mt-1.5"),"aria-hidden":"true"}),c.jsxs("span",{className:R("flex-1 min-w-0",y?"space-y-1":"space-y-0.5"),children:[c.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0",children:[c.jsx("span",{className:"typography-ui-label font-medium truncate text-foreground min-w-0",children:e.label}),c.jsx(sT,{item:e,onSelectRoute:h}),e.isCurrent&&c.jsx("span",{className:"typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50",children:"Current"})]}),c.jsxs("span",{className:nT(e.status,y),title:x.description,children:[x.label,typeof e.latencyMs=="number"&&(e.status==="connected"||e.status==="reachable")?` · ${e.latencyMs}ms`:"",s&&e.status!=="checking"?" · checking":""]}),S?c.jsx("span",{className:R("block truncate font-mono text-subtle-foreground",y?"typography-meta":"typography-micro"),children:S}):null]})]});return c.jsxs("div",{className:R("group flex gap-2 overflow-hidden rounded-md px-2.5 py-2",y?"flex-col rounded-xl bg-[var(--surface-elevated)] px-3.5 py-3":"items-center",y&&e.isCurrent&&"bg-[var(--interactive-selection)]/25"),children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 gap-2",y?"items-start":"items-center"),children:[C&&!e.isCurrent?c.jsxs("div",{className:R("relative flex gap-2 flex-1 min-w-0",y?"items-start":"items-center",j&&"opacity-70"),children:[c.jsx("button",{type:"button",className:"absolute inset-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>a?.(e),disabled:j,"aria-label":`${r} to ${e.label}`}),o?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):null,c.jsx("span",{className:R("pointer-events-none flex gap-2 flex-1 min-w-0 [&_[data-route-picker]]:pointer-events-auto [&_[data-route-picker]]:relative",y?"items-start":"items-center"),children:k})]}):c.jsx("div",{className:R("flex gap-2 flex-1 min-w-0",y?"items-start":"items-center"),"aria-label":e.isCurrent?`Current server ${e.label}`:void 0,children:k}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[typeof l=="function"&&c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",y?"h-11 w-11":"h-8 w-8","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e.isDefault?"text-primary hover:text-primary/80":"text-subtle-foreground hover:text-primary/80",A&&"opacity-40 cursor-not-allowed"),onClick:()=>l?.(e),disabled:A,"aria-label":e.isDefault?`Default server ${e.label}`:`Set ${e.label} as default server`,"aria-pressed":e.isDefault,title:e.isDefault?"Default":"Set as default",children:c.jsx($,{name:e.isDefault?"star-fill":"star",className:"h-4 w-4","aria-hidden":"true"})}),T&&c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center text-subtle-foreground hover:text-foreground hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-40",y?"h-11 w-11":"h-8 w-8"),"aria-label":`Actions for ${e.label}`,disabled:v,children:c.jsx($,{name:"more",className:"h-4 w-4","aria-hidden":"true"})})}),c.jsxs(Va,{align:"end",portalToBody:!0,children:[C&&c.jsx(ur,{disabled:j,onSelect:()=>a?.(e),children:e.isCurrent?"Current server":`${r} to this server`}),w&&c.jsx(ur,{disabled:v||b,onSelect:()=>d?.(e),children:b?"Server unreachable":"Open in new window"}),I&&c.jsx(ur,{disabled:v,onSelect:()=>f?.(e),children:"Edit"}),E&&(C||w||I)&&c.jsx(Vj,{}),E&&c.jsx(ur,{variant:"destructive",disabled:v,onSelect:()=>g(!0),children:"Remove"})]})]})]})]}),m&&E&&c.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2",children:[c.jsx("span",{className:"typography-ui-label flex-1 min-w-0 text-foreground",children:`Remove ${e.label}?`}),c.jsx(be,{type:"button",variant:"destructive",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,disabled:v,onClick:()=>{g(!1),u?.(e)},"aria-label":`Confirm remove ${e.label}`,children:"Remove"}),c.jsx(be,{type:"button",variant:"outline",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,onClick:()=>g(!1),"aria-label":`Keep ${e.label}`,children:"Keep"})]})]})},iT=({items:e,emptyMessage:t="No servers yet.",pendingId:n=null,...r})=>e.length===0?c.jsx("p",{className:"typography-meta text-muted-foreground",children:t}):c.jsx("div",{className:"space-y-1",role:"list","aria-label":"Servers",children:e.map(s=>c.jsx("div",{role:"listitem",children:c.jsx(oT,{item:s,pending:n===s.id,...r})},s.id))}),aT=()=>{const e=new Map;return(t,n)=>{const r=e.get(t);if(r)return r;const s=n().finally(()=>{e.get(t)===s&&e.delete(t)});return e.set(t,s),s}},cT=aT(),lT=(e="",t="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:e,value:t}),dT=e=>e.trim().toLowerCase()==="authorization",Lf=e=>{const t={};for(const n of e){const r=n.name.trim(),s=n.value.trim();r&&s&&!dT(r)&&(t[r]=s)}return Object.keys(t).length>0?t:void 0},mJ=e=>Object.entries(e||{}).map(([t,n])=>lT(t,n)),N2=async e=>{const t=await yr(e);t.ok||console.error("Failed to copy to clipboard:",t.error)},bd=e=>e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(bd).join(" ").trim():H.isValidElement(e)?bd(e.props?.children):"",uT=e=>typeof e=="function"?e():e,L2=(e,t)=>{const n=bd(uT(t?.description));return n.length>0?n:bd(e)},Ce={...ui,success:(e,t)=>ui.success(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),info:(e,t)=>ui.info(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),error:(e,t)=>ui.error(e,{...t,action:t?.action||{label:"Copy",onClick:()=>N2(L2(e,t))}}),warning:(e,t)=>ui.warning(e,{...t,action:t?.action||{label:"Copy",onClick:()=>N2(L2(e,t))}})},Nl=new Map,fT=()=>Object.fromEntries(Nl),R2={status:"unreachable",latencyMs:0},Rf=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",P2=e=>{const t=Pr(e);if(!t)return e.trim();try{const n=new URL(t);return n.pathname.endsWith("/")||(n.pathname=`${n.pathname}/`),n.toString()}catch{return t}},D2=async()=>Vr()?US().catch(()=>""):"",Pf=e=>{const t=e.trim();if(t)try{window.location.assign(t)}catch{window.location.href=t}},hT="Invalid PiChamber connection link.",Oi="Invalid URL (must be http/https)",pT=e=>(e instanceof Error?e.message:String(e))==="invalid-connect-link"?hT:Oi;function mT(e){const t=e?.autoLoad!==!1,[n,r]=H.useState([]),[s,o]=H.useState(null),[i,a]=H.useState(()=>OS()),[l,d]=H.useState(()=>fT()),[f,u]=H.useState(!1),[h,m]=H.useState(!1),[g,x]=H.useState(!1),[b,S]=H.useState(null),[y,v]=H.useState(null),[C,w]=H.useState(0);H.useEffect(()=>Zt(()=>w(F=>F+1)),[]);const I=H.useMemo(()=>{const F=zS(i),U=n.map(P=>({...P,url:Pr(P.url)||P.url}));return[F,...U]},[n,i]),E=H.useMemo(()=>HS(I),[I,C]),T=H.useMemo(()=>{const F=s||gn;return I.find(U=>U.id===F)?.label||"Local"},[I,s]),A=H.useMemo(()=>{const F=I.map(U=>Yj(U,{isCurrent:U.id===E.id,isDefault:(s||gn)===U.id,isLocal:U.id===gn,probe:l[U.id]||null,probing:f,localOrigin:i,redactUrl:qn}));return Xj(F)},[I,E,s,l,f,i]),j=H.useCallback(async()=>{if(xt()){m(!0),v(null);try{const F=await vm();F.localOrigin&&a(F.localOrigin),r(F.hosts||[]),o(F.defaultHostId??null)}catch(F){v(F instanceof Error?F.message:"Failed to load"),r([]),o(null)}finally{m(!1)}}},[]);H.useEffect(()=>{t&&j()},[t,j]);const k=H.useCallback(async(F,U)=>{x(!0),v(null);try{await Zl({hosts:F,defaultHostId:U,initialHostChoiceCompleted:!0}),r(F),o(U)}catch(P){throw v(P instanceof Error?P.message:"Failed to save"),P}finally{x(!1)}},[]),_=H.useCallback(async(F,U)=>cT(F.id,async()=>{const P=F.id===gn?U:F.clientToken||"",q=F.requestHeaders||null,B=async()=>{const K=await Zg(F.relay,{clientToken:P,requestHeaders:q}).catch(()=>({status:"unreachable",latencyMs:0}));return{status:K.status,latencyMs:K.latencyMs,...K.status==="ok"?{via:"relay"}:{}}};if(F.relay&&!F.apiUrl)return B();const ee=Pr(Vr()?ml(F):F.url);if(!ee)return{...R2};const G=await Xu(ee,{clientToken:P||null,requestHeaders:q,expectedServerId:F.serverId??F.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Rf(G.status)&&F.relay){const K=await B();if(K.status==="ok")return K}return{status:G.status,latencyMs:G.latencyMs}}),[]),M=H.useCallback(async F=>{if(!xt())return{};u(!0);try{const U=await D2(),P=await Promise.all(F.map(async q=>[q.id,await _(q,U)]));for(const[q,B]of P)Nl.set(q,B);return d(q=>({...q,...Object.fromEntries(P)})),Object.fromEntries(P)}finally{u(!1)}},[_]),L=H.useCallback(async F=>{x(!0),v(null);try{const{hosts:U,hostId:P}=await FS(F,n);return await Zl({hosts:U,defaultHostId:s,initialHostChoiceCompleted:!0}),r(U),{ok:!0,hostId:P}}catch(U){const P=pT(U);return v(P),{ok:!1,error:P}}finally{x(!1)}},[n,s]),O=H.useCallback(async F=>{const U=Gg(F.url);if(!U)return v(Oi),{ok:!1,error:Oi};const P=U.persistedUrl,B={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:F.label.trim()||qn(P),url:P,apiUrl:P,...F.token.trim()?{clientToken:F.token.trim()}:{},...Lf(F.headers)?{requestHeaders:Lf(F.headers)}:{}};try{await k([B,...n],s)}catch{return{ok:!1,error:"Failed to save"}}return U.redeemUrl&&Pf(U.redeemUrl),{ok:!0}},[n,s,k]),N=H.useCallback(async(F,U)=>{const P=Gg(U.url);if(!P)return v(Oi),{ok:!1,error:Oi};const q=P.persistedUrl,B=n.map(ee=>ee.id===F?{...BS(ee,q),label:U.label.trim()||qn(q),clientToken:U.token.trim()||void 0,requestHeaders:Lf(U.headers)}:ee);try{await k(B,s)}catch{return{ok:!1,error:"Failed to save"}}return P.redeemUrl&&Pf(P.redeemUrl),{ok:!0}},[n,s,k]),D=H.useCallback(async F=>{const U=n.filter(q=>q.id!==F),P=s===F?gn:s;try{await k(U,P)}catch{}},[n,s,k]),W=H.useCallback(async F=>{try{await k(n,F)}catch{}},[n,k]),z=H.useCallback(async(F,U)=>{const P=I.find(K=>K.id===F);if(!P)return;const q=(K,se)=>{se&&qS({relayUrl:K.relayUrl,serverId:K.serverId,hostEncPubJwk:K.hostEncPubJwk},se),gl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:P.clientToken||null,runtimeKey:Yu(P),relay:K}),WS(P.id)},B=P.id===gn?i:Pr(P.url)||"",ee=P.id===gn?i:Pr(ml(P))||"",G=!!P.relay&&!P.apiUrl&&P.id!==gn;if(!(!B&&!G)){if(Vr()){if(!ee&&!P.relay)return;S(P.id);try{const K=P.id===gn?await D2():P.clientToken||"",se=l[P.id];if(se?.status==="ok"){se.via==="relay"&&P.relay?q(P.relay):ee?gl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Yu(P)}):P.relay&&q(P.relay),U?.onSwitched?.();return}let le={...R2},oe=null;if(ee){const we=await Xu(ee,{clientToken:K||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));le={status:we.status,latencyMs:we.latencyMs},Rf(we.status)||(oe="direct")}let ue;if(!oe&&P.relay){const we=await Zg(P.relay,{keepTunnel:!0,clientToken:K||null,requestHeaders:P.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));we.status==="ok"&&(le={status:we.status,latencyMs:we.latencyMs,via:"relay"},oe="relay",ue="tunnel"in we?we.tunnel:void 0)}const ye=le;if(Nl.set(P.id,ye),d(we=>({...we,[P.id]:ye})),!oe){Ce.error(`Server "${qn(P.label)}" is unreachable`);return}oe==="relay"&&P.relay?q(P.relay,ue):gl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Yu(P)}),U?.onSwitched?.()}finally{S(null)}return}if(P.id!==gn&&xt()){S(P.id);try{const K=await Xu(B,{clientToken:P.clientToken||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0})),se={status:K.status,latencyMs:K.latencyMs};if(Nl.set(P.id,se),d(le=>({...le,[P.id]:se})),Rf(K.status)){Ce.error(`Server "${qn(P.label)}" is unreachable`);return}}finally{S(null)}}U?.onSwitched?.(),Pf(P2(B))}},[I,i,l]),X=H.useCallback(F=>{const U=I.find(B=>B.id===F);if(!U)return;const P=B=>{Ce.error("Failed to open new window",{description:B instanceof Error?B.message:String(B)})};if(U.relay&&U.id!==gn){VS(U.id).catch(P);return}const q=U.id===gn?i:ml(U);q&&$S(P2(q),{clientToken:U.clientToken||null,requestHeaders:U.requestHeaders||null}).catch(P)},[I,i]);return{remoteHosts:n,allHosts:I,defaultHostId:s,localOrigin:i,current:E,currentDefaultLabel:T,items:A,statusById:l,probing:f,loading:h,saving:g,switchingHostId:b,error:y,setError:v,load:j,probeAll:M,importPairingLink:L,addManualServer:O,updateServer:N,removeServer:D,setDefaultServer:W,switchToHost:z,openInNewWindow:X}}function gT({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){const s=re(u=>u.setSettingsDialogOpen),o=re(u=>u.setSettingsPage),i=mT({autoLoad:!1}),a=H.useCallback(()=>{o("servers"),s(!0),t(!1)},[t,s,o]);H.useEffect(()=>{e&&i.load()},[e]);const l=i.allHosts;if(H.useEffect(()=>{e&&i.probeAll(l)},[e,l]),!xt())return null;const d=xt(),f=c.jsxs(c.Fragment,{children:[n?c.jsx("div",{className:"flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"min-w-0 flex items-baseline gap-1.5 typography-ui-label",children:[c.jsx("span",{className:"font-medium text-foreground",children:"Current"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:qn(i.current.label)}),c.jsx("span",{className:"text-subtle-foreground",children:"•"}),c.jsx("span",{className:"font-medium text-foreground",children:"Default"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:qn(i.currentDefaultLabel)})]}),c.jsx("button",{type:"button",className:R("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,"aria-label":"Refresh servers",children:c.jsx($,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")})})]})}):c.jsxs(vu,{className:"flex-shrink-0",children:[c.jsxs(xu,{className:"flex items-center gap-2",children:[c.jsx($,{name:"server",className:"h-5 w-5"}),"Servers"]}),c.jsx(o1,{children:"Switch between this computer and remote PiChamber servers"})]}),!n&&c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:qn(i.current.label)}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:qn(i.currentDefaultLabel)})]}),c.jsx("div",{className:"flex items-center gap-1",children:c.jsxs(be,{type:"button",size:"sm",variant:"ghost",onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,children:[c.jsx($,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")}),"Refresh"]})})]}),!d&&c.jsx("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Server switcher is limited on this page. Use Local to recover."})}),c.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:c.jsx("div",{className:R(n&&"px-3 py-1"),children:i.loading?c.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading..."}):c.jsx(iT,{items:i.items,layout:n?"touch":"comfortable",guardDefaultByStatus:!0,refreshing:i.probing,pendingId:i.switchingHostId,actionsDisabled:i.saving,onSwitch:u=>{i.switchToHost(u.id,{onSwitched:r})},onSetDefault:u=>{i.setDefaultServer(u.id)},onOpenInNewWindow:u=>i.openInNewWindow(u.id)})})}),c.jsx("div",{className:"flex-shrink-0 border-t border-[var(--interactive-border)]",children:c.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors",onClick:a,children:[c.jsx($,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"typography-ui-label",children:"Add server"})]})}),i.error&&c.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:i.error})]});return n?c.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:f}):c.jsx(gu,{open:e,onOpenChange:t,children:c.jsx(yu,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:f})})}function Ww(){const[e,t]=H.useState(!1);return xt()?c.jsxs(c.Fragment,{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>t(!0),children:[c.jsx($,{name:"server",className:"h-4 w-4"}),"Switch server"]}),c.jsx(gT,{open:e,onOpenChange:t})]}):null}const O2=H.memo(function({checked:t,onChange:n,disabled:r=!1,indeterminate:s,ariaLabel:o,className:i,iconClassName:a}){const l="h-[14px] w-[14px] min-h-[14px] min-w-[14px]",d="h-[10px] w-[10px] min-h-[10px] min-w-[10px]",f=t||s;return c.jsx(GC,{checked:t,onCheckedChange:u=>n(!!u),disabled:r,indeterminate:s,"aria-label":o,className:R("group/checkbox relative flex shrink-0 self-center items-center justify-center rounded-[4px] border outline-none",l,"transition-[background-color,border-color,box-shadow] duration-200 ease-out",f?"border-[color:color-mix(in_srgb,var(--primary-base)_65%,var(--interactive-border))] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[color:color-mix(in_srgb,var(--primary-base)_75%,var(--interactive-border))]":"border-[var(--interactive-border-hover)] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[var(--interactive-border-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-transparent","disabled:cursor-not-allowed disabled:opacity-50",i),children:c.jsx(ZC,{keepMounted:!0,className:R("flex items-center justify-center text-[var(--primary-base)]","data-[unchecked]:hidden",a),children:s?c.jsx($,{name:"subtract",className:R(d,"text-[var(--primary-base)]")}):c.jsx($,{name:"check",className:R(d,"text-[var(--primary-base)]")})})})});function Uo({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:R("text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent","focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none","aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...n})}const c1=({className:e="",width:t=70,height:n=70,isAnimated:r=!1})=>{const s=Dw(),i=H.useId().replace(/[^a-zA-Z0-9_-]/g,""),a=`pc-shimmer-mask-${i}`,l=`pc-shimmer-grad-${i}`,d=H.useMemo(()=>{if(s)return s.currentTheme.colors.surface.foreground;if(typeof window<"u"){const f=getComputedStyle(document.documentElement).getPropertyValue("--splash-stroke").trim();return f||(window.matchMedia("(prefers-color-scheme: dark)").matches?"white":"black")}return"white"},[s]);return c.jsxs("svg",{width:t,height:n,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,role:"img","aria-label":"PiChamber logo",children:[r?c.jsxs(c.Fragment,{children:[c.jsxs("defs",{children:[c.jsxs("linearGradient",{id:l,gradientUnits:"userSpaceOnUse",x1:"0",y1:"0",x2:"100",y2:"100",children:[c.jsx("stop",{offset:"0%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"35%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"50%",stopColor:d,stopOpacity:"1"}),c.jsx("stop",{offset:"65%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"100%",stopColor:d,stopOpacity:"0"})]}),c.jsx("mask",{id:a,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:c.jsxs("g",{fill:"none",children:[c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:"white",opacity:"0.3"}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:"white",opacity:"0.55"}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:"white",opacity:"0.85"}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:"white",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),c.jsx("style",{children:"@keyframes pc-shimmer-anim{0%{transform:translate(-110px,-110px)}100%{transform:translate(110px,110px)}}.pc-shimmer-sweep{animation:pc-shimmer-anim 1.8s cubic-bezier(0.4,0,0.2,1) infinite}@media (prefers-reduced-motion:reduce){.pc-shimmer-sweep{animation:none}}"})]}):null,c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:d,opacity:r?.04:.08}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:d,opacity:r?.08:.14}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:d,opacity:r?.13:.22}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:d,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.6:1}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:d,strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.75:1}),r?c.jsx("g",{mask:`url(#${a})`,children:c.jsx("rect",{x:"-50",y:"-50",width:"200",height:"200",fill:`url(#${l})`,className:"pc-shimmer-sweep"})}):null]})},Kw=({children:e})=>{const t=p.useMemo(()=>({height:"var(--oc-wco-titlebar-height, 0px)",right:"var(--oc-wco-right-inset, 0px)"}),[]);return c.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[c.jsx("div",{className:"app-region-drag fixed left-0 top-0 z-20",style:t,"aria-hidden":!0}),c.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),c.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),c.jsx("div",{className:"app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:e})]})},yT=()=>c.jsx("div",{className:"flex h-full min-h-screen w-full items-center justify-center overflow-hidden bg-background text-foreground",children:c.jsx(c1,{width:120,height:120,isAnimated:!0})}),H2=({onRetry:e,errorType:t="network",retryAfter:n,children:r})=>{const s=t==="rate-limit",o=n?Math.ceil(n/60):1;return c.jsx(Kw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:s?"Too many attempts":"Unable to reach server"}),c.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:s?o>1?`Please wait ${o} minutes before trying again.`:`Please wait ${o} minute before trying again.`:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]}),c.jsx(be,{type:"button",onClick:e,className:"w-full max-w-xs",children:"Retry"}),r]})})},vT=({isTunnelLocked:e,password:t,setPassword:n,passwordInputRef:r,isSubmitting:s,errorMessage:o,setErrorMessage:i,trustDevice:a,setTrustDevice:l,supportsPasskeys:d,passkeyStatus:f,isPasskeyBusy:u,activePasskeyAction:h,showHostSwitcher:m,onSubmit:g,onPasskeyUnlock:x,onPasskeySetupOnly:b})=>{const S=d&&f.hasPasskeys,y=d&&!f.hasPasskeys;return c.jsx(Kw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[c.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[c.jsx("h1",{className:"text-xl font-semibold text-foreground",children:e?"Tunnel access required":"Unlock PiChamber"}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:e?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!e&&c.jsxs("form",{onSubmit:g,className:"w-full space-y-2",children:[S&&c.jsxs(be,{type:"button",variant:"outline",className:"w-full",onClick:()=>{x()},disabled:s||u&&h!=="auth",children:[u?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"lock-unlock",className:"h-4 w-4"}),c.jsx("span",{children:u&&h==="auth"?"Cancel passkey":"Use passkey"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx($,{name:"lock",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-subtle-foreground"}),c.jsx(Uo,{id:"pichamber-ui-password",ref:r,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:t,onChange:v=>{n(v.target.value),o&&i("")},className:"pl-10","aria-invalid":!!o||void 0,"aria-describedby":o?"oc-ui-auth-error":void 0,disabled:s})]}),c.jsx(be,{type:"submit",size:"icon",disabled:!t||s,"aria-label":s?"Unlocking":"Unlock",children:s?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"lock-unlock",className:"h-4 w-4"})})]}),y?c.jsxs("div",{className:"flex items-center justify-between pt-1",children:[c.jsxs("label",{className:"flex items-center gap-2 text-center typography-micro text-muted-foreground",children:[c.jsx(O2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),c.jsx(be,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>{b()},disabled:s,children:u&&h==="register"?"Cancel passkey setup":"Add passkey"})]}):c.jsxs("label",{className:"flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground",children:[c.jsx(O2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),o&&c.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:o})]}),m&&c.jsxs("div",{className:"w-full",children:[c.jsx(Ww,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})})},xT="/auth/passkey/authenticate/options",bT="/auth/passkey/authenticate/verify",wT="/auth/passkey/register/options",ST="/auth/passkey/register/verify",Gw="/api/passkeys",CT="/auth/passkey/status",kT="/api/auth/reset",Ll={enabled:!1,hasPasskeys:!1,passkeyCount:0,rpID:null},_a=async(e,t)=>Rt(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:t===void 0?void 0:JSON.stringify(t)}),Rs=async(e,t)=>{try{const n=await e.json();if(n&&typeof n.error=="string"&&n.error.trim())return n.error}catch{}return t},Df=e=>e instanceof JC&&e.code==="ERROR_CEREMONY_ABORTED",F2=()=>{YC.cancelCeremony()},Zw=()=>typeof window>"u"?{supported:!1,reason:"Passkeys are unavailable outside the browser."}:window.isSecureContext?{supported:!0,reason:""}:{supported:!1,reason:"Passkeys require HTTPS or localhost."},B2=async()=>{const e=Zw();if(!e.supported)throw new Error(e.reason);const t=typeof navigator.userAgent=="string"&&navigator.userAgent.trim()?navigator.userAgent:"This device",n=await _a(wT,{label:t});if(!n.ok)throw new Error(await Rs(n,"Could not start passkey setup."));const{requestId:r,optionsJSON:s}=await n.json(),o=await XC({optionsJSON:s}),i=await _a(ST,{requestId:r,response:o});if(!i.ok)throw new Error(await Rs(i,"Could not finish passkey setup."));return i.json().catch(()=>null)},MT=async(e,t={})=>{const n=Zw();if(!n.supported)throw new Error(n.reason);const r=await _a(xT);if(!r.ok)throw new Error(await Rs(r,"Passkey sign-in is not available right now."));const{requestId:s,optionsJSON:o}=await r.json(),i=await QC({optionsJSON:o}),a=await _a(bT,{requestId:s,response:i,trustDevice:e,issueClientToken:t.issueClientToken===!0,clientLabel:t.clientLabel,clientKind:t.clientKind,dedupeKey:t.dedupeKey});if(!a.ok)throw new Error(await Rs(a,"Passkey sign-in failed."));return a.json().catch(()=>null)},IT=15e3,ET=async()=>{const e=new AbortController,t=setTimeout(()=>e.abort(),IT);try{const n=await Rt(CT,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:e.signal});if(!n.ok)return Ll;const r=await n.json().catch(()=>null);return{enabled:r?.enabled===!0,hasPasskeys:r?.hasPasskeys===!0,passkeyCount:typeof r?.passkeyCount=="number"?r.passkeyCount:0,rpID:typeof r?.rpID=="string"&&r.rpID?r.rpID:null}}finally{clearTimeout(t)}},gJ=async()=>{const e=await Rt(Gw,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(await Rs(e,"Could not load passkeys."));const t=await e.json().catch(()=>null);return Array.isArray(t?.passkeys)?t.passkeys:[]},yJ=async e=>{const t=await Rt(`${Gw}/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(await Rs(t,"Could not remove passkey."));return t.json().catch(()=>null)},vJ=async()=>{const e=await _a(kT);if(!e.ok)throw new Error(await Rs(e,"Could not clear saved authentication."));return e.json().catch(()=>null)},_T=(e,t)=>e.apiBaseUrl===t.apiBaseUrl&&e.runtimeKey===t.runtimeKey,jT=e=>e.shouldUseDesktopShellPasswordLogin?"locked":"error",Yw="/auth/session",TT=4,AT=1500,Xw="pichamber.uiAuth.trustDevice",NT="desktop-local",LT="desktop-local",RT=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},PT=(e,t)=>{const n=Pr(e),r=Pr(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},kp=()=>xt(),DT=e=>{const t=e.replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"},Jw=()=>{if(!xt())return!1;const e=RT();if(!e)return!1;const n=qd()||(typeof window<"u"?window.location.origin:"");if(PT(e,n))return!0;try{const r=Pr(n);return!!(r&&DT(new URL(r).hostname))}catch{return!1}},l1=()=>Jw()?{clientKind:NT,dedupeKey:LT}:{},OT=15e3,HT=async()=>{const e=new AbortController,t=setTimeout(()=>e.abort(),OT);try{return await Rt(Yw,{method:"GET",credentials:"include",headers:{Accept:"application/json"},signal:e.signal})}finally{clearTimeout(t)}},FT=()=>typeof window>"u"?!1:window.localStorage.getItem(Xw)==="true",BT=async(e,t)=>{const n=kp();return await Rt(Yw,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:"PiChamber Desktop",...l1()})})},VT=async()=>{if(!xt())return"";const e=await Rt("/api/client-auth/clients",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:"PiChamber Desktop",...l1()})}).catch(()=>null);if(!e?.ok)return"";const t=await e.json().catch(()=>null);return typeof t?.token=="string"?t.token.trim():""},Of=()=>xt()&&!Jw(),us=()=>({apiBaseUrl:qd(),runtimeKey:Y()}),pt=e=>_T(e,us()),Hf=async(e,t,n,r)=>{if(!xt()||typeof window>"u")return null;const s=await lr("desktop_remote_password_login",{url:n.apiBaseUrl,password:e,trustDevice:t,requestHeaders:r}).catch(()=>null);if(!s||typeof s!="object")return null;const o=s.token,i=s.status;return{token:typeof o=="string"?o.trim():"",...typeof i=="number"?{status:i}:{}}},$T=async(e,t)=>{if(!xt()||!t||!pt(e))return!1;const n=await vm().catch(()=>null);if(!n||!pt(e))return!1;const r=KS({runtimeKey:e.runtimeKey,apiBaseUrl:e.apiBaseUrl,hosts:n.hosts,localOrigin:n.localOrigin});return r?r.kind==="local"?(await Zl({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>{}),pt(e)):r.host.clientToken===t?!0:pt(e)?(await Zl({hosts:n.hosts.map(s=>s.id===r.host.id?{...s,clientToken:t}:s),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{}),pt(e)):!1:!0},Gc=async(e,t,n)=>!e||!pt(t)||!await $T(t,e)||!pt(t)?!1:(gl({apiBaseUrl:t.apiBaseUrl,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null,runtimeKey:t.runtimeKey}),!0);function zT(){const t=p.useMemo(()=>xt(),[]),[n,r]=p.useState(()=>"pending"),[s,o]=p.useState(""),[i,a]=p.useState(!1),[l,d]=p.useState(""),[f,u]=p.useState(void 0),[h,m]=p.useState(!1),[g,x]=p.useState(Ll),[b,S]=p.useState(!1),[y,v]=p.useState(!1),[C,w]=p.useState(()=>FT()),[I,E]=p.useState(null),T=p.useRef(null),A=p.useRef(!1);p.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Xw,C?"true":"false")},[C]);const j=p.useCallback(async(q=us())=>{try{const B=await ET();return pt(q)&&x(B),B}catch{return pt(q)&&x(Ll),Ll}},[!1]);p.useEffect(()=>{let q=!1;return(async()=>{try{if(!window.isSecureContext||!e8()){q||S(!1);return}q||S(!0)}catch{q||S(!1)}})(),()=>{q=!0}},[!1]);const k=p.useRef(0),_=p.useRef(null),M=p.useRef(null),L=p.useCallback(()=>{_.current!==null&&(window.clearTimeout(_.current),_.current=null)},[]),O=p.useCallback(()=>{k.current=0,L()},[L]),N=p.useCallback(()=>k.current>=TT?!1:(k.current+=1,L(),_.current=window.setTimeout(()=>{_.current=null,M.current?.()},AT*k.current),!0),[L]);p.useEffect(()=>L,[L]);const D=p.useCallback(async()=>{const q=us();r(B=>B==="authenticated"?B:"pending");try{const[B,ee]=await Promise.all([HT(),j(q)]),G=await B.text();if(!pt(q))return;if(B.ok){O(),r("authenticated"),m(!1),d(""),u(void 0);return}if(B.status===401){let K={};try{K=JSON.parse(G)}catch{K={}}O(),m(K.tunnelLocked===!0),x(ee),r("locked"),u(void 0);return}if(B.status===429){let K={};try{K=JSON.parse(G)}catch{K={}}O(),u(K.retryAfter),m(!1),r("rate-limited");return}if(N())return;r("error"),m(!1)}catch(B){if(!pt(q))return;if(console.warn("Failed to check session status:",B),jT({shouldUseDesktopShellPasswordLogin:Of()})==="locked"){r("locked"),u(void 0),m(!1);return}if(N())return;r("error"),m(!1)}},[j,O,N,!1]);p.useEffect(()=>{M.current=D},[D]),p.useEffect(()=>{D()},[D,!1]),p.useEffect(()=>GS(()=>{O(),D()}),[D,O,!1]),p.useEffect(()=>Zt(()=>{F2(),o(""),d(""),u(void 0),m(!1),a(!1),E(null),v(!1),O(),r("pending"),D()}),[D,O,!1]),p.useEffect(()=>{n==="locked"&&(A.current=!1)},[!1,n]),p.useEffect(()=>{n==="locked"&&T.current&&(T.current.focus(),T.current.select())},[n]),p.useEffect(()=>{n==="authenticated"&&(A.current=!0)},[!1,n]);const W=p.useCallback(async()=>{const q=us();E("register"),v(!0);try{await B2()}finally{pt(q)&&(E(null),v(!1))}pt(q)&&await j(q)},[j]),z=p.useCallback(()=>{F2(),E(null),v(!1)},[]),X=p.useCallback(async q=>{if(h||!s||i)return;y&&z();const B=us(),ee=Yg();a(!0),d("");try{if(Of()){const K=await Hf(s,C,B,ee);if(!pt(B))return;if(K?.token){if(o(""),m(!1),!await Gc(K.token,B,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}}const G=await BT(s,C);if(!pt(B))return;if(G.ok){const K=await G.json().catch(()=>null);if(!pt(B))return;const se=kp();let le="";if(se&&(le=typeof K?.clientToken=="string"&&K.clientToken.trim()?K.clientToken.trim():"",!le)){const oe=await Hf(s,C,B,ee);if(!pt(B)||(le=oe?.token||await VT(),!pt(B)))return}if(o(""),m(!1),le&&!await Gc(le,B,ee))return;if(q&&b)try{if(await W(),!pt(B))return;Ce.success("Passkey added"),r("authenticated");return}catch(oe){if(Df(oe))Ce.message("Passkey setup canceled");else{const ue=oe instanceof Error?oe.message:"Passkey setup failed.";Ce.error(ue)}r("authenticated");return}r("authenticated");return}if(G.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(G.status===429){const K=await G.json().catch(()=>({}));u(K.retryAfter),m(!1),r("rate-limited");return}d("Unexpected response from server."),m(!1),r("error")}catch(G){if(!pt(B))return;console.warn("Failed to submit UI password:",G);const K=Of()?await Hf(s,C,B,ee):null;if(!pt(B))return;if(K?.token){if(o(""),m(!1),!await Gc(K.token,B,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}d("Network error. Check connection and retry."),m(!1),r("error")}finally{pt(B)&&a(!1)}},[z,y,i,h,s,W,b,C]),F=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}v(!0),E("auth"),d("");const q=us(),B=Yg();try{const ee=await MT(C,{issueClientToken:kp(),clientLabel:"PiChamber Desktop",...l1()});if(!pt(q))return;if(typeof ee?.clientToken=="string"&&ee.clientToken.trim()){const G=ee.clientToken.trim();if(!await Gc(G,q,B))return}m(!1),r("authenticated")}catch(ee){if(!pt(q)||Df(ee))return;const G=ee instanceof Error?ee.message:"Passkey sign-in failed.";d(G)}finally{pt(q)&&(E(null),v(!1))}},[z,y,i,b,C]),U=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}const q=us();E("register"),v(!0);try{if(await B2(),!pt(q))return;Ce.success("Passkey added"),await j(q)}catch(B){if(!pt(q))return;if(Df(B))Ce.message("Passkey setup canceled");else{const ee=B instanceof Error?B.message:"Passkey setup failed.";Ce.error(ee)}}finally{pt(q)&&(E(null),v(!1))}},[z,y,i,j,b]);return{state:n,password:s,setPassword:o,passwordInputRef:T,isSubmitting:i,errorMessage:l,setErrorMessage:d,retryAfter:f,isTunnelLocked:h,passkeyStatus:g,supportsPasskeys:b,isPasskeyBusy:y,trustDevice:C,setTrustDevice:w,activePasskeyAction:I,showHostSwitcher:t,resetTransientRetry:O,checkStatus:D,handleSubmit:async q=>{q.preventDefault(),await X(!1)},handlePasswordUnlock:X,handlePasskeyUnlock:F,handlePasskeySetupOnly:U}}const xJ=({children:e})=>{const{state:t,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,retryAfter:l,isTunnelLocked:d,passkeyStatus:f,supportsPasskeys:u,isPasskeyBusy:h,trustDevice:m,setTrustDevice:g,activePasskeyAction:x,showHostSwitcher:b,resetTransientRetry:S,checkStatus:y,handleSubmit:v,handlePasskeyUnlock:C,handlePasskeySetupOnly:w}=zT();return t==="pending"?c.jsx(yT,{}):t==="error"?c.jsx(H2,{onRetry:()=>{S(),y()},errorType:"network",children:b&&c.jsxs("div",{className:"w-full max-w-xs",children:[c.jsx(Ww,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})}):t==="rate-limited"?c.jsx(H2,{onRetry:()=>{y()},errorType:"rate-limit",retryAfter:l}):t==="locked"?c.jsx(vT,{isTunnelLocked:d,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,trustDevice:m,setTrustDevice:g,supportsPasskeys:u,passkeyStatus:f,isPasskeyBusy:h,activePasskeyAction:x,showHostSwitcher:b,onSubmit:v,onPasskeyUnlock:C,onPasskeySetupOnly:w}):c.jsx(c.Fragment,{children:e})},wu=e=>{try{return new URL(e)}catch{return null}},bJ=e=>{const t=wu(e.trim());return t?t.protocol==="http:"||t.protocol==="https:":!1},UT=e=>{const t=wu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${t.hostname.toLowerCase()}.ico`},qT=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),WT=e=>{const t=wu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?!1:qT.has(t.hostname.toLowerCase())},KT=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,GT=e=>{if(!e)return[];const t=e.match(KT);if(!t||t.length===0)return[];const n=new Set,r=[];for(const s of t){const o=s.replace(/[),.;:!?'"`]+$/g,"");!o||!WT(o)||n.has(o)||(n.add(o),r.push(o))}return r},ja=async e=>{if(typeof window>"u")return!1;const t=e.trim();if(!t)return!1;const n=wu(t);if(!n||n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.toString(),s=window.__PICHAMBER_DESKTOP__;if(s?.openExternal)try{return await s.openExternal(r),!0}catch{}try{return window.open(r,"_blank","noopener,noreferrer"),!0}catch{return!1}},Qw="pichamber.mobileUpdateChannel",ZT=/^\d+\.\d+\.\d+-rc\.[1-9]\d*$/,wJ=e=>e==="rc"?"rc":"stable",YT=e=>ZT.test(e)?"rc":"stable",XT=e=>{try{const t=typeof window>"u"?null:window.localStorage.getItem(Qw);if(t==="rc"||t==="stable")return t}catch{}return YT(e)},SJ=e=>(window.localStorage.setItem(Qw,e),e);function JT(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=pu();return e}catch{return"unknown"}}function QT(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function eA(){const e=XS();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const t=(navigator.platform||"").toLowerCase();return t.includes("mac")?"macos":t.includes("win")?"windows":t.includes("linux")?"linux":"web"}function tA(e){const t=new URLSearchParams;return t.set("deviceClass",JT()),t.set("arch",QT()),t.set("platform",eA()),e==="desktop"?(t.set("appType","desktop-electron"),t.set("instanceMode",Yr()?"local":"remote"),t):e==="mobile"?(t.set("appType","mobile-capacitor"),t.set("instanceMode","remote"),t):(t.set("appType","web"),t.set("instanceMode","unknown"),t)}async function bi(e,t,n){try{const r=tA(e);t&&r.set("currentVersion",t),n&&r.set("channel",n);const s=await Rt(`/api/pi/update-check?${r.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!s.ok)throw new Error(`Server responded with ${s.status}`);const o=await s.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand,channel:o.channel==="rc"?"rc":"stable"}}catch(r){return console.warn("Failed to check for updates:",r),null}}function nA(){return cr()?"mobile":Vr()?"desktop":xm()?"web":null}const V2={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,serverInfo:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null};let Rl=0;const Mp=Et()((e,t)=>({...V2,checkForUpdates:async()=>{const n=nA();if(!n)return null;const r=++Rl,s=()=>r===Rl;e({checking:!0,error:null,runtimeType:n});try{let o=null,i=null;if(n==="desktop"){const a="1.0.7",l=!Yr(),[d,f]=await Promise.allSettled([Xg(),l?bi("web"):bi("desktop",a)]);if(!s())return null;const u=d.status==="fulfilled"?d.value:null,h=f.status==="fulfilled"?f.value:null;return i=h?.nextSuggestedCheckInSec??null,e({checking:!1,available:u?.available??!1,info:u,serverInfo:l?h:null,lastChecked:Date.now(),nextCheckInSec:i}),i}else if(n==="web")o=await bi("web"),i=o?.nextSuggestedCheckInSec??null;else if(n==="mobile"){const a="1.0.7",[l,d]=await Promise.all([bi("mobile",a,XT(a)),bi("web")]);return s()?(i=l?.nextSuggestedCheckInSec??d?.nextSuggestedCheckInSec??null,e({checking:!1,available:l?.available??!1,info:l,serverInfo:d,lastChecked:Date.now(),nextCheckInSec:i}),i):null}return s()?(e({checking:!1,available:o?.available??!1,info:o,serverInfo:null,lastChecked:Date.now(),nextCheckInSec:i}),i):null}catch(o){return s()&&e({checking:!1,error:o instanceof Error?o.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=t();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const s=await Xg();if(!s?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(i=>({info:i.info?{...i.info,...s,body:i.info.body||s.body,available:i.info.available}:s})),!await YS(i=>{e({progress:i})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(s){e({downloading:!1,error:s instanceof Error?s.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=t();if(!(r!=="desktop"||!n))try{if(!await ZS())throw new Error("Desktop restart only works on Local instance")}catch(s){e({error:s instanceof Error?s.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null,serverInfo:null})},reset:()=>{Rl+=1,e(V2)}})),rA=()=>{Rl+=1;const{runtimeType:e}=Mp.getState(),t=e==="web";Mp.setState({checking:!1,serverInfo:null,lastChecked:null,nextCheckInSec:null,error:null,...t?{info:null,available:!1}:{}})};Zt(e=>{e.runtimeKey!==e.previousRuntimeKey&&rA()});function sA({className:e,...t}){return c.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",e),...t})}function oA({className:e,...t}){return c.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function iA({className:e,...t}){return c.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",e),...t})}function aA({className:e,...t}){return c.jsx("div",{"data-slot":"card-content",className:R("px-6",e),...t})}class cA extends p.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n,copied:!1}),console.error("Error caught by boundary:",t,n)}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};handleCopy=async()=>{const{strings:t}=this.props,n=this.state.error?String(this.state.error):t.unknownError,r=this.state.error?.stack?`
36
-
37
- Stack:
38
- ${this.state.error.stack}`:"",s=this.state.errorInfo?.componentStack?`
39
-
40
- ${t.componentStackLabel}${this.state.errorInfo.componentStack}`:"",o=`${n}${r}${s}`;(await yr(o)).ok&&(this.setState({copied:!0}),window.setTimeout(()=>{this.setState(a=>a.copied?{copied:!1}:null)},1500))};render(){const{strings:t}=this.props;return this.state.hasError?this.props.fallback?this.props.fallback:c.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:c.jsxs(sA,{className:"w-full max-w-md",children:[c.jsx(oA,{className:"text-center",children:c.jsxs(iA,{className:"flex items-center justify-center gap-2 text-destructive",children:[c.jsx($,{name:"error-warning",className:"h-5 w-5"}),t.title]})}),c.jsxs(aA,{className:"space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground text-center",children:t.description}),this.state.error&&c.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[c.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:t.detailsSummary}),c.jsxs("pre",{className:"mt-2 max-h-48 overflow-auto",children:[this.state.error.toString(),this.state.errorInfo?.componentStack?`
41
-
42
- ${t.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(be,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[c.jsx($,{name:"restart",className:"h-4 w-4 mr-2"}),t.tryAgain]}),c.jsx(be,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?t.copied:t.copy})]})]})]})}):this.props.children}}const CJ=({children:e,fallback:t})=>{const n=p.useMemo(()=>({unknownError:"Unknown error",title:"Something went wrong",description:"The application encountered an unexpected error. This has been logged for debugging.",detailsSummary:"Error details",componentStackLabel:"Component stack:",tryAgain:"Try again",copied:"Copied",copy:"Copy"}),[]);return c.jsx(cA,{fallback:t,strings:n,children:e})},lA=1e3,$2=.5,z2={length:0,offset:0},U2=(e,t)=>Math.abs(e.length-t.length)<$2&&Math.abs(e.offset-t.offset)<$2,e3=({containerRef:e,minThumbSize:t=32,hideDelayMs:n=1e3,className:r,disableHorizontal:s=!1,observeMutations:o=!0,suppressVisibility:i=!1,userIntentOnly:a=!1})=>{const[l,d]=p.useState(!1),[f,u]=p.useState({length:0,offset:0}),[h,m]=p.useState({length:0,offset:0}),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(!1),v=p.useRef(0),C=p.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),w=p.useRef(null),I=p.useRef(new Set),E=p.useCallback(()=>{const F=e.current;if(!F)return;const{scrollHeight:U,clientHeight:P,scrollTop:q,scrollWidth:B,clientWidth:ee,scrollLeft:G}=F,K=8;let se=z2;if(U>P){const oe=Math.max(P-K*2,0),ue=P/U*oe,ye=Math.max(t,Math.min(oe,ue)),we=Math.max(oe-ye,0),Me=Math.max(U-P,1),He=q/Me*we;se={length:ye,offset:He}}u(oe=>U2(oe,se)?oe:se);let le=z2;if(!s&&B>ee){const oe=Math.max(ee-K*2,0),ue=ee/B*oe,ye=Math.max(t,Math.min(oe,ue)),we=Math.max(oe-ye,0),Me=Math.max(B-ee,1),He=G/Me*we;le={length:ye,offset:He}}m(oe=>U2(oe,le)?oe:le)},[e,t,s]),T=p.useCallback(()=>{b.current===null&&(b.current=requestAnimationFrame(()=>{b.current=null,E()}))},[E]),A=p.useCallback((F,U)=>{if(!U){I.current.clear();return}const P=new Set;P.add(F),Array.from(F.children).forEach(q=>{P.add(q)}),I.current.forEach(q=>{P.has(q)||U.unobserve(q)}),P.forEach(q=>{I.current.has(q)||U.observe(q)}),I.current=P},[]),j=p.useCallback(()=>{g.current&&clearTimeout(g.current),!y.current&&(g.current=setTimeout(()=>d(!1),n))},[n]),k=p.useCallback(()=>{v.current=Date.now()},[]),_=p.useCallback(()=>{x.current&&cancelAnimationFrame(x.current),x.current=requestAnimationFrame(()=>{if(E(),i&&!S.current){d(!1);return}if(a&&!S.current&&!(Date.now()-v.current<=lA)){d(!1);return}d(!0),j()})},[j,i,E,a]);p.useEffect(()=>{const F=e.current;if(!F)return;E(),d(!1);const U=()=>_(),P=K=>{(K.key==="ArrowUp"||K.key==="ArrowDown"||K.key==="PageUp"||K.key==="PageDown"||K.key==="Home"||K.key==="End"||K.key===" ")&&k()};F.addEventListener("scroll",U,{passive:!0}),a&&(F.addEventListener("wheel",k,{passive:!0}),F.addEventListener("touchstart",k,{passive:!0}),F.addEventListener("touchmove",k,{passive:!0}),F.addEventListener("keydown",P));const q=typeof ResizeObserver<"u"?new ResizeObserver(()=>{T()}):null;A(F,q);const B=o&&typeof MutationObserver<"u"?new MutationObserver(()=>{A(F,q),T()}):null;B?.observe(F,{childList:!0});const ee=()=>T(),G=()=>T();return F.addEventListener("input",ee,!0),F.addEventListener("load",G,!0),()=>{F.removeEventListener("scroll",U),F.removeEventListener("input",ee,!0),F.removeEventListener("load",G,!0),a&&(F.removeEventListener("wheel",k),F.removeEventListener("touchstart",k),F.removeEventListener("touchmove",k),F.removeEventListener("keydown",P)),q?.disconnect(),B?.disconnect(),I.current.clear(),g.current&&clearTimeout(g.current),x.current&&cancelAnimationFrame(x.current),b.current&&cancelAnimationFrame(b.current)}},[e,_,k,o,T,A,E,a]),p.useEffect(()=>{i&&(S.current||(d(!1),g.current&&(clearTimeout(g.current),g.current=null)))},[i]);const M=(F,U)=>{const P=e.current;P&&(S.current=!0,C.current={pointerX:F.clientX,pointerY:F.clientY,scrollTop:P.scrollTop,scrollLeft:P.scrollLeft},w.current=U,k(),d(!0),g.current&&clearTimeout(g.current),F.currentTarget.setPointerCapture(F.pointerId))},L=F=>{if(!S.current)return;const U=e.current;if(!U)return;const P=w.current;if(P==="vertical"){const{pointerY:q,scrollTop:B}=C.current,ee=F.clientY-q,G=U.clientHeight,K=Math.max(G-f.length,1),se=Math.max(U.scrollHeight-U.clientHeight,1),le=ee/K*se;U.scrollTop=B+le}else if(P==="horizontal"){const{pointerX:q,scrollLeft:B}=C.current,ee=F.clientX-q,G=U.clientWidth,K=Math.max(G-h.length,1),se=Math.max(U.scrollWidth-U.clientWidth,1),le=ee/K*se;U.scrollLeft=B+le}},O=F=>{S.current&&(S.current=!1,F.currentTarget.releasePointerCapture(F.pointerId),j())},N=p.useCallback(()=>{y.current=!0,g.current&&(clearTimeout(g.current),g.current=null)},[]),D=p.useCallback(()=>{y.current=!1,j()},[j]),W=f.length>0,z=h.length>0;if(!W&&!z)return null;const X=8;return c.jsxs("div",{className:R("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:l?1:0},children:[W&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${f.length}px`,top:`${X+f.offset}px`,right:`${X/2}px`},onPointerDown:F=>M(F,"vertical"),onPointerMove:L,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D}),z&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${h.length}px`,left:`${X+h.offset}px`,bottom:`${X/2}px`},onPointerDown:F=>M(F,"horizontal"),onPointerMove:L,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D})]})};e3.displayName="OverlayScrollbar";const t3=e3;function dA(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&typeof n=="object"&&(n.current=t)})}}const Su=p.forwardRef(({as:e="div",orientation:t="vertical",offset:n=0,size:r=48,isEnabled:s=!0,hideTopShadow:o=!1,hideBottomShadow:i=!1,observeMutations:a=!0,onVisibilityChange:l,style:d,className:f,children:u,...h},m)=>{const g=p.useRef(null),x=p.useRef("none"),b=h["data-scroll-shadow"];delete h["data-scroll-shadow"];const S=p.useMemo(()=>{const w={...d};return w["--scroll-shadow-size"]=`${r}px`,w},[r,d]),y=p.useCallback((w,I,E,T,A)=>{const j=`${T}${A.charAt(0).toUpperCase()}${A.slice(1)}Scroll`;I&&E?(w.dataset[j]="true",w.removeAttribute(`data-${T}-scroll`),w.removeAttribute(`data-${A}-scroll`)):(w.dataset[`${T}Scroll`]=String(I),w.dataset[`${A}Scroll`]=String(E),w.removeAttribute(`data-${T}-${A}-scroll`))},[]),v=p.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(I=>{w.removeAttribute(`data-${I}-scroll`)})},[]),C=p.useCallback(()=>{const w=g.current;if(!w)return;if(!s){v(w);return}const I=1,E=t==="vertical"?w.scrollTop>n+I:w.scrollLeft>n+I;let T=t==="vertical"?w.scrollHeight-(w.scrollTop+w.clientHeight)>n+I:w.scrollWidth-(w.scrollLeft+w.clientWidth)>n+I;const A=o&&t==="vertical"?!1:E;i&&t==="vertical"&&(T=!1),y(w,A,T,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const j=A&&T?"both":A?t==="vertical"?"top":"left":T?t==="vertical"?"bottom":"right":"none";j!==x.current&&(x.current=j,l?.(j))},[v,o,i,s,n,l,t,y]);return p.useEffect(()=>{const w=g.current;if(!w)return;let I=null;const E=()=>{I===null&&(I=requestAnimationFrame(()=>{I=null,C()}))},T=()=>C(),A=typeof ResizeObserver<"u"?new ResizeObserver(E):null,j=a&&typeof MutationObserver<"u"?new MutationObserver(E):null;return C(),w.addEventListener("scroll",T,{passive:!0}),A?.observe(w),j?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{I!==null&&cancelAnimationFrame(I),w.removeEventListener("scroll",T),A?.disconnect(),j?.disconnect()}},[C,a]),c.jsx(e,{...h,ref:dA(g,m),className:f,"data-orientation":t,"data-scroll-shadow":b??!0,style:S,children:u})});Su.displayName="ScrollShadow";const Yn=p.forwardRef(({className:e,outerClassName:t,children:n,style:r,minThumbSize:s,hideDelayMs:o,as:i="div",scrollbarClassName:a,disableHorizontal:l=!1,observeMutations:d=!0,fillContainer:f=!0,preventOverscroll:u=!1,useScrollShadow:h=!1,scrollShadowSize:m,hideTopScrollShadow:g=!1,userIntentOnly:x=!1,...b},S)=>{const y=p.useRef(null);return p.useImperativeHandle(S,()=>y.current,[]),c.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden",u&&"overscroll-none",t),children:[h?c.jsx(Su,{as:i,ref:y,size:m,hideTopShadow:g,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,observeMutations:d,...b,children:n}):c.jsx(i,{ref:y,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,...b,children:n}),c.jsx(t3,{containerRef:y,minThumbSize:s,hideDelayMs:o,className:a,disableHorizontal:l,observeMutations:d,userIntentOnly:x})]})});Yn.displayName="ScrollableOverlay";const q2="mobile-overlay-root",W2=16,K2=200,uA=()=>{if(typeof document>"u")return null;let e=document.getElementById(q2);return e||(e=document.createElement("div"),e.id=q2,document.body.appendChild(e)),e},Ta=({open:e,title:t,onClose:n,children:r,footer:s,className:o,contentMaxHeightClassName:i,renderHeader:a})=>{const l=p.useRef(null),[d,f]=p.useState(!1),[u,h]=p.useState(!1);if(typeof document<"u"&&!l.current&&(l.current=uA()),p.useEffect(()=>{if(!e){f(!1),h(!1);return}const x=window.setTimeout(()=>f(!0),W2),b=window.setTimeout(()=>h(!0),W2+K2+50);return()=>{window.clearTimeout(x),window.clearTimeout(b)}},[e]),p.useLayoutEffect(()=>{if(e)return window.dispatchEvent(new Event("oc:mobile-overlay-opened")),()=>{window.dispatchEvent(new Event("oc:mobile-overlay-closed"))}},[e]),p.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;document.body.style.overflow="hidden";const b=S=>{S.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>{document.body.style.overflow=x,document.removeEventListener("keydown",b)}},[e,n]),!e||!l.current)return null;const m=i??"max-h-[min(70vh,520px)]",g=c.jsx("div",{className:R("oc-keyboard-inset-surface fixed inset-0 z-[60] flex flex-col bg-[rgb(0_0_0_/_0.45)] transition-opacity duration-200 ease-out",!u&&"oc-keyboard-inset-snap",d?"opacity-100":"opacity-0"),role:"dialog","aria-modal":"true",onClick:n,style:{paddingLeft:"var(--oc-chat-inset-left, 0px)",paddingRight:"var(--oc-chat-inset-right, 0px)"},children:c.jsxs("div",{className:R("mt-auto flex max-h-[calc(100dvh-0.75rem)] min-h-0 w-full flex-col rounded-t-xl border-x border-t border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",o),style:{transform:d?"none":"translateY(100%)",transition:`transform ${K2}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:x=>x.stopPropagation(),children:[(()=>{const x=c.jsx("button",{type:"button",onClick:n,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover",children:c.jsx($,{name:"close",className:"h-4 w-4"})});return a?a(x):c.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[c.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t}),x]})})(),c.jsx(Yn,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:R("min-h-0 flex-1",m),className:"px-2 py-2 pwa-overlay-scroll",children:r}),s?c.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:s}):null]})});return ba.createPortal(g,l.current)},fA=10,G2=16,Z2=4,hA=/[-_./]/;function pA(e){const t=Array.from(e);let n=fA;const r=t.lastIndexOf("/");if(r>0&&r<t.length-1){const i=t.length-r-1;i>=Z2&&i<=G2&&(n=i)}if(t.length<=n+4)return null;let s=t.length-n;const o=i=>hA.test(t[i-1]??"");if(!o(s)){let i=-1;for(let a=s+1;a<=t.length-Z2;a+=1)if(o(a)){i=a;break}for(let a=s-1;i<0&&a>=t.length-G2&&a>4;a-=1)o(a)&&(i=a);i>0&&(s=i)}return{head:t.slice(0,s).join(""),tail:t.slice(s).join("")}}function mA(e,t,n){t.style.clipPath="",n.style.translate="",e.removeAttribute("data-overflow");const r=t.firstChild;if(!(r instanceof Text)||t.scrollWidth<=t.clientWidth)return;e.setAttribute("data-overflow","");const s=t.clientWidth,o=t.getBoundingClientRect().left,i=document.createRange(),a=u=>(i.setStart(r,0),i.setEnd(r,u),i.getBoundingClientRect().right-o);let l=0,d=r.length;for(;d-l>1;){const u=l+d>>1;a(u)<=s?l=u:d=u}/[\uD800-\uDBFF]/.test(r.data[l-1]??"")&&(l-=1);const f=Math.max(0,s-a(l));f>0&&(t.style.clipPath=`inset(-0.25em ${f}px -0.25em 0)`,n.style.translate=`-${f}px 0`)}function d1({value:e,showTitle:t=!0,className:n,...r}){const s=pA(e),o=p.useRef(null),i=p.useRef(null),a=p.useRef(null),l=s?.head;return p.useLayoutEffect(()=>{const d=o.current,f=i.current,u=a.current;if(!d||!f||!u||l===void 0)return;const h=()=>mA(d,f,u);if(h(),typeof ResizeObserver>"u")return;const m=new ResizeObserver(h);return m.observe(d),()=>m.disconnect()},[l]),c.jsx("span",{...r,ref:o,title:t?e:void 0,className:R("group/middle-truncate inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",n),children:s?c.jsxs(c.Fragment,{children:[c.jsx("span",{ref:i,className:"min-w-0 overflow-hidden",children:s.head}),c.jsxs("span",{ref:a,className:"shrink-0",children:[c.jsx("span",{"aria-hidden":"true",className:"hidden group-data-[overflow]/middle-truncate:inline",children:"…"}),s.tail]})]}):c.jsx("span",{className:"min-w-0 truncate",children:e},"whole")})}const gA="Awaiting first prompt";function n3(e,t="Untitled Session"){const n=e?.title?.trim();return n||(e?.messageCount===0?gA:t)}const Ff=new Set,Bf=new Set,Vf=new Set,$f=new Set,Cu={onDeleteRequest(e){return Ff.add(e),()=>{Ff.delete(e)}},requestDelete(e){e.sessions.length&&Ff.forEach(t=>t(e))},onCreateRequest(e){return Bf.add(e),()=>{Bf.delete(e)}},requestCreate(e){const t=e??{};Bf.forEach(n=>n(t))},onDirectoryRequest(e){return Vf.add(e),()=>{Vf.delete(e)}},requestDirectoryDialog(){Vf.forEach(e=>e())},onGitRefreshHint(e){return $f.add(e),()=>{$f.delete(e)}},requestGitRefresh(e){e.directory.trim()&&$f.forEach(t=>t(e))}},$a=p.createContext(null),yA=40,Y2=20*1024*1024;function vA(e){const t=new Map;let n=0,r=0,s=!0,o=Promise.resolve();const i=(y,v)=>JSON.stringify([v?.directory??"",y]),a=y=>new TextEncoder().encode(y).byteLength,l=y=>{const v=t.get(y);v&&(n=Math.max(0,n-v.bytes)),t.delete(y)},d=y=>{const v=y.endsWith("/")?y:`${y}/`;for(const[C,w]of t)(w.sourcePath===y||w.sourcePath.startsWith(v))&&l(C)},f=(y,v)=>v.isFile&&v.mtimeMs!==void 0&&y.mtimeMs===v.mtimeMs&&y.size===v.size,u=()=>{t.clear(),n=0},h=(y,v,C,w)=>{if(!s||!w.isFile||w.mtimeMs===void 0)return C;const I=a(C.content);if(I>Y2)return C;for(l(y),t.set(y,{...C,sourcePath:v,size:w.size,mtimeMs:w.mtimeMs,bytes:I}),n+=I;t.size>yA||n>Y2;){const E=t.keys().next().value;if(!E)break;l(E)}return C},m=async(y,v,C,w)=>{const I=await e.statFile?.(v,C).catch(()=>null),E=await e.readFile(v,C),T=await e.statFile?.(v,C).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return w!==r?g(v,C):I&&T&&I.isFile&&T.isFile&&I.mtimeMs!==void 0&&T.mtimeMs!==void 0&&I.size===T.size&&I.mtimeMs===T.mtimeMs?h(y,v,E,T):E},g=e.readFile?async(y,v)=>{if(await o,!s)throw new Error("File cache owner disposed");const C=r;if(v?.allowOutsideWorkspace)return e.readFile(y,v);const w=i(y,v),I=t.get(w);if(!I)return m(w,y,v,C);const E=await e.statFile?.(y,v).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return C!==r?g(y,v):!E||!f(I,E)?(l(w),m(w,y,v,C)):(t.delete(w),t.set(w,I),{content:I.content,path:I.path,revision:I.revision})}:void 0,x=async(y,v)=>{const C=o;let w;o=new Promise(I=>{w=I}),await C,r+=1,y.forEach(d);try{return await v()}finally{y.forEach(d),r+=1,w()}},b={...e,readFile:g,writeFile:e.writeFile?(y,v,C)=>x([y],()=>e.writeFile(y,v,C)):void 0,delete:e.delete?y=>x([y],()=>e.delete(y)):void 0,rename:e.rename?(y,v)=>x([y,v],()=>e.rename(y,v)):void 0},S=A5(y=>{y.runtimeKey!==y.previousRuntimeKey&&(r+=1,u())});return{files:b,dispose:()=>{s=!1,r+=1,u(),S()}}}function kJ({apis:e,children:t}){const[n,r]=p.useState(null);p.useEffect(()=>{const i=vA(e.files);return r(i),()=>{i.dispose(),r(a=>a===i?null:a)}},[e.files]);const s=n?.files??e.files,o=p.useMemo(()=>({...e,files:s}),[e,s]);return c.jsx($a.Provider,{value:o,children:t})}const xA=600,bA=1600,X2=10,r3=H.createContext(null);class s3 extends H.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function wA({delayDuration:e=0,skipDelayDuration:t,delay:n,closeDelay:r,...s}){return c.jsx(t8,{delay:n??e,closeDelay:r??t,...s})}function wt({delayDuration:e,open:t,onOpenChange:n,...r}){const[s,o]=H.useState(!1),i=H.useRef(null),a=H.useRef(null),l=H.useRef(null),d=H.useRef(!1),f=t!==void 0,u=f?t:s,h=H.useCallback(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),m=H.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),g=H.useCallback(y=>{f||o(y)},[f]),x=H.useMemo(()=>({handlePointerDown:y=>{y.pointerType!=="touch"&&y.pointerType!=="pen"||(h(),m(),l.current={x:y.clientX,y:y.clientY},i.current=window.setTimeout(()=>{f||(d.current=!0,g(!0))},xA))},handlePointerMove:y=>{const v=l.current;if(!v)return;const C=Math.abs(y.clientX-v.x),w=Math.abs(y.clientY-v.y);(C>X2||w>X2)&&(h(),l.current=null)},handlePointerEnd:()=>{h(),l.current=null,d.current&&(m(),a.current=window.setTimeout(()=>{d.current=!1,g(!1)},bA))},handleClickCapture:y=>{d.current&&(d.current=!1,y.preventDefault(),y.stopPropagation())},handleContextMenu:y=>{d.current&&y.preventDefault()}}),[m,h,f,g]);H.useEffect(()=>()=>{h(),m()},[m,h]);const b=H.useCallback((y,v)=>{f||o(y),n?.(y,v)},[f,n]),S=c.jsx(r3.Provider,{value:x,children:c.jsx(n8,{open:u,onOpenChange:b,...r})});return e===void 0?S:c.jsx(wA,{delayDuration:e,children:S})}function St({asChild:e,children:t,onPointerDown:n,onPointerMove:r,onPointerUp:s,onPointerCancel:o,onClickCapture:i,onContextMenu:a,...l}){const d=H.useContext(r3),f=e&&H.isValidElement(t)?{render:t}:{children:t};return c.jsx(s3,{fallback:t,children:c.jsx(r8,{"data-slot":"tooltip-trigger",onPointerDown:u=>{n?.(u),d?.handlePointerDown(u)},onPointerMove:u=>{r?.(u),d?.handlePointerMove(u)},onPointerUp:u=>{s?.(u),d?.handlePointerEnd()},onPointerCancel:u=>{o?.(u),d?.handlePointerEnd()},onClickCapture:u=>{d?.handleClickCapture(u),!u.defaultPrevented&&i?.(u)},onContextMenu:u=>{d?.handleContextMenu(u),!u.defaultPrevented&&a?.(u)},...l,...f})})}function Ct({className:e,sideOffset:t=0,side:n,align:r,children:s,style:o,...i}){return c.jsx(s3,{children:c.jsx(s8,{children:c.jsx(o8,{sideOffset:t,side:n,align:r,className:"z-50",children:c.jsxs(i8,{"data-slot":"tooltip-content",className:R("oc-glass-tooltip text-[var(--surface-elevated-foreground)] border border-border/60 transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 data-[instant]:transition-none data-[instant]:duration-0 z-50 w-fit origin-[var(--transform-origin)] rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden",e),style:{...o},...i,children:[s,c.jsx(a8,{className:"fill-[var(--surface-elevated)] z-50 size-2"})]})})})})}const SA="inset 0 1px 0 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 0 0 1px rgba(0,0,0,0.36), 0 1px 1px -0.5px rgba(0,0,0,0.22), 0 3px 3px -1.5px rgba(0,0,0,0.20), 0 6px 6px -3px rgba(0,0,0,0.16)",CA="inset 0 1px 0 0 rgba(255,255,255,0.8), inset 0 0 0 1px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.10), 0 1px 2px -0.5px rgba(0,0,0,0.08), 0 4px 8px -2px rgba(0,0,0,0.08), 0 12px 20px -4px rgba(0,0,0,0.08)";function kA(){const e=()=>typeof document<"u"&&document.documentElement.classList.contains("dark"),[t,n]=H.useState(e);return H.useEffect(()=>{const r=()=>n(e()),s=new MutationObserver(r);return s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r(),()=>s.disconnect()},[]),t}function MA(e){H.useEffect(()=>{if(typeof document>"u")return;const t=s=>{s.style.setProperty("box-shadow",e,"important"),s.style.setProperty("outline","none","important"),s.getAttribute("tabindex")==="0"&&s.setAttribute("tabindex","-1")},n=()=>{document.querySelectorAll("[data-sonner-toast]").forEach(t)};n();const r=new MutationObserver(s=>{for(const o of s)o.addedNodes.forEach(i=>{i instanceof HTMLElement&&(i.matches?.("[data-sonner-toast]")&&t(i),i.querySelectorAll?.("[data-sonner-toast]").forEach(t))});n()});return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","tabindex","data-expanded","data-swiping"]}),()=>r.disconnect()},[e])}const MJ=({...e})=>{const t=kA();return MA(t?SA:CA),c.jsx(c8,{theme:t?"dark":"light",className:"toaster group",closeButton:!1,toastOptions:{classNames:{toast:"group/toast toast !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground [&_[data-cancel]+[data-button]]:!ml-2",title:"typography-ui-label !font-medium !text-foreground",description:"typography-meta !text-muted-foreground !mt-0.5",actionButton:"!rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity",cancelButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors",closeButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]",icon:"!text-muted-foreground",success:"[&_[data-icon]]:!text-[var(--status-success)]",error:"[&_[data-icon]]:!text-[var(--status-error)]",warning:"[&_[data-icon]]:!text-[var(--status-warning)]",info:"[&_[data-icon]]:!text-[var(--status-info)]"},style:{borderRadius:"var(--radius-xl)",backgroundColor:"var(--surface-elevated)"}},style:{"--normal-bg":"var(--surface-elevated)","--normal-text":"var(--foreground)","--normal-border":"transparent","--error-bg":"var(--surface-elevated)","--error-text":"var(--foreground)","--error-border":"transparent","--success-bg":"var(--surface-elevated)","--success-text":"var(--foreground)","--success-border":"transparent","--warning-bg":"var(--surface-elevated)","--warning-text":"var(--foreground)","--warning-border":"transparent","--info-bg":"var(--surface-elevated)","--info-text":"var(--foreground)","--info-border":"transparent"},...e})},$t=e=>Math.round(e*100)/100,cs=e=>{if(!e)return null;const t=e.getBoundingClientRect();return{top:$t(t.top),right:$t(t.right),bottom:$t(t.bottom),left:$t(t.left),width:$t(t.width),height:$t(t.height)}},En=e=>{const t=Number.parseFloat(e);return Number.isFinite(t)?$t(t):null};function IA(){if(typeof window>"u"||typeof document>"u"||!document.body)return null;const e=document.documentElement,t=document.querySelector(".oc-mobile-composer"),n=document.querySelector(".oc-mobile-app-shell"),r=t?.querySelector("[data-composer-card]")??null,s=t?.querySelector("[data-chat-input-footer]")??null,o=t?window.getComputedStyle(t):null,i=cs(n),a=cs(t),l=cs(r),d=window.visualViewport,f=window.getComputedStyle(document.body,"::after"),u=document.createElement("div");u.setAttribute("aria-hidden","true"),u.style.cssText="position:fixed;top:0;left:0;visibility:hidden;pointer-events:none;contain:strict;box-sizing:content-box;width:0;height:0;width:100dvh;height:100lvh;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)",document.body.appendChild(u);let h;try{const m=window.getComputedStyle(u);h={safeTop:En(m.paddingTop),safeBottom:En(m.paddingBottom),dynamicHeight:window.CSS.supports("height","100dvh")?En(m.width):null,largeHeight:window.CSS.supports("height","100lvh")?En(m.height):null}}finally{u.remove()}return{capturedAt:Date.now(),devicePixelRatio:window.devicePixelRatio,screen:{width:window.screen.width,height:window.screen.height,availableHeight:window.screen.availHeight},window:{width:window.innerWidth,height:window.innerHeight,scrollY:$t(window.scrollY)},client:{width:e.clientWidth,height:e.clientHeight},visual:d?{width:$t(d.width),height:$t(d.height),offsetTop:$t(d.offsetTop),offsetLeft:$t(d.offsetLeft),scale:$t(d.scale)}:null,css:{...h,viewportBottomStrip:En(window.getComputedStyle(e).getPropertyValue("--oc-viewport-bottom-strip"))},flags:{standalone:window.matchMedia("(display-mode: standalone)").matches,capacitor:e.classList.contains("oc-capacitor-app"),browserKeyboardOpen:e.classList.contains("oc-browser-keyboard-open"),browserFullscreen:e.classList.contains("oc-browser-kb-fullscreen")},root:cs(e),body:cs(document.body),appRoot:cs(document.getElementById("root")),shell:i,composer:a,card:l,footer:cs(s),composerStyle:o?{paddingTop:En(o.paddingTop),paddingBottom:En(o.paddingBottom),marginBottom:En(o.marginBottom),position:o.position}:null,bottomOverlay:{present:f.content!=="none"&&f.content!=="normal",height:En(f.height),bottom:En(f.bottom),position:f.position,zIndex:En(f.zIndex)},gaps:{cardToShellBottom:l&&i?$t(i.bottom-l.bottom):null,shellToClientBottom:i?$t(e.clientHeight-i.bottom):null,composerToVisualBottom:a&&d?$t(d.offsetTop+d.height-a.bottom):null}}}const EA="pichamber_session_load_perf",Ip=1e3,_A=new Set(["bootstrap.directory","bootstrap.sessions.all","bootstrap.sessions.archived","bootstrap.sessions.roots","global-sessions.active","global-sessions.archived","session-messages.initial","session-messages.older","session-messages.page","session-messages.refresh","session-messages.visible","session-prefetch"]),jA=new Set(["action-demand","current-directory","initial","initial-page","known-project","known-worktree","older","pagination","prefetch","project-expanded","refresh","selected-session","server-connected","worktree-expanded"]),TA=new Set(["complete","error","stale","deduplicated","canceled"]),o3=()=>{if(Xo())return!0;if(typeof window>"u")return!1;try{return window.localStorage.getItem(EA)==="1"}catch{return!1}};function AA(){return typeof window>"u"?0:window.__pichamberSessionLoadPerformance?.events.length??0}function NA(){typeof window>"u"||window.__pichamberSessionLoadPerformance&&(window.__pichamberSessionLoadPerformance.events=[])}const J2=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),LA=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,zf=e=>Number.isInteger(e)&&Number(e)>=0?Number(e):void 0;function RA(e){if(!o3()||!_A.has(e.operation)||e.caller!==void 0&&!jA.has(e.caller))return()=>{};const t=J2();return(n,r)=>{if(typeof window>"u"||!TA.has(n))return;const s=window.__pichamberSessionLoadPerformance??{events:[]},o=LA(e.queuedMs),i=zf(e.requestLimit),a=zf(r?.retryCount??e.retryCount),l=zf(r?.recordCount??e.recordCount);s.events.push({operation:e.operation,...e.caller!==void 0?{caller:e.caller}:{},...o!==void 0?{queuedMs:o}:{},...i!==void 0?{requestLimit:i}:{},...typeof e.cursorPresent=="boolean"?{cursorPresent:e.cursorPresent}:{},outcome:n,durationMs:Math.max(0,J2()-t),...a!==void 0?{retryCount:a}:{},...l!==void 0?{recordCount:l}:{},at:Date.now()}),s.events.length>Ip&&s.events.splice(0,s.events.length-Ip),window.__pichamberSessionLoadPerformance=s}}const Q2="pichamber.chat.first_message_visible";function PA(e){const t=e?.enabled??o3,n=e?.requestFrame??(l=>window.requestAnimationFrame(l)),r=e?.cancelFrame??(l=>window.cancelAnimationFrame(l)),s=e?.markVisible??(()=>{performance.mark(Q2),performance.clearMarks(Q2)}),o=e?.startEvent??RA,i=new Set;let a=null;return{schedule(l,d){if(!t()||i.has(l))return()=>{};a&&(r(a.frame),a=null);const f=o({operation:"session-messages.visible",caller:"selected-session",recordCount:d}),u=n(()=>{a?.key!==l||a.frame!==u||(a=null,i.add(l),i.size>Ip&&i.delete(i.values().next().value),s(),f("complete"))});return a={key:l,frame:u},()=>{a?.key!==l||a.frame!==u||(r(u),a=null)}}}}const DA=1e3,OA=6,HA=16.7,FA=50,BA=(e,t)=>{if(e.length===0)return 0;const n=e.slice().sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[r]??0},VA=(e=DA)=>{const t=[],n=[];let r=0,s=!1;const o=i=>{const a=i-e;for(;t.length>0&&(t[0]??0)<a;)t.shift(),n.shift()};return{reset(){t.length=0,n.length=0,r=0,s=!1},sample(i){s&&(t.push(i),n.push(i-r),o(i)),r=i,s=!0},snapshot(){if(n.length===0||t.length<1)return{fps:0,lastMs:0,p95Ms:0,samples:0};const i=(t[t.length-1]??0)-(t[0]??0);return{fps:i>0?1e3*(t.length-1)/i:0,lastMs:n[n.length-1]??0,p95Ms:BA(n,95),samples:n.length}}}},ey=(e,t=OA)=>e.filter(n=>n.value>0&&Number.isFinite(n.value)).sort((n,r)=>r.value-n.value||n.metric.localeCompare(r.metric)).slice(0,t).map(n=>({metric:n.metric,value:n.value})),wi=(e,t=1)=>Number.isFinite(e)?e.toFixed(t):"—",$A=e=>typeof e!="number"||!Number.isFinite(e)||e<0?null:e/(1024*1024),zA=250,UA=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),qA=()=>{if(typeof performance>"u")return null;const e=performance.memory?.usedJSHeapSize;return typeof e=="number"&&Number.isFinite(e)?e:null},WA=e=>{if(typeof PerformanceObserver>"u")return()=>{};try{const t=new PerformanceObserver(n=>{for(const r of n.getEntries())typeof r.duration=="number"&&r.duration>0&&e(r.duration)});return t.observe({type:"longtask",buffered:!0}),()=>t.disconnect()}catch{return()=>{}}},KA=(e,t={})=>{const n=(t.getStreamSnapshot??QS)(),r=(t.getSyncSnapshot??ew)(),s=(t.getSessionLoadEventCount??AA)(),o=ey(n.entries.map(a=>({metric:a.metric,value:a.count}))),i=ey(Object.entries(r??{}).map(([a,l])=>({metric:`sync.${a}`,value:typeof l=="number"?l:0})));return{...e,capturedAt:Date.now(),stream:o,sync:i,sessionLoadEvents:s}},GA=(e,t={})=>{const n=t.now??UA,r=t.requestFrame??(S=>window.requestAnimationFrame(S)),s=t.cancelFrame??(S=>window.cancelAnimationFrame(S)),o=t.observeLongTasks??WA,i=t.readHeapUsedBytes??qA,a=VA();let l=0,d=0,f=0,u=0,h=0,m=!1;const g=o(S=>{l+=1,d=S,f+=S}),x=S=>{const y=a.snapshot();e(KA({fps:y.fps,frameMs:{last:y.lastMs,p95:y.p95Ms},longTasks:{count:l,lastMs:d,totalMs:f},heapUsedMb:$A(i())},t)),u=S},b=S=>{if(m)return;const y=typeof S=="number"&&Number.isFinite(S)?S:n();a.sample(y),(u===0||y-u>=zA)&&x(y),h=r(b)};return h=r(b),{stop(){m=!0,s(h),g(),a.reset()},reset(){a.reset(),l=0,d=0,f=0,ZA(),x(n())}}},ZA=()=>{JS(),Qb(),NA()},YA=()=>({capturedAt:0,fps:0,frameMs:{last:0,p95:0},longTasks:{count:0,lastMs:0,totalMs:0},heapUsedMb:null,stream:[],sync:[],sessionLoadEvents:0});let Ep=YA();const XA=()=>p.useSyncExternalStore(tC,Xo,()=>!1),JA=e=>e>=FA?"var(--status-error)":e>=HA?"var(--status-warning)":"var(--surface-foreground)",Qs=(e,t)=>{e&&e.textContent!==t&&(e.textContent=t)},QA=e=>{const t=[...e.stream.map(n=>`${n.metric} ${n.value}`),...e.sync.map(n=>`${n.metric} ${n.value}`)];return e.sessionLoadEvents>0&&t.push(`session-load.events ${e.sessionLoadEvents}`),t.length>0?t.join(`
43
- `):"no counters yet"},Zc=8,Uf=(e,t,n,r)=>{if(typeof window>"u")return{left:e,top:t};const s=window.visualViewport,o=s?.offsetLeft??0,i=s?.offsetTop??0,a=s?.width||window.innerWidth,l=s?.height||window.innerHeight,d=o+Zc,f=i+Zc,u=Math.max(d,o+a-n-Zc),h=Math.max(f,i+l-r-Zc);return{left:Math.round(Math.min(Math.max(e,d),u)),top:Math.round(Math.min(Math.max(t,f),h))}},ty=(e,t)=>{e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.right="auto",e.style.transform="none"},eN=()=>{const[e,t]=p.useState(!1),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(null),[l,d]=p.useState(null),f=p.useRef(null),u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(null),y=p.useRef(Ep),v=p.useRef(null),C=p.useCallback(k=>{const _=f.current;if(!_||u.current)return;const M=_.getBoundingClientRect(),L=Uf(k.left,k.top,M.width,M.height);L.left===k.left&&L.top===k.top||(ty(_,L),r(L))},[]);p.useLayoutEffect(()=>{n&&C(n)},[l,e,C,i,n]),p.useEffect(()=>{if(!n||typeof window>"u")return;const k=()=>{C(n)},_=window.visualViewport;return window.addEventListener("resize",k),_?.addEventListener("resize",k),()=>{window.removeEventListener("resize",k),_?.removeEventListener("resize",k)}},[C,n]);const w=p.useCallback(k=>{if(k.button!==0||u.current)return;const _=f.current;if(!_)return;const M=_.getBoundingClientRect();u.current={pointerId:k.pointerId,offsetX:k.clientX-M.left,offsetY:k.clientY-M.top,originLeft:M.left,originTop:M.top,left:M.left,top:M.top,width:M.width,height:M.height};try{k.currentTarget.setPointerCapture(k.pointerId)}catch{}o(!0),k.preventDefault()},[]),I=p.useCallback(k=>{const _=u.current;if(!_||_.pointerId!==k.pointerId)return;const M=Uf(k.clientX-_.offsetX,k.clientY-_.offsetY,_.width,_.height);M.left===_.left&&M.top===_.top||(_.left=M.left,_.top=M.top,f.current?.style.setProperty("transform",`translate3d(${M.left-_.originLeft}px, ${M.top-_.originTop}px, 0)`),k.cancelable&&k.preventDefault())},[]),E=p.useCallback((k,_)=>{const M=u.current;if(!M||M.pointerId!==k.pointerId)return;const L=f.current,O=L?.getBoundingClientRect(),N=_?{left:M.originLeft,top:M.originTop}:Uf(k.clientX-M.offsetX,k.clientY-M.offsetY,O?.width??M.width,O?.height??M.height);u.current=null,L&&(_?L.style.transform="none":ty(L,N)),o(!1),_||r(N);try{k.currentTarget.hasPointerCapture(k.pointerId)&&k.currentTarget.releasePointerCapture(k.pointerId)}catch{}},[]);p.useEffect(()=>()=>{u.current=null},[]),p.useEffect(()=>{const _=GA(M=>{Ep=M,y.current=M,Qs(h.current,wi(M.fps,0)),Qs(m.current,`${wi(M.frameMs.last)}ms`),Qs(g.current,`${wi(M.frameMs.p95)}ms`),g.current&&(g.current.style.color=JA(M.frameMs.p95)),Qs(x.current,`${M.longTasks.count} / ${wi(M.longTasks.lastMs,0)}ms`),Qs(b.current,M.heapUsedMb==null?"—":`${wi(M.heapUsedMb,0)}MB`),Qs(S.current,QA(M))});return v.current=_,()=>{_.stop(),v.current=null}},[]);const T=p.useCallback(()=>{try{const k=IA();return a(k),d(k?null:"Layout measurements unavailable."),k}catch{return a(null),d("Layout measurement failed."),null}},[]),A=p.useCallback(()=>{const k=T();yr(`${JSON.stringify({...y.current,layout:k},null,2)}
44
- `).then(_=>{if(!_.ok){t(!1),d("Copy failed. Use the displayed measurements if available.");return}d(k?"Snapshot copied.":"Performance snapshot copied. Layout measurements unavailable.")}).catch(()=>{t(!1),d("Copy failed. Use the displayed measurements if available.")})},[T]),j=p.useCallback(()=>{v.current?.reset()},[]);return c.jsxs("aside",{ref:f,role:"complementary","aria-label":"Performance overlay",className:"pointer-events-auto fixed z-[300] w-[18.5rem] max-w-[calc(100vw-1.5rem)] rounded-lg border border-border bg-[var(--surface-elevated)] text-foreground [contain:layout_style]",style:{...n?{left:`${n.left}px`,top:`${n.top}px`,right:"auto"}:{top:"calc(0.5rem + env(safe-area-inset-top, 0px))",right:"calc(0.5rem + env(safe-area-inset-right, 0px))"},transform:"none"},children:[c.jsxs("div",{className:"flex items-center gap-1 px-2 py-1",children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 cursor-grab touch-none select-none items-center gap-1",s?"cursor-grabbing":"active:cursor-grabbing"),title:"Drag to move performance overlay",onPointerDown:w,onPointerMove:I,onPointerUp:k=>E(k,!1),onPointerCancel:k=>E(k,!0),onLostPointerCapture:k=>E(k,!0),children:[c.jsx($,{name:"draggable",className:"size-3.5 text-muted-foreground"}),c.jsx("p",{className:"min-w-0 flex-1 typography-micro font-medium",children:"Performance"})]}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Copy performance and layout snapshot",onPointerDown:k=>k.preventDefault(),onClick:A,children:c.jsx($,{name:"file-copy",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Reset performance counters",onClick:j,children:c.jsx($,{name:"refresh",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":e?"Expand performance overlay":"Collapse performance overlay","aria-expanded":!e,onClick:()=>t(k=>!k),children:c.jsx($,{name:e?"arrow-down-s":"arrow-up-s",className:"size-3.5"})}),c.jsx(be,{variant:"ghost",size:"xs","aria-label":"Turn off performance overlay",onClick:()=>Yl(!1),children:c.jsx($,{name:"close",className:"size-3.5"})})]}),c.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 px-2 pb-2 font-mono typography-micro tabular-nums text-muted-foreground",children:[c.jsx("span",{children:"FPS"}),c.jsx("span",{ref:h,className:"text-right text-foreground",children:"0"}),c.jsx("span",{children:"Frame"}),c.jsx("span",{ref:m,className:"text-right text-foreground",children:"0.0ms"}),c.jsx("span",{children:"p95"}),c.jsx("span",{ref:g,className:"text-right",children:"0.0ms"}),c.jsx("span",{children:"Long"}),c.jsx("span",{ref:x,className:"text-right text-foreground",children:"0 / 0ms"}),c.jsx("span",{children:"Heap"}),c.jsx("span",{ref:b,className:"text-right text-foreground",children:"—"})]}),e?null:c.jsx("pre",{ref:S,className:"max-h-40 overflow-auto border-t border-border px-2 py-1.5 font-mono typography-micro text-muted-foreground whitespace-pre-wrap",children:"no counters yet"}),e?null:c.jsxs("div",{className:"border-t border-border px-2 py-1.5",children:[c.jsx(be,{variant:"ghost",size:"xs",onPointerDown:k=>k.preventDefault(),onClick:T,children:"Measure layout"}),l?c.jsx("p",{role:"status",className:"typography-micro text-muted-foreground",children:l}):null,i?c.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap font-mono typography-micro text-muted-foreground",children:JSON.stringify(i,null,2)}):null]})]})},IJ=()=>{const e=XA();return p.useLayoutEffect(()=>{eC()},[]),p.useEffect(()=>{if(!(typeof window>"u"))return window.__pichamberPerfHud={setEnabled:Yl,isEnabled:Xo,getSnapshot:()=>Ep},()=>{delete window.__pichamberPerfHud}},[]),!e||typeof document>"u"||!document.body?null:ba.createPortal(c.jsx(eN,{}),document.body)},u1=48,tN=e=>e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,u1).replace(/-$/g,""),nN=e=>{const t=e.trim();return t.length===0||t.length>u1?null:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)?t:null},ny=e=>{const t=tN(e.trim());return t&&t.split("-").filter(Boolean).slice(0,7).join("-").slice(0,u1).replace(/-$/g,"")||null},rN=async(e,t)=>{const n=e.trim();if(!n||!t)return ny(n);try{const r=await Rt("/api/pi/small-model/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:n,directory:t})});if(r.ok){const s=await r.json().catch(()=>null);if(typeof s?.text=="string"){const o=nN(s.text);if(o)return o}}}catch{}return ny(n)},sN=500,Pl="Worktree creation superseded.",_p=e=>{const t=de(e.projectRoot)??e.projectRoot,n=de(e.sourceDirectory)??e.sourceDirectory;return JSON.stringify([e.runtimeKey,t,n,e.startRef])},i3=e=>e?_p(e):null,oN=e=>new Promise(t=>{setTimeout(t,e)}),iN=(e,t)=>!!(e&&t&&e.runtimeKey===t.runtimeKey&&de(e.projectRoot)===de(t.projectRoot)&&de(e.sourceDirectory)===de(t.sourceDirectory)&&e.startRef===t.startRef),aN=(e,t)=>({...e,path:t.path,branch:t.branch}),Ir=new Map,Si=new Map,cN=e=>({prompt:e.prompt,confirmedMentions:Array.from(new Set(Array.isArray(e.confirmedMentions)?e.confirmedMentions:[...e.confirmedMentions])),attachments:e.attachments.map(su)}),Ci=(e,t,n)=>{e(r=>{const s=r.entries.get(t),o=n(s,Date.now());if(!o&&!s)return r;const i=new Map(r.entries);return o?i.set(t,o):i.delete(t),{entries:i}})},cn=Et()((e,t)=>{const n=(a,l,d)=>{Ci(e,a,(f,u)=>f?{...f,state:d,failedSend:null,updatedAt:u}:{key:a,intent:l,state:d,receipt:null,failedSend:null,notificationSent:!1,startedAt:u,updatedAt:u})},r=(a,l,d,f)=>{Ci(e,a,(u,h)=>({key:a,intent:l,state:d,receipt:null,failedSend:f,notificationSent:u?.notificationSent??!1,path:u?.path??null,branch:u?.branch??null,startedAt:u?.startedAt??h,updatedAt:h}))},s=(a,l,d,f,u,h)=>{Ci(e,a,(m,g)=>({key:a,intent:l,state:null,receipt:d,failedSend:f,notificationSent:m?.notificationSent??!1,path:u??d.path,branch:h??d.branch,startedAt:m?.startedAt??g,updatedAt:g}))},o=(a,l,d)=>{Ci(e,a,(f,u)=>f?{...f,path:l,branch:d,updatedAt:u}:null)},i=async a=>{const{intent:l,prompt:d,git:f,refreshProject:u}=a,h=a.failedSend?cN(a.failedSend):null,m=a.pollIntervalMs??sN,g=a.taskId??_p(l),x=(Ir.get(g)??0)+1;Ir.set(g,x);const b=()=>Ir.get(g)!==x||l.runtimeKey!==Y(),S=()=>{!f||l.runtimeKey!==Y()||u(l.projectRoot,f,{force:!0}).catch(()=>{})};if(n(g,l,{phase:"naming",label:"Naming worktree..."}),!f?.createGitWorktree||!f.getGitWorktreeBootstrapStatus){const y="Git worktrees are unavailable for this runtime.";throw r(g,l,{phase:"failed",label:"Worktree creation failed",error:y},h),new Error(y)}if(l.runtimeKey!==Y()){const y="The runtime changed. Select New worktree again.";throw r(g,l,{phase:"failed",label:"Worktree creation stopped",error:y},h),new Error(y)}try{const y=await rN(d,l.sourceDirectory);if(b())throw new Error(Pl);const v={mode:"new",startRef:l.startRef,...y?{worktreeName:y}:{},returnAfterDirectoryCreated:!0};if(f.validateGitWorktree){const E=await f.validateGitWorktree(l.sourceDirectory,v);if(!E.ok)throw new Error(E.errors.map(T=>T.message).filter(Boolean).join(`
45
- `)||"The worktree request is invalid.")}if(b())throw new Error(Pl);n(g,l,{phase:"creating",label:"Creating worktree..."});const C=await f.createGitWorktree(l.sourceDirectory,v),w=aN(l,C);if(b())return w;o(g,C.path,C.branch);let I=C.bootstrapStatus;for(;I.status==="pending";){if(b()||(n(g,l,I.phase==="directory-created"?{phase:"checking-out",label:"Checking out files..."}:{phase:"setting-up",label:"Setting up project..."}),await oN(m),b()))return w;I=await f.getGitWorktreeBootstrapStatus(C.path)}if(I.status==="failed"||I.phase!=="setup-ready")throw new Error(I.error||"Worktree setup failed.");try{await u(l.projectRoot,f,{force:!0})}catch{}return b()||s(g,l,w,h,C.path,C.branch),w}catch(y){if(b())throw y;const v=y instanceof Error?y.message:"Failed to create the worktree.";throw v===Pl||(S(),r(g,l,{phase:"failed",label:"Worktree creation failed",error:v},h)),y}};return{runtimeKey:Y(),entries:new Map,getEntry:a=>{const l=i3(a);return l?t().entries.get(l)??null:null},getEntryByKey:a=>t().entries.get(a)??null,getActiveEntries:()=>{const a=[];for(const l of t().entries.values())l.state&&l.state.phase!=="failed"&&a.push(l);return a},clearEntry:a=>{e(l=>{if(!l.entries.has(a))return l;const d=new Map(l.entries);return d.delete(a),Ir.delete(a),{entries:d}})},consumeFailedSend:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||u.state?.phase!=="failed"||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),Ir.delete(a),d=!0,{entries:h}}),d},markWorktreePromptSucceeded:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||!u.receipt||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),Ir.delete(a),d=!0,{entries:h}}),d},markWorktreePromptFailed:(a,l,d)=>{let f=!1;return e(u=>{const h=u.entries.get(a);if(!h||!h.receipt||h.failedSend!==l)return u;const m=new Map(u.entries);return m.set(a,{...h,state:{phase:"failed",label:"Prompt failed to send",error:d},updatedAt:Date.now()}),f=!0,{entries:m}}),f},markNotificationSent:a=>{Ci(e,a,(l,d)=>!l||l.notificationSent?l??null:{...l,notificationSent:!0,updatedAt:d})},dismissFailed:a=>{e(l=>{if(l.entries.get(a)?.state?.phase!=="failed")return l;const f=new Map(l.entries);return f.delete(a),Ir.delete(a),{entries:f}})},resetForRuntimeSwitch:a=>{Ir.clear(),Si.clear(),e({runtimeKey:a,entries:new Map})},request:a=>{const l=a.taskId??_p(a.intent),d=Si.get(l);if(d)return d;const f=i(a).finally(()=>{Si.get(l)===f&&Si.delete(l)});return Si.set(l,f),f}}}),a3=e=>i3(e),lN=iN,dN=async e=>(await sw([...e])).map(su),uN=(e,t)=>e??t,c3=(e,t)=>(e??t).map(n=>n.id),jp=e=>{const t=Math.max(1,e.currentCount+e.missingCount-e.limit),n=r=>r===1?"file":"files";return{title:"Too many attachments to restore",description:`Remove ${t} ${n(t)} to restore ${e.missingCount} ${n(e.missingCount)}. You can attach up to ${e.limit} files to one message.`}},fN=(e,t)=>e.ok?null:e.reason==="runtime-mismatch"?{title:"The runtime changed",description:"Your failed prompt was kept in Background tasks."}:e.reason==="target-occupied"?{title:"Draft already has content",description:t==="pending-composer"?"Your restored prompt was kept in Background tasks.":"Your failed prompt was kept in Background tasks."}:e.reason==="attachment-limit"?jp(e):(t==="background-task"?e.reason==="missing":e.reason==="dismissed"||e.reason==="navigated-away")?null:{title:"Could not restore the failed prompt",description:"Your prompt was kept in Background tasks."},l3=()=>{try{const e=he.getState(),t=e.newSessionDraft?.open?e.newSessionDraft.directoryOverride:null,n=e.currentSessionId,r=n?e.getDirectoryForSession(n)??e.currentSessionDirectory:t??nt.getState().currentDirectory,s=Jo(Y(),r,n);return s?Qt(s):null}catch{return null}},EJ=e=>{const t=cn.getState(),n=t.getEntryByKey(e),r=n?.failedSend;if(!n||!r)return{ok:!1,reason:"missing"};if(n.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const s=Jo(Y(),n.intent.sourceDirectory,null);if(!s)return{ok:!1,reason:"invalid-target"};const o=Qt(s);try{const d=ru(s);if(d.text.trim().length>0&&d.text!==r.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const i=l3();if(i!==null&&i===o){try{he.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}const d={entryKey:e,prompt:r.prompt,confirmedMentions:[...r.confirmedMentions],targetKey:o,attachments:r.attachments.map(su),expectedFailedSend:r};try{Ye.getState().requestWorktreeRestore(d)}catch{return{ok:!1,reason:"open-failed"}}return{ok:!0,reason:"pending"}}const l=t.getEntryByKey(e);if(!l||l.failedSend!==r)return{ok:!1,reason:"missing"};try{he.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}try{As(s,r.prompt,r.confirmedMentions)}catch{return{ok:!1,reason:"invalid-target"}}try{Ye.getState().activateAttachmentsDraft(o);const d=Ye.getState().restoreAttachmentsForRetry(r.attachments);if(!d.ok)return{ok:!1,reason:"attachment-limit",limit:d.limit,currentCount:d.currentCount,missingCount:d.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!t.consumeFailedSend(e,r))return{ok:!1,reason:"missing"}}catch{return{ok:!0}}return{ok:!0}},hN=(e,t)=>{const n=cn.getState(),r=n.getEntryByKey(e.entryKey),s=r?.failedSend;if(!r||!s)return{ok:!1,reason:"dismissed"};if(s!==e.expectedFailedSend)return{ok:!1,reason:"dismissed"};if(r.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const o=Jo(Y(),r.intent.sourceDirectory,null);if(!o)return{ok:!1,reason:"invalid-target"};const i=Qt(o);if(i!==e.targetKey)return{ok:!1,reason:"invalid-target"};const a=l3();if(a!==null&&a!==i)return{ok:!1,reason:"navigated-away"};const l=t??"";if(l.trim().length>0&&l!==e.prompt)return{ok:!1,reason:"target-occupied"};try{const u=ru(o);if(u.text.trim().length>0&&u.text!==e.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const d=de(r.intent.sourceDirectory),f=de(o.directory);if(!d||d!==f)return{ok:!1,reason:"invalid-target"};try{As(o,e.prompt,e.confirmedMentions),Ye.getState().activateAttachmentsDraft(i);const u=Ye.getState().restoreAttachmentsForRetry(e.attachments);if(!u.ok)return{ok:!1,reason:"attachment-limit",limit:u.limit,currentCount:u.currentCount,missingCount:u.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!n.consumeFailedSend(e.entryKey,s))return{ok:!1,reason:"dismissed"}}catch{return{ok:!0}}return{ok:!0}},_J=e=>!!(e?.receipt&&e?.failedSend&&!e?.state),pN=e=>!!(e?.receipt&&!e?.state&&!e?.failedSend),jJ=e=>pN(e),TJ=e=>!!(e?.receipt&&!e?.notificationSent&&!e?.state&&!e?.failedSend),mN=(e,t,n)=>{if(!e||!t)return!1;try{return cn.getState().markWorktreePromptFailed(e,t,n)}catch{return!1}},gN=(e,t,n,r)=>{if(!e||!t)return!1;let s=!1;try{s=cn.getState().markWorktreePromptSucceeded(e,t)}catch{return!1}if(!s)return!1;if(!n||n.length===0)return!0;try{const o=c3(n,r);o.length>0&&Ye.getState().detachAttachedFiles(o)}catch{}return!0},yN=600*1e3,Tp="pending-input:",vN=e=>!Number.isFinite(e.ageMs)||Math.max(0,e.ageMs)>yN||e.isCurrent&&e.visible&&e.focused?"none":!e.visible||!e.focused||e.mode==="always"&&!e.isCurrent?"toast-and-notify":"toast",wd=e=>`${Tp}${e}`,xN=e=>e==="approval"?"Approval needed":"Input needed",ry=e=>{const t=qe().getState().catalog.byId.get(e);return t?n3(Ls(t),"Untitled session"):"Untitled session"},bN=(e,t,n)=>{const r=he.getState().currentSessionId===e,s=typeof document<"u"&&document.visibilityState==="visible";let o=!1;try{o=typeof document<"u"&&document.hasFocus()}catch{o=!1}const i=re.getState().notificationMode,a=Date.now(),l=Fo(t.since,n,a)??t.since;return{isCurrent:r,visible:s,focused:o,mode:i==="always"?"always":"hidden-only",ageMs:a-l}},d3=(e,t)=>{he.getState().setCurrentSession(e,t)},sy=(e,t,n,r,s)=>{Ce.warning(xN(n.kind),{id:wd(e),description:r,duration:1/0,onDismiss:s,onAutoClose:s,action:{label:"Open session",onClick:()=>d3(e,t||null)}})},wN=(e,t)=>{const n=[];for(const[r,s]of e){const o=t(r);o!==s.label&&n.push([r,o])}return n},SN=(e,t,n,r)=>{e.get(n)?.raise===r&&(e.delete(n),t.delete(wd(n)))},CN=(e,t,n)=>{const r=[];for(const s of e){if(t.has(s))continue;const o=n(s);o.exists&&o.pendingInput===null&&r.push(s)}return r},AJ=()=>{const e=he(d=>d.currentSessionId),t=p.useRef(new Map),n=p.useRef(new Set),r=p.useRef(new Map),s=p.useRef(0),o=p.useCallback((d,f)=>{SN(r.current,n.current,d,f)},[]),i=p.useCallback(d=>{const f=wd(d);n.current.delete(f),r.current.delete(d),Ce.dismiss(f);const u=t.current.get(d);if(u!==void 0){t.current.delete(d);const h=zr()?.notifications?.close;h&&h(u).catch(()=>{})}},[]),a=p.useCallback(()=>{for(const f of n.current)Ce.dismiss(f);n.current.clear(),r.current.clear();const d=zr()?.notifications?.close;if(d)for(const f of t.current.values())d(f).catch(()=>{});t.current.clear()},[]);p.useEffect(()=>xE(d=>{if(d.type==="cleared"||!d.pending){i(d.sessionId);return}const f=d.pending,u=vN(bN(d.sessionId,f,d.serverNow));if(u==="none")return;const h=ry(d.sessionId),m=++s.current,g=d.sessionId;if(n.current.add(wd(g)),r.current.set(g,{directory:d.directory,pending:f,label:h,raise:m}),sy(g,d.directory,f,h,()=>o(g,m)),u==="toast-and-notify"){const x=Dm(d.sessionId,f.since);t.current.set(d.sessionId,x),Xb({sessionId:d.sessionId,directory:d.directory,since:f.since,kind:f.kind,title:h})}}),[i,o]),p.useEffect(()=>qe().subscribe(()=>{if(r.current.size!==0)for(const[d,f]of wN(r.current,ry)){const u=r.current.get(d);u&&(r.current.set(d,{...u,label:f}),sy(d,u.directory,u.pending,f,()=>o(d,u.raise)))}},yt),[o]),p.useEffect(()=>{e&&i(e)},[e,i]);const l=Mw();return p.useEffect(()=>{const d=new Set(l.map(m=>m.sessionId)),f=new Set(t.current.keys());for(const m of n.current)m.startsWith(Tp)&&f.add(m.slice(Tp.length));if(f.size===0)return;const u=qe().getState().catalog,h=CN([...f],d,m=>{const g=u.byId.get(m);return g?{exists:!0,pendingInput:g.pendingInput}:{exists:!1,pendingInput:void 0}});for(const m of h)i(m)},[l,i]),p.useEffect(()=>Zt(()=>{a()}),[a]),p.useEffect(()=>()=>{a()},[a]),null},NJ=()=>{const t=Mw().length,n=re(r=>r.dockBadgeEnabled);return p.useEffect(()=>{const r=xt()&&!n?0:t;try{zr()?.notifications?.setAttentionCount?.(r)}catch{}},[t,n]),p.useEffect(()=>()=>{try{zr()?.notifications?.setAttentionCount?.(0)}catch{}},[]),null},kN=()=>{const e=ze(t=>Wm(t.catalog).length,Object.is,"catalog");return e<=0||xt()||cr()?"":`(${e}) `},LJ=()=>(p.useEffect(()=>{const e=t=>{const n=t.detail,r=typeof n?.sessionId=="string"?n.sessionId.trim():"";if(!r)return;const s=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():null;d3(r,s)};return window.addEventListener("pichamber:open-session",e),()=>window.removeEventListener("pichamber:open-session",e)},[]),null),MN=e=>e.replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase()),za=(e,t=null)=>{const n=e.label?.trim();return n||MN(nC(e.path,t)||e.path)},IN="PiChamber",EN=(e,t)=>[e,t,IN].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),_N=()=>{const e=he(l=>l.currentSessionId),t=ze(l=>e?l.reducer.bySession.get(e)?.extensionTitle??null:null,Object.is,e?`session:${e}`:"chrome"),n=lt(l=>l.activeProjectId?l.projects.find(d=>d.id===l.activeProjectId)??null:null),r=p.useMemo(()=>n&&za(n)||null,[n]),[s,o]=p.useState(null),i=kN();p.useEffect(()=>{if(typeof window>"u"||!xt()){o(null);return}let l=!1;const d=async()=>{try{if(Yr()){l||o(null);return}const u=window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,h=qd();if(h&&Jg(h,u)){l||o(null);return}const g=(await vm()).hosts.find(b=>h?Jg(h,ml(b)):!1),x=g?.label?.trim()?qn(g.label.trim()):"Instance";l||o(x)}catch{l||o("Instance")}};d();const f=()=>{d()};return window.addEventListener("focus",f),()=>{l=!0,window.removeEventListener("focus",f)}},[]);const a=p.useMemo(()=>`${i}${EN(t?.trim()||r,s)}`,[t,s,r,i]);p.useEffect(()=>{if(typeof document<"u"&&(document.title=a),!xt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await z_(a)}catch{return}})()},[a])},RJ=()=>(_N(),null),jN=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]),TN=e=>{try{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;const n=t.hostname.toLowerCase();return jN.has(n)}catch{return!1}},f1=()=>Vr()&&Yr()?"device":"server",PJ=(e,t)=>Qg(e)??(Vr()?Qg(t):null)??f1(),AN=10*6e4,Ap=e=>TN(e)?"panel":"external",NN=e=>Math.max(0,e.serverNow-e.createdAt),DJ=e=>({showNotice:NN(e)<=AN,target:Ap(e.url)}),OJ=(e,t,n)=>t==="external"?{title:"Open this page?",description:`${e}. Opens in your browser.`,canOpen:!0}:n.isMobile?{title:"A page is ready to view",description:`${e}. Open PiChamber on a larger screen to view it.`,canOpen:!1}:{title:"Open this page?",description:`${e}. Opens in the PiChamber browser.`,canOpen:!0},LN=e=>{try{const t=new URL(e),n=t.pathname==="/"?"":t.pathname,r=`${t.host}${n}`;return r.length>80?`${r.slice(0,79)}…`:r}catch{return e.slice(0,80)}},RN=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,PN=/\bhttps?:\/\/[^\s<>"'`\u0000-\u001f]+/gi,DN=(e,t=3)=>{if(!e)return[];const n=[];for(const r of e.replace(RN," ").match(PN)??[]){const s=r.replace(/[),.;:!?'"`\]]+$/g,"");let o;try{o=new URL(s)}catch{continue}if(!(o.protocol!=="http:"&&o.protocol!=="https:")&&!n.includes(s)&&(n.push(s),n.length>=t))break}return n},ON=()=>{const{currentSessionId:e,newSessionDraft:t}=he.getState();if(e){const n=qe().getState(),r=n.catalog.byId.get(e)?.directory??n.directory;if(r)return r}return t?.open&&t.directoryOverride?t.directoryOverride:nt.getState().currentDirectory??void 0},HN=(e,t,n)=>{if(e==="external")return ja(t),!0;const r=re.getState();return r.isMobile?!1:(r.openContextBrowser(n,t,{route:f1()}),!0)},HJ=e=>{const t=re.getState(),n=t.chatLinkTarget==="pichamber"&&!t.isMobile?ON():void 0;if(!n){ja(e);return}t.openContextBrowser(n,e,{route:f1()})},oy=(e,t)=>{const n=de(t??null);if(!n)return;const r=n.toLowerCase();e.has(r)||e.set(r,n)},u3=(e,t,n)=>{const r=new Map;for(const s of e)oy(r,s?.path);if(n?.includeWorktrees===!1||!t)return new Set(r.values());for(const s of t.values())if(s)for(const o of s)oy(r,o?.path);return new Set(r.values())},Yc=new Map,FN=e=>{const t=new Set;for(const n of e){const r=de(n);r&&t.add(r)}return t},BN=()=>{const e=new Set,t=lt.getState().projects,n=u3(t,Zn(t,un.getState()),{includeWorktrees:!0});for(const o of n){const i=de(o);i&&i!=="~"&&e.add(i)}const r=de(qe().getState().directory);r&&e.add(r);const s=nt.getState().homeDirectory??null;for(const o of qm(s)){const i=de(o);i&&i!=="~"&&e.add(i)}for(const[o,i]of qe().getState().catalog.byDirectory){if(i.length===0)continue;const a=de(o);a&&a!=="~"&&e.add(a)}return e},VN=async(e,t,n,r,s)=>{const o=e.getState().catalog.listStatusByDirectory,i=r.filter(m=>o.get(m)!=="ready");i.length>0&&await e.refreshAllDirectoryCatalogs(i).catch(()=>{});const a=qe(),l=a!==e||Y()!==t||a.getRuntimeGeneration()!==n,d=a.getState().catalog,f=new Set,u=new Set;for(const m of r){const g=d.listStatusByDirectory.get(m);g==="ready"?f.add(m):g==="failed"&&u.add(m)}const h=!l&&u.size===0&&f.size===r.length&&(s||r.length>0);return{runtimeKey:t,catalog:d,readyDirectories:f,failedDirectories:u,complete:h,stale:l}},$N=e=>{const t=qe(),n=Y(),r=t.getRuntimeGeneration(),s=e!==void 0,i=[...e===void 0?BN():FN(e)].sort(),a=`${n}::${i.join("|")}`,l=Yc.get(a);if(l&&l.store===t&&l.runtimeKey===n&&l.generation===r)return l.promise;const d=VN(t,n,r,i,s);Yc.set(a,{store:t,runtimeKey:n,generation:r,promise:d});const f=()=>{Yc.get(a)?.promise===d&&Yc.delete(a)};return d.then(f,f),d},zN=e=>{if(typeof Element>"u"||!(e instanceof Element))return null;const t=e.closest("[data-terminal-owner]");return t?.isConnected&&t.dataset.terminalOwner||null},qf=e=>zN(e)!==null,UN=e=>{const t=e.info;if(t.finish==="stop"||t.finish==="error")return!0;const n=t.time?.completed,r=t.status;return typeof n!="number"||n<=0?!1:typeof r=="string"?r==="completed":!0},qN=e=>{const{activeStreamingMessageId:t,assistantMessages:n}=e;if(t&&n.some(r=>r.info.id===t))return t;for(let r=n.length-1;r>=0;r--)if(!UN(n[r]))return n[r].info.id;return null},WN=e=>e.connection==="ready"&&(e.authoritativeWorking||e.hasPendingAssistant),KN=e=>{const t=e.connection==="ready"&&!e.transportUncertain,n=e.authoritativeWorking||e.hasPendingAssistant;return{isWorking:t&&n,isAwaitingRecovery:!t&&(n||e.hasRetainedStream)}},GN=e=>e.turnIsInActiveStream||e.isLastTurn&&e.sessionIsWorking&&e.awaitingPromptEcho!==!0&&(e.isSteering===!0||!e.activeStreamingMessageId),ZN=e=>e.isRetrying===!0||e.isAwaitingRecovery===!0||!!e.activeStreamingMessageId&&e.messageId===e.activeStreamingMessageId,Wf={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function YN(e,t){const n=Iw(),r=du(e??""),s=Qm(e??"");return p.useMemo(()=>{if(!e)return Wf;const o=r?.type??"idle",i=s[s.length-1],a=!!(i&&i.role==="assistant"&&typeof i.time?.completed!="number"),l=r!==void 0,d=l&&o!=="idle",f=WN({connection:n,authoritativeWorking:d,hasPendingAssistant:a});return l&&!d||!f?Wf:{phase:d?o:"busy",isWorking:!0,isBusy:o==="busy"||!d&&a,isCooldown:!1}},[n,e,r,s])}function h1(){const e=he(t=>t.currentSessionId);return he(t=>t.currentSessionDirectory),YN(e)}const FJ=.45,p1=[{id:"context",description:"Session context and token usage",mode:"context",icon:"pie-chart",label:"Context",availability:"always"},{id:"editor",description:"Edit project files",mode:"file",icon:"file-text",label:"Files",availability:"always"},{id:"git",description:"Review diffs, commit, and push",mode:"git",icon:"git-branch",label:"Git",availability:"always"},{id:"terminal",description:"Built-in terminal",mode:"terminal",icon:"terminal-box",label:"Terminal",availability:"always"},{id:"browser",description:"Built-in web browser",mode:"browser",icon:"global",label:"Browser",availability:"always"},{id:"preview",description:"Dev server preview",mode:"preview",icon:"window",label:"Preview",availability:"has-content"},{id:"pull-requests",description:"Browse pull requests for this repository",mode:"pull-requests",icon:"git-pull-request",label:"Pull requests",availability:"github-repo"},{id:"issues",description:"Browse issues for this repository",mode:"issues",icon:"task",label:"Issues",availability:"github-repo"},{id:"extensions",description:"Extension widgets for this session",mode:"extensions",icon:"plug-2",label:"Extensions",availability:"extensions"}],f3=new Map(p1.map(e=>[e.id,e])),Kf=p1.find(e=>e.id==="git"),BJ=e=>e===!1?{icon:"arrow-left-right",label:"Changes",description:"Review working and last-turn changes"}:{icon:Kf?.icon??"git-branch",label:Kf?.label??"Git",description:Kf?.description??"Review diffs, commit, and push"},XN=e=>typeof e=="string"&&f3.has(e),JN=e=>{const t=[],n=new Set;for(const r of e){if(!XN(r)||n.has(r))continue;const s=f3.get(r);s&&(n.add(r),t.push(s))}for(const r of p1)n.has(r.id)||t.push(r);return t},VJ=e=>{if(!e)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const t=e.scope?.repositories??[];return{isLoading:e.isLoading,hasResult:!!(e.scope||e.error),hasGitHubRepo:t.some(n=>!!(n.host&&n.owner&&n.repo&&!n.disabledReason)),hasError:!!(e.error&&!e.scope)}},QN=e=>!e||e.isLoading&&!e.hasResult?!1:e.hasError?!0:e.hasGitHubRepo,eL=e=>JN(e.railOrder).filter(t=>t.availability==="has-content"?e.tabs.some(n=>n.mode===t.mode):t.availability==="github-repo"?e.tabs.some(n=>n.mode===t.mode)?!0:QN(e.githubScope):t.availability==="extensions"?e.tabs.some(n=>n.mode===t.mode)?!0:!!e.hasExtensionContent:!0),h3=3e4,fs=()=>({scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),ki=new Map,tL=(e,t)=>`${e}
46
- ${t}`,nL=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub scope check failed"}},Dl=e=>!e.host||!e.owner||!e.repo?null:N5(`${e.host}/${e.owner}/${e.repo}`),Ol=e=>!!(e.host&&e.owner&&e.repo&&!e.disabledReason),m1=(e,t)=>{if(!e)return t;const n=new Set(e.repositories.filter(Ol).map(i=>Dl(i)).filter(i=>!!i));if(t&&n.has(t))return t;if(e.defaultSelection&&n.has(e.defaultSelection))return e.defaultSelection;const r=e.repositories.find(i=>i.kind==="containing"&&Ol(i)),s=r?Dl(r):null;if(s&&n.has(s))return s;const o=e.repositories.find(Ol);return o?Dl(o):null},Ua=Et()(gr((e,t)=>({runtimeKey:Y(),entriesByDirectory:{},resetForRuntimeSwitch:n=>{const r=n??Y();ki.clear(),e({runtimeKey:r,entriesByDirectory:{}})},ensureScope:async(n,r)=>{const s=ys(n.trim());if(!s)return fs();const o=Y();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t().entriesByDirectory[s],a=Date.now();return i?.scope&&i.fetchedAt&&a-i.fetchedAt<h3&&!i.isLoading?i:t().refreshScope(s,r)},refreshScope:async(n,r,s)=>{const o=ys(n.trim());if(!o)return fs();const i=Y();t().runtimeKey!==i&&t().resetForRuntimeSwitch(i);const a=tL(i,o),l=ki.get(a);if(l&&!s?.force)return l;const d=r??null;if(!d)return t().entriesByDirectory[o]??fs();const f=t().entriesByDirectory[o]??fs();f.isLoading||e(h=>({entriesByDirectory:{...h.entriesByDirectory,[o]:{...f,isLoading:!0}}}));const u=(async()=>{try{const h=await d.scope(o);if(Y()!==i)return t().entriesByDirectory[o]??fs();const m={scope:h,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null};e(b=>({entriesByDirectory:{...b.entriesByDirectory,[o]:m}}));const g=re.getState().githubSelectedRepoByDirectory[o]??null,x=m1(h,g);return x!==g&&re.getState().setGitHubSelectedRepo(o,x),m}catch(h){if(Y()!==i)return t().entriesByDirectory[o]??fs();const m=nL(h),g=f.scope?{...f,isLoading:!1,stale:!0,error:m}:{scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:m};return e(x=>({entriesByDirectory:{...x.entriesByDirectory,[o]:g}})),g}})();ki.set(a,u);try{return await u}finally{ki.get(a)===u&&ki.delete(a)}},setSelectedRepo:(n,r)=>{const s=ys(n.trim());if(!s)return;const o=t().entriesByDirectory[s]?.scope??null;if(r!=null){const i=N5(r);if(!i||o&&!new Set(o.repositories.filter(Ol).map(l=>Dl(l)).filter(l=>!!l)).has(i))return;re.getState().setGitHubSelectedRepo(s,i);return}re.getState().setGitHubSelectedRepo(s,null)},invalidate:async(n,r)=>{const s=ys(n.trim());if(!s)return null;const o=r??null;if(o)try{await o.invalidate({directory:s})}catch{}return t().refreshScope(s,o??void 0,{force:!0})}}),{name:"github-scope-store"}));typeof window<"u"&&Zt(e=>{Ua.getState().resetForRuntimeSwitch(e.runtimeKey)});const iy=Object.freeze(fs()),rL=e=>Ua(t=>e?t.entriesByDirectory[ys(e)]??iy:iy),sL=e=>{const t=Ua(r=>e?r.entriesByDirectory[ys(e)]?.scope??null:null),n=re(r=>e?r.githubSelectedRepoByDirectory[ys(e)]??null:null);return p.useMemo(()=>e?m1(t,n):null,[e,t,n])},$J=Object.freeze(Object.defineProperty({__proto__:null,GITHUB_SCOPE_STALE_MS:h3,resolveGitHubSelectedRepo:m1,useGitHubScope:rL,useGitHubScopeStore:Ua,useGitHubSelectedRepo:sL},Symbol.toStringTag,{value:"Module"})),Xn=()=>{const e=he(s=>s.currentSessionId),t=he(s=>s.newSessionDraft),n=a_(e),r=nt(s=>s.currentDirectory);return e&&n?n:t?.open&&t.directoryOverride?t.directoryOverride:r??void 0},oL=()=>({setCurrentVariant:e=>We.getState().setCurrentVariant(e)}),Hi=(e,t=oL())=>(t.setCurrentVariant(e),"applied"),iL=async(e=1)=>{const t=We.getState(),n=jm(t.getCurrentModelVariants(),t.currentVariant,e);return Hi(n),n},aL='[data-chat-input="true"] .cm-content';function To(){document.querySelector(aL)?.focus()}const cL=new Set(["address","article","aside","blockquote","dd","div","dl","dt","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","ul"]),g1=e=>e.replace(/\r\n?/g,`
47
- `),wn=e=>g1(e).trim(),lL=e=>e.replace(/\s+/g," ").trim(),p3=e=>(e.match(/language-([\w+#.-]+)/)?.[1]||"").trim(),dL=e=>e.closest("pre")?.getAttribute("data-md-lang")||p3(e.className),m3=e=>{if(e.nodeType===3)return{type:"text",value:e.textContent||""};if(e.nodeType!==1)return null;const t=e;return{type:"element",tag:t.tagName.toLowerCase(),className:t.getAttribute("class")||"",href:t.getAttribute("href")||"",component:t.getAttribute("data-component")||"",markdownLanguage:t.getAttribute("data-md-lang")||"",isMarkdownBlock:t.hasAttribute("data-md-block"),isCodeLines:t.hasAttribute("data-md-code-lines"),isCodeLineNumber:t.hasAttribute("data-md-code-line-number"),children:Array.from(t.childNodes).map(n=>m3(n)).filter(n=>n!==null)}},y1=e=>e.filter(t=>t.type==="text"||!t.isCodeLineNumber).map(t=>t.type==="text"?t:{...t,children:y1(t.children)}),uL=e=>Array.from(e.childNodes).map(t=>m3(t)).filter(t=>t!==null),ua=e=>e.type==="text"?e.value:e.children.map(t=>ua(t)).join(""),Np=(e,t)=>{if(e.type==="text")return null;if(t(e))return e;for(const n of e.children){const r=Np(n,t);if(r)return r}return null},v1=(e,t="")=>{const n=g1(e).replace(/\n$/,""),r=Math.max(0,...Array.from(n.matchAll(/`+/g),o=>o[0].length)),s="`".repeat(Math.max(3,r+1));return`${s}${t}
48
- ${n}
49
- ${s}`},Ao=e=>{if(e.type==="text")return lL(e.value);const t=e.children.map(n=>Ao(n)).join("").replace(/\s+/g," ").trim();return!t&&e.tag!=="br"?"":e.tag==="br"?`
50
- `:e.tag==="strong"||e.tag==="b"?`**${t}**`:e.tag==="em"||e.tag==="i"?`*${t}*`:e.tag==="code"?`\`${t.replace(/`/g,"\\`")}\``:e.tag==="a"&&e.href?`[${t}](${e.href})`:t},ay=(e,t)=>e.children.filter(n=>n.type==="element"&&n.tag==="li").map((n,r)=>{const s=n.children.map(o=>Ao(o)).join("").replace(/\s+/g," ").trim();return s?`${t?`${r+1}.`:"-"} ${s}`:""}).filter(Boolean).join(`
51
- `),Fi=e=>{if(e.type==="text")return wn(e.value);if(e.isMarkdownBlock)return e.children.map(n=>Fi(n)).filter(n=>n.length>0).join(`
52
-
53
- `);if(e.component==="markdown-code"){const n=Np(e,r=>r.tag==="pre");return n?Fi(n):""}if(e.tag==="pre"||e.tag==="code"&&e.isCodeLines){const n=e.tag==="code"?e:Np(e,r=>r.tag==="code");return v1(ua(n||e),e.markdownLanguage||p3(n?.className||""))}if(e.tag==="code"){const n=g1(ua(e)).trim();return n?`\`${n.replace(/`/g,"\\`")}\``:""}if(e.tag==="ul")return ay(e,!1);if(e.tag==="ol")return ay(e,!0);if(e.tag==="blockquote")return wn(e.children.map(r=>Fi(r)).join(`
54
- `)).split(`
55
- `).filter(r=>r.length>0).map(r=>`> ${r}`).join(`
56
- `);if(/^h[1-6]$/.test(e.tag)){const n=Number.parseInt(e.tag[1],10),r=wn(e.children.map(s=>Ao(s)).join(""));return r?`${"#".repeat(n)} ${r}`:""}if(e.tag==="p"||e.tag==="div"||e.tag==="li")return wn(e.children.map(n=>Ao(n)).join(""));const t=e.children.map(n=>Fi(n)).filter(n=>n.length>0);return t.length>0?t.join(`
57
-
58
- `):wn(e.children.map(n=>Ao(n)).join(""))},fL=e=>e.type==="text"?!0:!e.isMarkdownBlock&&!e.isCodeLines&&e.component!=="markdown-code"&&!cL.has(e.tag),hL=(e,t)=>{const n=y1(e);if(n.every(s=>fL(s))){const s=wn(n.map(o=>Ao(o)).join(""));if(s)return s}return n.map(s=>Fi(s)).filter(s=>s.length>0).join(`
59
-
60
- `).trim()||wn(t)},cy=e=>(e.nodeType===1?e:e.parentElement)?.closest("pre code")??null,g3=(e,t)=>{const n=cy(e.startContainer),r=cy(e.endContainer),s=y1(uL(e.cloneContents()));return n&&n===r?v1(s.map(o=>ua(o)).join(""),dL(n)):hL(s,t)},x1=e=>{const t=Math.max(0,...Array.from(e.matchAll(/`+/g),r=>r[0].length)),n="`".repeat(Math.max(3,t+1));return`${n}md
61
- ${e}
62
- ${n}`},pL='[data-chat-input="true"]',b1=e=>{if(!e)return!1;const t=e;return!!(typeof t.closest=="function"?t:e.parentElement)?.closest(pL)},mL=e=>{if(b1(e))return null;const t=e.tagName?.toLowerCase();if(t==="textarea"){const n=e,r=n.selectionStart??0,s=n.selectionEnd??0,o=wn(n.value.slice(r,s));return o?(n.selectionStart=s,n.selectionEnd=s,o):null}if(t==="input"){const n=e,r=n.type?.toLowerCase()??"text";if(!["text","search","url","tel","password"].includes(r))return null;const s=n.selectionStart??0,o=n.selectionEnd??0,i=wn(n.value.slice(s,o));return i?(n.selectionStart=o,n.selectionEnd=o,i):null}return null},gL=()=>{if(typeof document>"u")return null;const e=document.activeElement;if(!e||typeof e.tagName!="string")return null;const t=mL(e);return t?x1(t):null},yL=()=>{if(typeof document>"u")return null;const e=document.querySelector(".cm-editor.cm-focused");if(!e||b1(e))return null;const t=bn.findFromDOM(e);if(!t)return null;const{from:n,to:r}=t.state.selection.main;if(n===r)return null;const s=wn(t.state.sliceDoc(n,r));return s?(t.dispatch({selection:{anchor:r}}),v1(s)):null},vL=()=>{if(typeof window>"u")return null;const e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return null;const t=e.getRangeAt(0);if(b1(t.commonAncestorContainer))return null;const n=wn(e.toString());if(!n)return null;const r=g3(t,n);return e.removeAllRanges(),x1(r)},xL=()=>yL()??gL()??vL(),y3=()=>{const e=xL();return re.getState().setActiveMainTab("chat"),re.getState().setSessionSwitcherOpen(!1),e&&Ye.getState().setPendingInputText(e,"append"),queueMicrotask(()=>{To()}),e!==null},v3="file://";function bL(e){let t=e.replace(/\\/g,"/");return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split("/").map((n,r)=>r===1&&/^[A-Za-z]:$/.test(n)?n:encodeURIComponent(n)).join("/")}function wL(e){const t=e.replace(/\\/g,"/").trim();return t.toLowerCase().startsWith(v3)?t:`file://${bL(t)}`}function SL(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function ly(e){const t=e.trim().replace(/^['"]+|['"]+$/g,"");return!t||/[\r\n]/.test(t)?null:t.toLowerCase().startsWith(v3)||SL(t)?t:null}function Lp(e,t,n=0){if(!(n>6||e==null)){if(typeof e=="string"){t.add(e);return}if(Array.isArray(e)){for(const r of e)Lp(r,t,n+1);return}if(typeof e=="object")for(const r of Object.values(e))Lp(r,t,n+1)}}function CL(e){const t=new Set,n=r=>{const s=ly(r);if(s){t.add(s);return}for(const o of r.split(/\r?\n/)){const i=ly(o);i&&t.add(i)}};n(e);try{const r=JSON.parse(e),s=new Set;Lp(r,s);for(const o of s)n(o)}catch{}return Array.from(t)}function Xt(e){if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return n==="/"?"/":n.length>1?n.replace(/\/+$/,""):n}function kL(e,t){const n=e.replace(/\\/g,"/").trim(),r=(t||"").replace(/\\/g,"/").replace(/\/+$/,"");if(!r||n===r)return n;const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n}const ML=["CodeFiles","codefiles","application/vnd.code.tree","application/vnd.code.tree.explorer","text/uri-list","text/plain"],fr="__home__",IL="Don't work in a folder",EL=()=>"~",_L=e=>e.enabled&&e.isDraftOpen&&!!e.activeProjectId&&e.selectedProjectId!==fr&&e.selectedProjectId!==e.activeProjectId,jL=e=>{if(e.selectedProjectId===fr)return null;const t=e.selectedProjectId??e.activeProjectId,n=(t?e.projects.find(r=>r.id===t):null)??e.projects[0]??null;return n?za(n):null};function x3(e,t){const n=e.flatMap(o=>{const i={...o,id:o.id,ownerProjectId:o.id,kind:"project"},a=t.get(Xt(o.path)??o.path)??[];return[i,...a.map(l=>({id:`worktree:${o.id}:${l.path}`,ownerProjectId:o.id,kind:"worktree",path:l.path,branch:l.branch,label:l.branch||(l.detached?"Detached HEAD":l.name)}))]}),r=EL();return[{id:fr,ownerProjectId:fr,kind:"project",path:r,label:IL},...n]}const b3=Et()(gr(e=>({selectedSpaceId:null,selectedWorktreePath:null,selectSpace:t=>{e({selectedSpaceId:t,selectedWorktreePath:null})},selectWorktree:(t,n)=>{e({selectedSpaceId:t,selectedWorktreePath:n})},clearSpaceSelection:()=>{e({selectedSpaceId:null,selectedWorktreePath:null})},clearSelectedWorktree:()=>{e({selectedWorktreePath:null})}}),{name:"sidebar-space"}));function w3(e,t){if(e.length<=1)return null;const n=t?e.indexOf(t):-1;return e[(n+1)%e.length]??null}function Rp(e=1){const t=lt.getState(),n=t.projects;if(n.length<=1)return!1;const r=n.map(f=>f.id);let s=t.activeProjectId;if(!s||!r.includes(s)){const f=de(nt.getState().currentDirectory??null);s=dr(n,Zn(n,un.getState()),f)?.id??null}const o=e===1?w3(r,s):r[((s?r.indexOf(s):0)-1+r.length)%r.length]??null;if(!o)return!1;const i=n.find(f=>f.id===o),a=de(i?.path??null);if(!i||!a)return!1;t.setActiveProjectIdOnly(o),b3.getState().selectSpace(o),re.getState().closeMainSurfaces();const l=Zn(n,un.getState()),d=gw().find(f=>{const u=de(f.directory??null);return u?dr(n,l,u)?.id===o:!1});if(d){const f=de(d.directory??null);return he.getState().setCurrentSession(d.id,f),!0}return he.getState().openNewSessionDraft({selectedProjectId:o,directoryOverride:a}),!0}function TL(){const e=he.getState(),t=e.newSessionDraft;if(!t?.open)return!1;const n=lt.getState(),r=n.projects,s=x3(r,Zn(r,un.getState()));if(s.length<=1)return!1;const o=de(t.directoryOverride??null),i=t.selectedProjectId?s.find(f=>f.ownerProjectId===t.selectedProjectId&&(!o||de(f.path)===o))??s.find(f=>f.id===t.selectedProjectId)??(o?s.find(f=>de(f.path)===o)??null:null):o?s.find(f=>de(f.path)===o)??null:null,a=w3(s.map(f=>f.id),i?.id??null),l=s.find(f=>f.id===a),d=de(l?.path??null);return!l||!d?!1:l.ownerProjectId===fr?(e.setNewSessionDraftTarget({projectId:fr,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0):(n.activeProjectId!==l.ownerProjectId&&(n.setActiveProjectIdOnly(l.ownerProjectId),b3.getState().selectSpace(l.ownerProjectId)),e.setNewSessionDraftTarget({projectId:l.ownerProjectId,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0)}const AL=['[data-slot="dropdown-menu-content"][data-open]','[data-slot="select-content"][data-open]'].join(",");function NL(e=document){return!!e.querySelector(AL)}const LL=(e,t)=>!e.repeat&&Tt(e,t),RL=e=>{const t=he.getState().currentSessionId;t&&qe().prompt(t,aC(e),"prompt").catch(()=>{})},PL=()=>{const e=he(M=>M.openNewSessionDraft),t=he(M=>M.armAbortPrompt),n=he(M=>M.clearAbortPrompt),r=he(M=>M.currentSessionId),s=e1,o=re(M=>M.toggleCommandPalette),i=re(M=>M.toggleHelpDialog),a=re(M=>M.toggleSidebar),l=nt(M=>M.currentDirectory),d=Xn(),f=p.useCallback(()=>{l&&re.getState().openContextSurface(Ji(l),"terminal")},[l]),u=re(M=>M.isMobile),h=re(M=>M.setSessionSwitcherOpen),m=re(M=>M.setActiveMainTab),g=re(M=>M.setSettingsDialogOpen),x=re(M=>M.setModelSelectorOpen),b=re(M=>M.setTimelineDialogOpen),S=re(M=>M.setPromptNavigatorPanelOpen),y=re(M=>M.shortcutOverrides),v=nt(M=>M.currentDirectory),C=lt(M=>M.getActiveProject()),{themeMode:w,setThemeMode:I}=vr(),{phase:E}=h1(),T=p.useRef(null),A=p.useRef(null),j=p.useRef(w),k=p.useRef(new Set);p.useEffect(()=>{j.current=w},[w]);const _=p.useCallback(()=>{A.current&&(clearTimeout(A.current),A.current=null),T.current=null,n()},[n]);p.useEffect(()=>{const M=P=>iC(P,y),L=rC("switch_context_surface",y),O=['[data-slot="dropdown-menu-content"]','[data-slot="select-content"]','[role="combobox"]','[role="listbox"]','[role="menu"]','[role="menuitem"]','[role="option"]',"[data-radix-popper-content-wrapper]"].join(","),N=P=>P instanceof Element&&!!P.closest(O),D=P=>{if(qf(P.target)&&Tt(P,M("toggle_terminal"))){const{isMobile:q}=re.getState();if(q)return;P.preventDefault(),P.stopPropagation(),f();return}},W=P=>{if(P.key!=="Escape")return;const q=P.target,B=!!q?.closest('[role="dialog"]'),ee=!!document.querySelector('[data-settings-view="true"]'),G=qf(q),K=N(q)||NL(),{isSettingsDialogOpen:se,isCommandPaletteOpen:le,isHelpDialogOpen:oe,isSessionSwitcherOpen:ue,isImagePreviewOpen:ye,activeMainTab:we,isPromptNavigatorPanelOpen:Me}=re.getState();if(B||G||K){_();return}if(Me){P.preventDefault(),S(!1),_();return}if(se){P.preventDefault(),g(!1),_();return}if(ee){_();return}if(le||oe||ue||ye||!(we==="chat")){_();return}const Ge=r,et=!!(Ge&&qe().getState().reducer.bySession.get(Ge)?.bashExecutions?.some(Se=>Se.phase==="running"));if(E==="idle"&&!et||!Ge){_();return}const Xe=Date.now(),te=T.current;if(te&&Xe<te){P.preventDefault(),_(),et?Aw(Ge).catch(()=>{Ce.error("Failed to stop the shell command")}):s(Ge);return}P.preventDefault();const Q=t(3e3)??Xe+3e3;T.current=Q,A.current&&clearTimeout(A.current);const me=Math.max(Q-Xe,0);A.current=setTimeout(()=>{T.current&&Date.now()>=T.current&&_()},me||0)},z=P=>{if(P.key==="Escape"||qf(P.target))return;if(Tt(P,M("open_command_palette"))){P.preventDefault(),o();return}if(Tt(P,M("open_timeline_dialog"))){P.preventDefault(),b(!0);return}if(Tt(P,M("open_help"))){P.preventDefault(),i();return}if(sC()&&Tt(P,M("new_mini_chat"))){P.preventDefault(),lr("desktop_open_draft_mini_chat_window",{directory:v||C?.path||"",projectId:C?.id??null}).catch(G=>{console.warn("[keyboard-shortcuts] failed to open draft mini chat window",G)});return}if(Tt(P,M("new_chat"))){P.preventDefault(),m("chat"),h(!1),e();return}if(Tt(P,M("cycle_theme"))){P.preventDefault();const G=["light","dark","system"],K=document.activeElement,le=(G.indexOf(j.current)+1)%G.length;I(G[le]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),K&&document.contains(K)&&K.focus({preventScroll:!0}))});return}if(Tt(P,M("open_settings"))){P.preventDefault();const{isSettingsDialogOpen:G}=re.getState();g(!G);return}if(Tt(P,M("add_selection_to_chat"))){P.preventDefault(),y3();return}if(Tt(P,M("toggle_sidebar"))){P.preventDefault();const{isMobile:G,isSessionSwitcherOpen:K}=re.getState();G?h(!K):a();return}if(Tt(P,M("focus_input"))){P.preventDefault(),To();return}if(Tt(P,M("cycle_session_folder"))){if(!Rp())return;P.preventDefault();return}if(Tt(P,M("cycle_draft_folder"))){if(!TL())return;P.preventDefault();return}if(Tt(P,M("open_right_sidebar"))){const G=re.getState();if(G.isMobile||!v)return;P.preventDefault();const K=Ji(v),se=G.contextPanelByDirectory[K];if(se?.isOpen)return;se?.activeTabId?G.setActiveContextPanelTab(K,se.activeTabId):G.openContextSurface(K,"git");return}if(Tt(P,M("toggle_terminal"))){const{isMobile:G}=re.getState();if(G)return;P.preventDefault(),f();return}const B=P.key.length===1&&P.key>="0"&&P.key<="9"?P.key==="0"?10:Number(P.key):null;if(B!==null&&!P.repeat&&oC(P,L,k.current)){const G=re.getState();if(G.isMobile||!d)return;const K=Ji(d),se=G.contextPanelByDirectory[K];let le;const oe=Ua.getState().entriesByDirectory[K]??null;if(oe){const we=oe.scope?.repositories??[];le={isLoading:oe.isLoading,hasResult:!!(oe.scope||oe.error),hasGitHubRepo:we.some(Me=>!!(Me.host&&Me.owner&&Me.repo&&!Me.disabledReason)),hasError:!!(oe.error&&!oe.scope)}}const ye=eL({railOrder:G.contextRailOrder,tabs:se?.tabs??[],githubScope:le})[B-1];if(!ye)return;P.preventDefault(),G.openContextSurface(K,ye.mode);return}if(LL(P,M("open_model_selector"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:le,activeMainTab:oe,isModelSelectorOpen:ue}=re.getState();if(G||K||se||le||!(oe==="chat"))return;P.preventDefault(),x(!ue);return}if(Tt(P,M("cycle_thinking_variant"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:le,activeMainTab:oe}=re.getState();if(G||K||se||le||!(oe==="chat")||We.getState().getCurrentModelVariants().length===0)return;P.preventDefault(),iL(1).catch(()=>{Ce.error("Couldn't update thinking")});return}if(Tt(P,M("cycle_favorite_model_forward"))||Tt(P,M("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:le,activeMainTab:oe,favoriteModels:ue,addRecentModel:ye}=re.getState();if(G||K||se||le||!(oe==="chat")||ue.length===0)return;P.preventDefault();const{currentProviderId:He,currentModelId:Ae,setProvider:Ge,setModel:et}=We.getState(),Xe=ue.length,te=ue.findIndex(Se=>Se.providerID===He&&Se.modelID===Ae),Q=Tt(P,M("cycle_favorite_model_forward"))?1:-1,me=ue[(te+Q+Xe)%Xe];Ge(me.providerID),et(me.modelID),ye(me.providerID,me.modelID);return}const ee=re.getState().commandTriggers;if(ee.length>0&&!N(P.target)){for(const G of ee)if(!(!G.combo||!Tt(P,G.combo))){P.preventDefault(),P.stopPropagation(),RL(G);return}}},X=P=>{k.current.add(P.key.toLowerCase())},F=P=>{k.current.delete(P.key.toLowerCase())},U=()=>{k.current.clear()};return window.addEventListener("keydown",X,!0),window.addEventListener("keyup",F,!0),window.addEventListener("blur",U),window.addEventListener("keydown",D,!0),window.addEventListener("keydown",W,!0),window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",X,!0),window.removeEventListener("keyup",F,!0),window.removeEventListener("blur",U),window.removeEventListener("keydown",D,!0),window.removeEventListener("keydown",W,!0),window.removeEventListener("keydown",z)}},[e,s,o,i,a,f,u,h,m,g,x,b,S,I,E,t,_,r,v,d,C?.id,C?.path,y]),p.useEffect(()=>()=>{_()},[_])},DL=3,OL=(e,t)=>{if(typeof e!="string")return t;const n=e.trim().replace(/\s+/g," ");return n?n.slice(0,48):t},HL=(e,t)=>{const n=t?[...e.filter(o=>o.id===t),...e.filter(o=>o.id!==t)]:e,r=[],s=new Set;for(const o of n){const i=typeof o.id=="string"?o.id.trim():"";if(!(!i||s.has(i))&&(s.add(i),r.push({sessionId:i,title:OL(o.title,`Session ${r.length+1}`)}),r.length>=DL))break}return r},FL=()=>{const e=_w(),t=he(o=>o.currentSessionId),n=p.useMemo(()=>HL(e,t),[t,e]),r=p.useMemo(()=>JSON.stringify(n),[n]),s=n.length>0;p.useEffect(()=>{if(typeof window>"u"||!xm())return;try{s?localStorage.setItem(e0,r):localStorage.removeItem(e0)}catch{return}window.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[s,r])},BL=e=>{if(!e||typeof e!="object")return"unknown";const t=e;if(t.status==="accepted"){const n=t.receipt;return n?.accepted===!0&&typeof n.messageId=="string"?"accepted":"unknown"}return t.status==="pending"?"pending":t.status==="expired"?"expired":(t.status==="unknown","unknown")},VL=async(e,t)=>{try{const n=lC(e.runtimeKey);if(!t.streamEpoch||t.streamEpoch!==n)return"unknown";const r=await Ie.getSendReceipt({sessionId:e.sessionId,kind:t.kind,operationId:t.operationId,streamEpoch:t.streamEpoch},{directory:e.directory,runtimeKey:e.runtimeKey});return BL(r)}catch{return"unknown"}},S3=e=>e instanceof cC,$L=2e3,Er="hydrate-demand",C3=2e3,zL=6e4,UL=e=>Math.min(C3*2**Math.max(e-1,0),zL),dy=(e,t,n)=>e!==void 0&&e.messageId===t&&n<e.nextAttemptAt,qL=(e,t=Date.now,n=setTimeout,r=clearTimeout)=>{let s=null,o=null;return{schedule(i){o!==null&&o<=i||(s!==null&&r(s),o=i,s=n(()=>{s=null,o=null,e()},Math.max(0,i-t())))},dispose(){s!==null&&r(s),s=null,o=null}}},WL=e=>{const t=he.getState().sessionAbortFlags.get(e);if(!t)return null;const n=t.timestamp+$L;return Date.now()<n?n:null},KL=e=>{const t=e[0];return t?{queuedMessageId:t.id,primaryText:t.content,primaryAttachments:t.attachments??[],agentMentionName:void 0,sendConfig:t.sendConfig}:null},GL=(e,t,n,r)=>he.getState().sendMessage(t.primaryText,n.providerID,n.modelID,n.agent,t.primaryAttachments,t.agentMentionName,void 0,n.variant,"normal",{target:e,delivery:"followUp",operationId:t.queuedMessageId,...r?{streamEpoch:r}:{}}),ZL=e=>{const t=We.getState(),n=Lt.getState(),r=n.getSessionAgentSelection(e)??void 0,s=n.getSessionModelSelection(e),o=r?n.getAgentModelForSession(e,r):null,i=o?.providerId??s?.providerId??t.currentProviderId??n.lastUsedProvider?.providerID,a=o?.modelId??s?.modelId??t.currentModelId??n.lastUsedProvider?.modelID,l=r&&i&&a?n.getAgentModelVariantForSession(e,r,i,a):void 0;return{providerID:i,modelID:a,agent:r,variant:l}},YL=(e,t)=>{if(e.connection!=="ready")return"unknown";const n=e.catalog.byId.get(t.sessionId);return!n||de(n.directory)!==de(t.directory)||n.archived?"unknown":n.lifecycle==="busy"||n.lifecycle==="retry"?"busy":n.hydrated?"ready":"unknown"};function XL(e){const t=typeof e=="boolean"?e:e?.enabled??!0,n=ft(h=>h.queuedMessages),r=nt(h=>h.currentDirectory),s=Ha(),o=ze(h=>h.catalog,void 0,yt),i=ze(h=>h.connection,void 0,At),a=p.useRef(new Set),l=p.useRef(new Map),[d,f]=p.useState(0),u=p.useMemo(()=>qL(()=>f(h=>h+1)),[]);p.useEffect(()=>()=>u.dispose(),[u]),p.useEffect(()=>{if(!t)return;const h=ft.getState().queuedMessages;for(const[S,y]of l.current)y.messageId===Er&&!(S in h)&&l.current.delete(S);const m=S=>{l.current.get(S)?.messageId===Er&&l.current.delete(S)},g=async(S,y,v)=>{const C=s.getState();if(C.connection!=="ready")return;const w=C.catalog.byId.get(y);if(!w||w.archived||de(w.directory)!==de(S.directory))return;const I=l.current.get(v);if(I?.messageId===Er&&dy(I,Er,Date.now())){u.schedule(I.nextAttemptAt);return}if(a.current.has(v))return;a.current.add(v);try{await s.ensureHydrated(y)}finally{a.current.delete(v),f(_=>_+1)}const E=s.getState();if(s.isDeleted(y)||!E.catalog.byId.has(y)){m(v);return}if(E.catalog.byId.get(y)?.hydrated){m(v);return}const j=(I?.messageId===Er?I.failures:0)+1,k=Date.now()+UL(j);l.current.set(v,{messageId:Er,failures:j,nextAttemptAt:k}),u.schedule(k)},x=async(S,y)=>{const{sessionId:v}=S,C=L5(S);if(y.length===0||S.runtimeKey!==Y()||a.current.has(C))return;const w=WL(v);if(w!==null){u.schedule(w);return}const I=s.getState(),E=YL(I,S);if(E==="busy")return;if(E==="unknown"){await g(S,v,C);return}const T=ft.getState().getAutoSendCandidate(S);if(!T)return;const A=l.current.get(C);if(A&&A.messageId!==T.id&&A.messageId!==Er)l.current.delete(C);else if(A&&A.messageId!==Er&&dy(A,T.id,Date.now())){Number.isFinite(A.nextAttemptAt)&&u.schedule(A.nextAttemptAt);return}const j=ft.getState().claimQueuedMessage(S,T.id);if(!j)return;const k=KL([j]);if(!k){ft.getState().clearSending(S,j.id);return}const _=k.sendConfig,M=_?.providerID&&_?.modelID?_:ZL(v);if(!M.providerID||!M.modelID){ft.getState().clearSending(S,j.id),u.schedule(Date.now()+C3);return}a.current.add(C);const L=ft.getState().markDeliveryAttempt(S,j.id,"followUp");if(!L?.streamEpoch){a.current.delete(C),ft.getState().clearSending(S,j.id);return}try{await GL(S,k,{providerID:M.providerID,modelID:M.modelID,agent:M.agent,variant:M.variant},L.streamEpoch),ft.getState().completeQueuedSend(S,k.queuedMessageId),l.current.delete(C)}catch(O){console.warn("[follow-up] auto-send failed:",O);const N=A?.messageId===k.queuedMessageId?A.failures:0;l.current.set(C,{messageId:k.queuedMessageId,failures:N+1,nextAttemptAt:Number.POSITIVE_INFINITY}),S3(O)?(ft.getState().markSendUnconfirmed(S,k.queuedMessageId,"followUp"),Ce.error("Follow-up status uncertain. Check status before retrying.",{id:`follow-up-unconfirmed:${C}:${k.queuedMessageId}`})):(ft.getState().markSendFailed(S,k.queuedMessageId),Ce.error("Follow-up message failed to send. Use Send now to retry.",{id:`follow-up-failed:${C}:${k.queuedMessageId}`}))}finally{a.current.delete(C),ft.getState().clearSending(S,k.queuedMessageId)}};Object.entries(n).forEach(([S,y])=>{const v=dC(S);!v||v.runtimeKey!==Y()||v.directory!==r||y.length!==0&&x(v,y)})},[t,n,r,o,i,d,u,s])}const k3=1440*60*1e3,JL=(e,t,n)=>{const r={...e};return Object.hasOwn(t,"snoozedUntil")&&(delete r.snoozedUntil,delete r.snoozedAt,typeof t.snoozedUntil=="number"&&(r.snoozedUntil=t.snoozedUntil,r.snoozedAt=n)),Object.keys(r).length>0?r:void 0},QL=(e,t,n)=>typeof e?.snoozedUntil=="number"&&e.snoozedUntil>t&&!n,eR=(e,t)=>typeof e?.snoozedUntil=="number"&&e.snoozedUntil<=t,tR=e=>{const t=eR(e.entry,e.now)?e.entry.snoozedUntil:0;return Math.max(e.updatedAt,t)},nR=(e,t)=>{if(!(t>0)||e.open||e.pinned||e.working||e.needsInput||typeof e.entry?.snoozedUntil=="number"&&e.entry.snoozedUntil>e.now)return!1;const n=tR(e);return n>0?n<e.now-t*k3:!1},zJ=e=>QL(e.entry,e.now,e.needsInput)?"snoozed":e.pinned?"pinned":e.workingShelf&&e.working&&!e.needsInput?"working":"active",UJ=(e,t)=>{let n=null;for(const r of Object.values(e)){const s=r.snoozedUntil;typeof s=="number"&&s>t&&(n===null||s<n)&&(n=s)}return n},rR=[{kind:"after",minutes:60},{kind:"after",minutes:180},{kind:"at",day:"today",time:"18:00"},{kind:"at",day:"tomorrow",time:"09:00"},{kind:"at",day:"monday",time:"09:00"}],Gf=(e,t)=>`${e} ${t}${e===1?"":"s"}`,sR=e=>e%1440===0?Gf(e/1440,"day"):e%60===0?Gf(e/60,"hour"):Gf(e,"minute"),M3=e=>e.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),oR=(e,t)=>e==="today"?0:e==="tomorrow"?1:(1-t.getDay()+7)%7||7,iR=(e,t)=>{if(e.kind==="after")return`In ${sR(e.minutes)}`;if(t===0){const n=Number(e.time.slice(0,2));return n<12?"This morning":n<17?"This afternoon":"This evening"}return t===1?"Tomorrow":"Next week"},aR=(e,t)=>{let n,r=0;if(e.kind==="after")n=new Date(t.getTime()+e.minutes*6e4);else if(r=oR(e.day,t),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()+r),n.setHours(Number(e.time.slice(0,2)),Number(e.time.slice(3)),0,0),n.getTime()<=t.getTime())return null;const s=iR(e,r),o=e.kind==="at"&&s!=="Next week",i=M3(n);return{id:e.kind==="after"?`after:${e.minutes}`:`at:${e.day}:${e.time}`,label:s,whenLabel:o||n.toDateString()===t.toDateString()?i:`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`,snoozedUntil:n.getTime()}},qJ=e=>{const t=new Set;return rR.flatMap(n=>aR(n,e)??[]).sort((n,r)=>n.snoozedUntil-r.snoozedUntil).filter(n=>{const r=Math.floor(n.snoozedUntil/6e4);return t.has(r)?!1:(t.add(r),!0)})},WJ=(e,t)=>{const n=new Date(e),r=new Date(t),s=M3(n);return n.toDateString()===r.toDateString()?s:e-t<6*k3?n.toLocaleDateString(void 0,{weekday:"short"}):n.toLocaleDateString(void 0,{month:"short",day:"numeric"})};let uy=0;const Bi=new Map;let Hl=0;const Zf=(e,t,n)=>{const r={...e};return n?r[t]=n:delete r[t],r},fy=e=>{Bi.clear(),Hl+=1,No.setState({runtimeKey:e,entries:{},status:"idle"})},No=Et((e,t)=>({runtimeKey:null,entries:{},status:"idle",load:async()=>{const n=Y();t().runtimeKey!==n&&fy(n);const r=++Hl,s=uy;t().status!=="ready"&&e({status:"loading"});try{const{sessions:o}=await Ie.getSessionShelf({runtimeKey:n});if(r!==Hl||Y()!==n)return;const i=t().entries,a={...o};for(const[l,d]of Bi)d<=s||(i[l]?a[l]=i[l]:delete a[l]);e({entries:a,status:"ready"})}catch(o){if(r!==Hl||Y()!==n)return;e({status:"failed"}),console.warn("[session-shelf] could not read the session shelf",o)}},update:async(n,r,s)=>{const o=Y();t().runtimeKey!==o&&fy(o);const i=t().entries[n],a=++uy;Bi.set(n,a),e({entries:Zf(t().entries,n,JL(i,r,Date.now()))});try{const l=await Ie.setSessionShelf({sessionId:n,...r},{runtimeKey:o,...s?{directory:s}:{}});if(Y()!==o||Bi.get(n)!==a)return;e({entries:Zf(t().entries,n,l)})}catch(l){throw Y()===o&&Bi.get(n)===a&&e({entries:Zf(t().entries,n,i)}),l}}})),cR=1440*60*1e3,lR=3600*1e3,dR=1e4,I3=(e,t)=>e.archived?!1:nR({entry:t.shelfEntries[e.id],pinned:cd(t.pinnedIds,e.directory,e.id),working:e.lifecycle==="busy"||e.lifecycle==="retry",needsInput:e.pendingInput!=null,updatedAt:e.updatedAt,now:t.now,open:e.id===t.currentSessionId},t.archiveDays),E3=(e,t)=>!(t.deleteDays>0)||!e.archived||e.id===t.currentSessionId||typeof e.archivedAt!="number"||!(e.archivedAt>0)?!1:e.archivedAt<t.now-t.deleteDays*cR,uR=(e,t)=>{const n=[],r=[];for(const s of e)I3(s,t)?n.push(s.id):E3(s,t)&&r.push(s.id);return{archive:n,delete:r}},fR=(e,t,n)=>{const r=[],s=[];for(const o of e){const i=t.get(o),a=i?r1(i):null;a&&n.has(a)?r.push(o):s.push(o)}return{actionable:r,unready:s}},hR=()=>{try{const e=qe();return{store:e,runtimeKey:Y(),generation:e.getRuntimeGeneration()}}catch{return null}},Pp=e=>{try{const t=qe();return t!==e.store||Y()!==e.runtimeKey?!1:t.getRuntimeGeneration()===e.generation}catch{return!1}},_3=()=>{const e=re.getState();return{archiveDays:e.sessionAutoArchiveAfterDays??0,deleteDays:e.sessionAutoDeleteAfterDays??0}},Dp=(e,t)=>{const n=No.getState();return{..._3(),currentSessionId:he.getState().currentSessionId??null,pinnedIds:Pm.getState().ids,shelfEntries:n.entries,shelfReady:n.status==="ready"&&n.runtimeKey===e.runtimeKey,now:t}};let Yf=!1;const rr=()=>({completedIds:[],failedIds:[],skippedReason:"disabled"}),hs=()=>({completedIds:[],failedIds:[],skippedReason:"partial"}),Xf=()=>({completedIds:[],failedIds:[],skippedReason:"stale"}),pR={isCandidate:(e,t)=>t.shelfReady&&I3(e,t),write:(e,t,n)=>e.archive(t,!0,n)},mR={isCandidate:(e,t)=>E3(e,t),write:(e,t,n)=>e.remove(t,n)},hy=async(e,t,n,r,s,o)=>{let i,a;try{const h=Dp(t,o);i=[],a=new Map;for(const m of n.byId.values())e.isCandidate(m,h)&&(i.push(m.id),a.set(m.id,Ls(m)))}catch{return hs()}const{actionable:l,unready:d}=fR(i,a,r),f=[],u=[...d];for(let h=0;h<l.length;h+=1){const m=l[h];if(!Pp(t))return u.push(...l.slice(h)),{completedIds:f,failedIds:u,skippedReason:"stale"};let g=null;try{const x=Dp(t,o),b=qe().getState().catalog,S=b.byId.get(m);if(S&&e.isCandidate(S,x)){const y=r1(Ls(S));y&&b.listStatusByDirectory.get(y)==="ready"&&(g=y)}}catch{g=null}if(!g){u.push(m);continue}try{await e.write(qe(),m,g)}catch{u.push(m);continue}if(!Pp(t))return u.push(m,...l.slice(h+1)),{completedIds:f,failedIds:u,skippedReason:"stale"};f.push(m)}return s||u.length>0?{completedIds:f,failedIds:u,skippedReason:"partial"}:{completedIds:f,failedIds:u}},gR=(e,t)=>{const n=[e.skippedReason,t.skippedReason];if(n.includes("stale"))return"stale";if(n.includes("partial"))return"partial";if(n.every(r=>r==="disabled"))return"disabled"},py=async({now:e}={})=>{if(Yf)return{archive:rr(),delete:rr(),skippedReason:"running"};let t;try{t=_3()}catch{return{archive:hs(),delete:hs(),skippedReason:"partial"}}const n=t.archiveDays>0,r=t.deleteDays>0;if(!n&&!r)return{archive:rr(),delete:rr(),skippedReason:"disabled"};const s=(l,d)=>({archive:l,delete:d,skippedReason:gR(l,d)}),o=l=>s(n?l():rr(),r?l():rr()),i=hR();if(!i)return o(Xf);const a=e??Date.now();Yf=!0;try{let l;try{const h=n?No.getState().load():Promise.resolve();[l]=await Promise.all([$N(),h])}catch{return o(hs)}if(l.stale||!Pp(i))return o(Xf);if(l.readyDirectories.size===0)return o(hs);const d=l.failedDirectories.size>0;let f=rr();if(n&&(f=Dp(i,a).shelfReady?await hy(pR,i,l.catalog,l.readyDirectories,d,a):hs(),f.skippedReason==="stale"))return s(f,r?Xf():rr());let u=rr();return r&&(u=await hy(mR,i,qe().getState().catalog,l.readyDirectories,d,a)),s(f,u)}catch{return o(hs)}finally{Yf=!1}},yR=new Map,vR={archive:[],delete:[]},xR=e=>{const t=typeof e=="object"?e:void 0,n=t?.autoRun!==!1,r=typeof e=="boolean"?e:t?.enabled??!0,s=r&&!n,o=re(S=>S.sessionAutoArchiveAfterDays),i=re(S=>S.sessionAutoDeleteAfterDays),a=he(S=>S.currentSessionId),l=Pm(S=>S.ids),d=No(S=>S.entries),f=No(S=>S.status==="ready"&&S.runtimeKey===Y()),u=ze(S=>s?S.catalog.byId:yR,void 0,"catalog");p.useEffect(()=>{s&&No.getState().load()},[s]);const h=p.useMemo(()=>{if(!s)return vR;const S=uR(u.values(),{archiveDays:o,deleteDays:i,currentSessionId:a??null,pinnedIds:l,shelfEntries:d,now:Date.now()});return f?S:{...S,archive:[]}},[s,f,u,o,i,a,l,d]),[m,g]=p.useState(!1),x=p.useCallback(async()=>{g(!0);try{return await py()}finally{g(!1)}},[]),b=r&&n&&(o>0||i>0);return p.useEffect(()=>{if(!b)return;const S=()=>{py()},y=window.setTimeout(S,dR),v=window.setInterval(S,lR);return()=>{window.clearTimeout(y),window.clearInterval(v)}},[b]),{archiveCandidates:h.archive,deleteCandidates:h.delete,isRunning:m,runCleanup:x}},Jf=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:"0px",Qf=(e,t,n)=>{const r=e.style.getPropertyValue(t);r===n||!r&&n==="0px"||e.style.setProperty(t,n)},eh=(e,t,n,r)=>{Qf(e,"--oc-wco-left-inset",Jf(t)),Qf(e,"--oc-wco-right-inset",Jf(n)),Qf(e,"--oc-wco-titlebar-height",Jf(r))},bR=()=>{p.useEffect(()=>{if(typeof window>"u"||!xm())return;const e=document.documentElement,t=typeof window.matchMedia=="function"?window.matchMedia("(display-mode: window-controls-overlay)"):null,r=window.navigator.windowControlsOverlay,s=()=>{if(!r||!t?.matches||!r.visible){eh(e,0,0,0);return}const i=r.getTitlebarAreaRect(),a=Math.max(0,Number(i.x)||0),l=Math.max(0,Number(i.width)||0),d=Math.max(0,Number(i.height)||0),f=Math.max(0,window.innerWidth-(a+l));eh(e,a,f,d)},o=()=>{s()};return s(),window.addEventListener("resize",s),window.addEventListener("focus",s),t&&(typeof t.addEventListener=="function"?t.addEventListener("change",o):typeof t.addListener=="function"&&t.addListener(o)),r&&typeof r.addEventListener=="function"&&r.addEventListener("geometrychange",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("focus",s),t&&(typeof t.removeEventListener=="function"?t.removeEventListener("change",o):typeof t.removeListener=="function"&&t.removeListener(o)),r&&typeof r.removeEventListener=="function"&&r.removeEventListener("geometrychange",s),eh(e,0,0,0)}},[])},wR=()=>{};async function SR(e,t){if(!e?.listen)return wR;const n=[];try{n.push(await e.listen("pichamber:menu-action",r=>{typeof r.payload=="string"&&t.onAction(r.payload)})),n.push(await e.listen("pichamber:check-for-updates",()=>{t.onCheckForUpdates()})),n.push(await e.listen("pichamber:open-mini-chat",()=>{t.onOpenMiniChat?.()}))}catch(r){for(const s of n)s();throw r}return()=>{for(const r of n)r()}}const Xc=e=>{const t=re.getState();e&&t.setSettingsPage(e),t.setSettingsDialogOpen(!0)},my=e=>{const t=gw();if(t.length<2)return;const n=he.getState(),r=t.findIndex(i=>i.id===n.currentSessionId),s=r<0?e===1?-1:0:r,o=t[(s+e+t.length)%t.length];o&&n.setCurrentSession(o.id,r1(o))};function CR(){const{setThemeMode:e}=vr(),t=p.useCallback(s=>{const o=re.getState();switch(s){case"about":Xc("about");return;case"settings":Xc();return;case"command-palette":o.setCommandPaletteOpen(!0);return;case"new-session":o.setActiveMainTab("chat"),o.setSessionSwitcherOpen(!1),he.getState().openNewSessionDraft();return;case"change-workspace":Cu.requestDirectoryDialog();return;case"add-selection-to-chat":y3();return;case"open-right-sidebar":{const i=nt.getState().currentDirectory;if(!i)return;const a=Ji(i),l=o.contextPanelByDirectory[a];if(l?.isOpen)return;l?.activeTabId?o.setActiveContextPanelTab(a,l.activeTabId):o.openContextSurface(a,"git");return}case"toggle-terminal":{const i=nt.getState().currentDirectory;i&&o.openContextSurface(Ji(i),"terminal");return}case"theme-light":e("light");return;case"theme-dark":e("dark");return;case"theme-system":e("system");return;case"toggle-sidebar":o.isMobile?o.setSessionSwitcherOpen(!o.isSessionSwitcherOpen):o.toggleSidebar();return;case"toggle-memory-debug":Yl(!Xo());return;case"go-back":window.history.back();return;case"go-forward":window.history.forward();return;case"previous-session":my(-1);return;case"next-session":my(1);return;case"previous-project":Rp(-1);return;case"next-project":Rp(1);return;case"help-dialog":o.setHelpDialogOpen(!0);return;case"download-logs":Xc("general"),Yl(!0);return;case"copy":return;default:return}},[e]),n=p.useCallback(()=>{Xc("about"),Mp.getState().checkForUpdates()},[]),r=p.useCallback(()=>{const s=lt.getState().getActiveProject();lr("desktop_open_draft_mini_chat_window",{directory:nt.getState().currentDirectory||s?.path||"",projectId:s?.id??null}).catch(o=>{console.warn("[desktop-menu] failed to open draft mini chat window",o)})},[]);p.useEffect(()=>{if(!Vr())return;let s=!1,o=()=>{};return SR(uC(),{onAction:t,onCheckForUpdates:n,onOpenMiniChat:r}).then(i=>{s?i():o=i}).catch(i=>{console.warn("[desktop-menu] failed to subscribe to application menu events",i)}),()=>{s=!0,o()}},[t,n,r])}const kR=()=>{const e=lt.getState().projects,t=Zn(e,un.getState()),n=[...u3(e,t,{includeWorktrees:!0})];try{const r=[nt.getState().homeDirectory,Gt().getItem("homeDirectory"),typeof window<"u"&&Yr()?window.__PICHAMBER_HOME__:null],s=new Set(n.map(o=>de(o)?.toLowerCase()??o));for(const o of r){if(!o)continue;const i=de(o);if(!i)continue;const a=i.toLowerCase();s.has(a)||(s.add(a),n.push(i))}}catch{}return n},MR=e=>e.length===0?"":[...e].sort().join("|"),IR=()=>(H.useEffect(()=>{let e=!1,t="";const n=qe(),r=()=>{if(e)return;const l=kR();if(l.length===0)return;const d=MR(l);if(d===t)return;const f=n.getState();if(f.connection!=="ready"||f.sessionsListStatus==="loading"||f.selectedSessionId&&f.focusPending&&f.sessionsListStatus!=="failed")return;const u=l.filter(h=>{const m=n.getState().catalog.listStatusByDirectory.get(h);return m!=="ready"&&m!=="loading"});if(u.length===0){t=d;return}t=d,n.refreshAllDirectoryCatalogs(u)};r();const s=lt.subscribe(r),o=un.subscribe(r),i=nt.subscribe((l,d)=>{l.homeDirectory&&l.homeDirectory!==d.homeDirectory&&r()}),a=n.subscribe(r,"chrome");return()=>{e=!0,s(),o(),i(),a()}},[]),null),qa=()=>{const e=p.useContext($a);if(!e)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return e},ER=6e4,_R=2,jR=()=>{const e=lt(l=>l.projects),t=un(l=>l.refreshProject),{git:n}=qa(),r=p.useMemo(()=>e.map(l=>l.path).filter(l=>!!l),[e]),s=p.useMemo(()=>[...r].sort().join("\0"),[r]),o=Y(),i=p.useCallback(async()=>{if(!n||r.length===0)return;let l=0;const d=async()=>{for(;l<r.length;){const f=r[l];l+=1,await t(f,n)}};await Promise.all(Array.from({length:Math.min(_R,r.length)},()=>d()))},[n,r,t]),a=p.useRef(null);return p.useEffect(()=>{const l=`${o}\0${s}`;a.current!==l&&(a.current=l,i())},[o,s,i]),p.useEffect(()=>{const l=()=>{i()},d=()=>{document.visibilityState==="visible"&&i()};window.addEventListener("focus",l),document.addEventListener("visibilitychange",d);const f=window.setInterval(()=>{document.visibilityState==="visible"&&i()},ER);return()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",d),window.clearInterval(f)}},[i]),null},gy=2e3,TR=3e4,AR=2;class NR{constructor(t){this.options=t}options;timer=null;currentDelayMs=gy;inFlight=!1;disposed=!1;get isRunning(){return this.inFlight||this.timer!==null}get currentBackoffDelayMs(){return this.currentDelayMs}isMismatched(){return this.options.getConnection()==="ready"&&(!this.options.getIsInitialized()||!this.options.getIsConnected())}isHidden(){return this.options.isDocumentHidden?this.options.isDocumentHidden():typeof document<"u"&&document.visibilityState==="hidden"}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}resetDelay(){this.currentDelayMs=gy}reconcile(){this.check(!1)}wake(){this.check(!0)}check(t){if(!this.disposed){if(!this.isMismatched()){this.clearTimer(),this.resetDelay();return}if(this.isHidden()){this.clearTimer();return}!t&&(this.inFlight||this.timer!==null)||this.executeAttempt()}}resetForRuntimeSwitch(){this.clearTimer(),this.resetDelay()}dispose(){this.disposed=!0,this.clearTimer()}async executeAttempt(){if(this.clearTimer(),this.disposed||this.inFlight)return;if(!this.isMismatched()){this.resetDelay();return}if(this.isHidden())return;this.inFlight=!0,Rr("config-reconcile",{code:"attempt"});try{await this.options.initializeApp()}catch{}finally{this.inFlight=!1}if(this.disposed)return;if(!this.isMismatched()){Rr("config-reconcile",{code:"success"}),this.resetDelay();return}if(Rr("config-reconcile",{code:"failure"}),this.isHidden())return;const t=this.currentDelayMs;this.currentDelayMs=Math.min(t*AR,TR),this.timer=setTimeout(()=>{this.timer=null,this.executeAttempt()},t)}}function LR({connection:e,isInitialized:t,isConnected:n,initializeApp:r}){const s=p.useRef({connection:e,isInitialized:t,isConnected:n,initializeApp:r});s.current={connection:e,isInitialized:t,isConnected:n,initializeApp:r};const o=p.useRef(null);p.useEffect(()=>{o.current?.reconcile()},[e,t,n]),p.useEffect(()=>{const i=new NR({getConnection:()=>s.current.connection,getIsInitialized:()=>s.current.isInitialized,getIsConnected:()=>s.current.isConnected,initializeApp:()=>s.current.initializeApp()});o.current=i,i.reconcile();const a=()=>{typeof document<"u"&&document.visibilityState==="visible"?i.wake():i.reconcile()},l=()=>{i.wake()};typeof document<"u"&&document.addEventListener("visibilitychange",a),typeof window<"u"&&window.addEventListener("online",l);const d=Zt(()=>{i.resetForRuntimeSwitch(),i.reconcile()});return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",a),typeof window<"u"&&window.removeEventListener("online",l),d(),i.dispose(),o.current===i&&(o.current=null)}},[])}const RR="pichamber:mini-chat-presence",PR=()=>(p.useEffect(()=>{if(typeof BroadcastChannel>"u")return;const e=new BroadcastChannel(RR);return e.onmessage=t=>{const n=t.data;if(n?.type!=="mini-chat-session-presence"||!n.sessionId||!n.directory)return;n.viewed!==!1&&nu(n.sessionId)},()=>e.close()},[]),null);function DR({embeddedBackgroundWorkEnabled:e}){return xR(e),XL(e),c.jsx(IR,{})}const OR=()=>{const e=p.useMemo(()=>qe(),[]),t=p.useMemo(()=>a=>e.subscribe(a,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),{selectedSessionId:r,directory:s,connection:o,focusPending:i}=n;return p.useEffect(()=>{if(!s||de(e.getState().directory)!==de(s))return;const a=nt.getState().currentDirectory;de(a)!==de(s)&&nt.getState().setDirectory(s,{showOverlay:!1}),We.getState().activateDirectory(s)},[s,e]),p.useEffect(()=>{const a=he.getState();if(!r||!s){if(o==="loading"||i)return;(a.currentSessionId!==null||a.currentSessionDirectory!==null)&&he.setState({currentSessionId:null,currentSessionDirectory:null});return}if(!i&&!Xm(a.newSessionDraft,a.currentSessionId)&&(a.currentSessionId!==r||a.currentSessionDirectory!==s)){const l=a.newSessionDraft?.open?{newSessionDraft:{id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0}}:{};he.setState({currentSessionId:r,currentSessionDirectory:s,...l}),nu(r)}},[r,s,o,i]),null},HR=()=>{const e=p.useMemo(()=>qe(),[]),t=p.useMemo(()=>l=>e.subscribe(l,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),r=We(l=>l.initializeApp),s=We(l=>l.isInitialized),o=We(l=>l.isConnected),i=We(l=>l.loadProviders),a=We(l=>l.providers.length);return LR({connection:n.connection,isInitialized:s,isConnected:o,initializeApp:r}),p.useEffect(()=>{!n.directory||n.connection!=="ready"||!o||a===0&&i({source:"webApp:recovery"})},[o,i,n.connection,n.directory,a]),null};function KJ({embeddedBackgroundWorkEnabled:e}){return FL(),bR(),PL(),CR(),c.jsxs(c.Fragment,{children:[c.jsx(HR,{}),c.jsx(DR,{embeddedBackgroundWorkEnabled:e}),c.jsx(OR,{}),c.jsx(PR,{}),c.jsx(jR,{})]})}const j3=({text:e})=>c.jsx("span",{"aria-hidden":"true",className:"oc-shimmer-clip",children:c.jsx("span",{className:"oc-shimmer-band","data-shimmer-text":e})}),FR=Array.from({length:9},(e,t)=>{const n=Math.floor(t/3);return(t%3+Math.abs(n-1))*90}),BR=650;function th({compact:e=!1}){return c.jsx("span",{"aria-hidden":"true",className:e?"grid shrink-0 grid-cols-[repeat(3,3px)] gap-[1px]":"grid shrink-0 grid-cols-[repeat(3,4px)] gap-[1.5px]",children:FR.map((t,n)=>c.jsx("span",{className:e?"pixel-loader-cell size-[3px] rounded-full bg-current":"pixel-loader-cell size-[4px] rounded-full bg-current",style:{opacity:.15,animation:`pixel-on ${BR}ms ease-in-out ${t}ms infinite`}},n))})}function VR(e,t){const[n,r]=p.useState(0),[s]=p.useState(()=>Date.now());if(p.useEffect(()=>{if(!e||t===null)return;const a=setInterval(()=>r(l=>l+1),100);return()=>clearInterval(a)},[e,t]),!e||t===null)return null;const o=t??s,i=Math.max(0,(Date.now()-o)/1e3);return i<60?`${i.toFixed(1)}s`:`${Math.floor(i/60)}m ${(i%60).toFixed(1)}s`}const yy=({text:e="Thinking",className:t,variant:n="inline",showText:r=!0,showElapsed:s=!0,animateText:o=!1,startedAt:i})=>{const a=r&&e!=null&&e!=="",l=VR(a&&s,i),d=a?c.jsxs("span",{className:R("pixel-loader-label min-w-0 truncate whitespace-nowrap typography-markdown font-medium",o&&"agent-thinking-label-enter"),children:[e,c.jsx(j3,{text:e})]},o?e:void 0):null,f=a&&s&&l!==null?c.jsx("span",{className:"shrink-0 whitespace-nowrap font-mono typography-code text-muted-foreground tabular-nums",children:l}):null;return n==="badge"?c.jsxs("span",{className:R("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-normal","bg-primary/10 text-primary border border-primary/20","transition-opacity duration-300",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]}):n==="full"?c.jsxs("div",{className:R("flex items-center gap-2.5 rounded-lg border border-primary/25 bg-primary/5 px-3 py-1.5 text-sm text-foreground",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]}):c.jsxs("span",{className:R("inline-flex min-w-0 items-center gap-2.5",t),role:"status","aria-live":"polite",children:[c.jsx(th,{compact:!a}),d,f]})},vy="pichamber:chunk-import-reload",$R=250,zR=3e4,UR=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function T3(e){if(e instanceof Error)return`${e.name}
63
- ${e.message}
64
- ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function xy(e){const t=T3(e);return UR.some(n=>n.test(t))}function qR(e){return`1.0.7:${T3(e).slice(0,500)}`}function WR(e){if(typeof window>"u")return;const t=Date.now(),n=qR(e);let r=null;try{const o=window.sessionStorage.getItem(vy);if(o)try{r=JSON.parse(o)}catch{r=null}}catch{return}const s=typeof r?.timestamp=="number"?r.timestamp:0;if(!(r?.signature===n&&t-s<zR)){try{window.sessionStorage.setItem(vy,JSON.stringify({signature:n,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function KR(e,t={}){const n=t.retries??1;let r;for(let s=0;s<=n;s+=1)try{return await e()}catch(o){if(r=o,!xy(o)||s>=n)break;await new Promise(i=>setTimeout(i,$R*(s+1)))}throw xy(r)&&WR(r),r}const Fs=e=>H.lazy(()=>KR(e)),GR=Fs(()=>s1().then(e=>({default:e.MarkdownRenderer}))),ZR=Fs(()=>s1().then(e=>({default:e.SimpleMarkdownRenderer}))),YR=c.jsx("div",{className:"break-words w-full min-w-0"}),XR=e=>e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",A3=e=>!dn()||typeof e.content!="string"||e.content.length===0?YR:c.jsx("div",{className:R("break-words w-full min-w-0 whitespace-pre-wrap",XR(e.variant),typeof e.className=="string"?e.className:void 0),children:e.content}),qo=e=>c.jsx(p.Suspense,{fallback:c.jsx(A3,{...e}),children:c.jsx(GR,{...e})}),Wa=e=>c.jsx(p.Suspense,{fallback:c.jsx(A3,{...e}),children:c.jsx(ZR,{...e})}),JR=D5(["border-input flex items-center justify-between gap-2 rounded-md border bg-transparent","typography-ui-label whitespace-nowrap shadow-none outline-none text-left","hover:bg-interactive-hover data-[popup-open]:bg-interactive-active","focus-visible:outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","disabled:cursor-not-allowed disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='text-'])]:text-muted-foreground"].join(" "),{variants:{size:{sm:"h-6 min-h-6 px-2 [&_svg:not([class*='size-'])]:size-3.5",default:"h-8 min-h-8 px-3 [&_svg:not([class*='size-'])]:size-4"}},defaultVariants:{size:"default"}}),w1=H.createContext(null),QR=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function by({onValueChange:e,modal:t=!1,...n}){const[r,s]=H.useState(null),o=H.useMemo(()=>({portalContainer:r,setPortalContainer:s}),[r]),i=H.useCallback((a,l)=>{typeof a=="string"&&e?.(a,l)},[e]);return c.jsx(w1.Provider,{value:o,children:c.jsx(l8,{...n,modal:t,onValueChange:i})})}function eP({...e}){return c.jsx(x8,{"data-slot":"select-group",...e})}function wy({placeholder:e,children:t,...n}){return c.jsx(f8,{"data-slot":"select-value",...n,children:r=>{const s=typeof r=="string"||r===void 0?r:r===null?void 0:String(r);return typeof t=="function"?t(s):t??(s===void 0||s===""?e:s)}})}function Sy({className:e,size:t="default",children:n,asChild:r,onPointerDownCapture:s,onFocusCapture:o,...i}){const a=H.useContext(w1),l=H.useCallback(f=>{if(!a)return;const u=f instanceof HTMLElement?f:null;a.setPortalContainer(QR(u))},[a]),d=r&&H.isValidElement(n)?{render:n}:null;return c.jsx(d8,{"data-slot":"select-trigger","data-size":t,className:R(JR({size:t==="settings"||t==="lg"?"default":"sm"}),"w-fit data-[placeholder]:text-muted-foreground aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2",e),onPointerDownCapture:f=>{l(f.currentTarget),s?.(f)},onFocusCapture:f=>{l(f.currentTarget),o?.(f)},...i,...d??{},children:d?void 0:c.jsxs(c.Fragment,{children:[n,c.jsx(u8,{children:c.jsx($,{name:"arrow-down-s",className:"size-4 opacity-70"})})]})})}function Cy({className:e,children:t,position:n="popper",fitContent:r=!1,portalToBody:s=!1,sideOffset:o,side:i,align:a,...l}){const d=H.useContext(w1),f=n==="item-aligned",u=d?.portalContainer??null;return c.jsx(h8,{container:s?void 0:u||void 0,children:c.jsx(p8,{alignItemWithTrigger:f,sideOffset:o,side:i,align:a,className:"absolute z-[120] pointer-events-auto",children:c.jsx(m8,{"data-slot":"select-content",style:{color:"var(--surface-elevated-foreground)"},className:R("oc-glass-popover oc-glass-floating pointer-events-auto transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 relative z-[120] max-h-[var(--oc-select-max-height,var(--available-height))] min-w-[8rem] origin-[var(--transform-origin)] overflow-x-hidden rounded-xl","data-[side=top]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-top,0px))] data-[side=bottom]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-bottom,0px))]",!f&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r&&"w-max min-w-0",e),...l,children:c.jsx(Yn,{outerClassName:R("max-h-[var(--oc-select-max-height,var(--available-height))]",r?"w-max":"w-full"),className:R("p-1",!f&&(r?"w-max min-w-0 scroll-my-1":"w-full min-w-[var(--anchor-width)] scroll-my-1")),preventOverscroll:!0,children:t})})})})}function tP({className:e,...t}){return c.jsx(b8,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",e),...t})}function ky({className:e,children:t,...n}){return c.jsxs(g8,{"data-slot":"select-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[selected]:bg-interactive-selection data-[selected]:text-interactive-selection-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[c.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:c.jsx(y8,{children:c.jsx($,{name:"check",className:"size-4"})})}),c.jsx(v8,{children:t})]})}const My=e=>e.some(t=>t.source==="local"&&(t.uploadState?.status==="preparing"||t.uploadState?.status==="uploading")),nP=e=>e.some(t=>t.source==="local"&&t.uploadState?.status==="failed"),nh=(e,t=Date.now())=>e.every(n=>n.source==="server"||n.uploadState?.status==="ready"&&n.uploadState.expiresAt>t),Fl=200,Iy={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},N3=()=>Fl,rP=()=>Math.round(N3()*.6),sP={MAX_SESSIONS:Iy.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(Fl*.6),HISTORICAL_MESSAGES:Fl,FETCH_BUFFER:20,HISTORY_CHUNK:Fl,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:Iy.ZOMBIE_TIMEOUT},Ey=()=>{const e=N3(),t=rP();return{...sP,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},oP=5e3,_n=new Map,Ar=new Map,ar=new Map,fa=new Map,co=(e,t)=>`${e}
65
- ${t?.trim()??""}`,Lo=e=>{fa.set(e,(fa.get(e)??0)+1),Ar.delete(e)},iP=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=co(t,e);_n.delete(r),Lo(r);return}const n=new Set([..._n.keys(),...Ar.keys(),...ar.keys()]);for(const r of n)r.startsWith(`${t}
66
- `)&&(_n.delete(r),Lo(r))},rh=e=>{const t=new Set([..._n.keys(),...Ar.keys(),...ar.keys()]);for(const n of t)n.startsWith(`${e}
67
- `)&&(_n.delete(n),Lo(n))},Jc=e=>e.snippets.map(t=>({id:t.id,name:t.name,content:t.content,aliases:t.aliases??[],...t.description?{description:t.description}:{},source:t.scope==="project"?"project":"global",...typeof t.directory=="string"?{directory:t.directory}:{}})),Or=Et()(gr((e,t)=>({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null,setSelectedSnippet:n=>e({selectedSnippetId:n}),setSnippetDraft:n=>e({snippetDraft:n}),resetForRuntimeSwitch:()=>{_n.clear(),Ar.clear(),ar.clear(),fa.clear(),e({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null})},loadSnippets:async n=>{const r=Y(),s=co(r,n),o=Date.now(),i=ar.get(s);e({activeCacheKey:s,snippets:i??[],isLoading:!0});const a=_n.get(s)??0;if(a>0&&o-a<oP)return e({isLoading:!1}),!0;const l=Ar.get(s);if(l)return l;const d=fa.get(s)??0,f=(async()=>{try{const u=await Ie.listSnippets(n,{runtimeKey:r});if(Y()!==r)return!1;if((fa.get(s)??0)!==d)return e(m=>m.activeCacheKey===s?{isLoading:!1}:m),!0;const h=Jc(u);return ar.set(s,h),_n.set(s,Date.now()),e(m=>m.activeCacheKey===s?{snippets:h,isLoading:!1,...m.selectedSnippetId&&!h.some(g=>g.id===m.selectedSnippetId)?{selectedSnippetId:null}:{}}:m),!0}catch{return e(u=>u.activeCacheKey===s?{isLoading:!1}:u),!1}})();Ar.set(s,f);try{return await f}finally{Ar.get(s)===f&&Ar.delete(s)}},createSnippet:async(n,r,s={})=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ie.createSnippet({name:n,content:r,...s.description!==void 0?{description:s.description}:{},...s.aliases!==void 0?{aliases:s.aliases}:{},scope:s.scope??"global",...i?{directory:i}:{}},{runtimeKey:o});if(Y()!==o)return!1;const l=co(o,i),d=Jc(a);Lo(l),ar.set(l,d),rh(o),_n.set(l,Date.now());const f=d.find(u=>u.name===n&&u.source===(s.scope??"global"));return e(u=>u.activeCacheKey===l?{snippets:d,snippetDraft:null,selectedSnippetId:f?.id??null,isLoading:!1}:u),!0}catch{return!1}},updateSnippet:async(n,r,s)=>{const o=Y(),i=t().snippets.find(l=>l.id===n);if(!i)return!1;const a=s?.trim()?s.trim():i.source==="project"&&i.directory?i.directory:void 0;try{const l=await Ie.updateSnippet(i.id,{...r.name!==void 0?{name:r.name}:{},...r.content!==void 0?{content:r.content}:{},...r.description!==void 0?{description:r.description}:{},...r.aliases!==void 0?{aliases:r.aliases}:{},...r.scope!==void 0?{scope:r.scope}:{},...r.directory!==void 0?{directory:r.directory}:{}},a,{runtimeKey:o});if(Y()!==o)return!1;const d=co(o,a),f=Jc(l);return Lo(d),ar.set(d,f),rh(o),_n.set(d,Date.now()),e(u=>u.activeCacheKey===d?{snippets:f,isLoading:!1}:u),!0}catch{return!1}},deleteSnippet:async(n,r)=>{const s=Y(),o=t().snippets.find(a=>a.id===n);if(!o)return!1;const i=r?.trim()?r.trim():o.source==="project"&&o.directory?o.directory:void 0;try{const a=await Ie.deleteSnippet(o.id,i,{runtimeKey:s});if(Y()!==s)return!1;const l=co(s,i),d=Jc(a);return Lo(l),ar.set(l,d),rh(s),_n.set(l,Date.now()),e(f=>f.activeCacheKey===l?{snippets:d,isLoading:!1,...f.selectedSnippetId===n?{selectedSnippetId:null}:{}}:f),!0}catch{return!1}},expandText:(n,r)=>{if(!n||!n.includes("#"))return n;const s=co(Y(),r),o=ar.get(s)??(t().activeCacheKey===s?t().snippets:[]),i=new Map,a=[...o].sort((l,d)=>+(d.source==="project")-+(l.source==="project"));for(const l of a){const d=l.name.toLowerCase();i.has(d)||i.set(d,l.content);for(const f of l.aliases??[]){const u=f.toLowerCase();i.has(u)||i.set(u,l.content)}}return i.size===0?n:n.replace(/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,(l,d,f)=>{const u=i.get(f.toLowerCase());return u!==void 0?`${d}${u}`:l})},getSnippetByName:n=>t().snippets.find(r=>r.name===n)}),{name:"snippets-store"})),GJ=Object.freeze(Object.defineProperty({__proto__:null,invalidateSnippetsLoadCache:iP,useSnippetsStore:Or},Symbol.toStringTag,{value:"Module"}));function L3(e){const t=e.split(".").pop()?.toLowerCase(),n=e.split("/").pop()?.toLowerCase()||"",r={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return r[n]?r[n]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"html",heex:"html",leex:"html",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[t||""]||null}const aP=["drawio","dio"];function R3(e){const t=e.split(".").pop()?.toLowerCase();return aP.includes(t||"")}const P3=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function ZJ(e){const t=e.split(".").pop()?.toLowerCase();return P3.includes(t||"")}function YJ(e){return e.split(".").pop()?.toLowerCase()==="pdf"}function cP(e){return e.toLowerCase().endsWith(".svg")}const lP=new Set(["pdf","doc","docx","xls","xlsx","ppt","pptx","odt","ods","odp","zip","rar","7z","gz","tgz","tar","bz2","xz","jar","war","apk","dmg","iso","deb","rpm","msi",...P3.filter(e=>e!=="svg"),"mp3","mp4","m4a","aac","flac","ogg","wav","wma","avi","mov","mkv","webm","wmv","ttf","otf","woff","woff2","eot","exe","dll","so","dylib","bin","class","o","a","lib","wasm","node","sqlite","sqlite3","db","dat","parquet","feather","pickle","pyc","pyo","lockb"]);function dP(e){const t=e.split(/[/\\]/).pop()??e,n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toLowerCase()}function XJ(e){if(cP(e))return!1;const t=dP(e);return lP.has(t)}function JJ(e){if(!e)return!1;const t=e.length>8192?e.slice(0,8192):e;if(t.includes("\0")||t.startsWith("%PDF")||t.startsWith("PK")||t.startsWith("PK")||t.startsWith("PK\x07\b"))return!0;let n=0;for(let r=0;r<t.length;r+=1){const s=t.charCodeAt(r);if(s===65533){n+=1;continue}(s<9||s>13&&s<32||s===127)&&(n+=1)}return t.length>0&&n/t.length>.1}function QJ(e){const t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[t||""]||"image/png"}const uP={read:{displayName:"Read file",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"offset",label:"Start line",type:"text"},{key:"limit",label:"Lines to read",type:"text"}]},write:{displayName:"Write file",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit file",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace all",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},apply_patch:{displayName:"Apply patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},bash:{displayName:"Shell command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include pattern",type:"pattern"}]},glob:{displayName:"Find files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore patterns",type:"pattern"}]},task:{displayName:"Agent task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search query",type:"text"},{key:"numResults",label:"Results count",type:"text"},{key:"type",label:"Search type",type:"text"}]},codesearch:{displayName:"Code search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update todo list",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo items",type:"code",language:"json"}]},todoread:{displayName:"Read todo list",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]},lsp:{displayName:"LSP",category:"code",outputLanguage:"json",inputFields:[{key:"operation",label:"Operation",type:"text"},{key:"filePath",label:"File path",type:"file"},{key:"line",label:"Line",type:"text"},{key:"character",label:"Character",type:"text"},{key:"query",label:"Query",type:"text"}]},pichamber:{displayName:"PiChamber",category:"system",outputLanguage:"json",inputFields:[]},plan_enter:{displayName:"Plan mode",category:"ai",outputLanguage:"text",inputFields:[]},plan_exit:{displayName:"Build mode",category:"ai",outputLanguage:"text",inputFields:[]},StructuredOutput:{displayName:"Structured output",category:"ai",outputLanguage:"json",inputFields:[]},structuredoutput:{displayName:"Structured output",category:"ai",outputLanguage:"json",inputFields:[]}};function fP(e){return e.trim().replace(/[_-]+/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Ka(e){return uP[e]||{displayName:fP(e),category:"system",outputLanguage:"text",inputFields:[]}}function hP(e,t,n){const r=Ka(e);if(r.outputLanguage==="auto"){if(n?.filePath||n?.file_path||n?.sourcePath){const s=n.filePath||n.file_path||n.sourcePath,o=L3(s);if(o)return o}if(e==="webfetch"){if(t.trim().startsWith("{")||t.trim().startsWith("["))try{return JSON.parse(t),"json"}catch{}if(t.trim().startsWith("<"))return"html";if(t.includes("```"))return"markdown"}return"text"}return r.outputLanguage||"text"}function pP(e,t){if(!e)return"";const n=r=>{const s=e[r];return typeof s=="string"?s:typeof s=="number"?String(s):null};if(t==="bash"){const r=n("command");if(r)return r}if(t==="lsp"){const r=n("operation")||"lsp",s=n("filePath")||n("file_path")||n("path"),o=n("line"),i=n("character"),a=n("query"),l=o&&i?` (Line: ${o}; Character: ${i})`:"";if(r==="workspaceSymbol")return a?`Operation: ${r} (Query: "${a}")`:`Operation: ${r}`;const d=`Operation: ${r}${l}`;return s?`${d}
68
- ${s}`:d}if(t==="task"){const r=n("prompt");if(r)return r;const s=n("description");if(s)return s}if(t==="apply_patch"&&typeof e=="object"){const r=n("patchText")||n("patch_text")||n("patch");if(r)return r}if((t==="edit"||t==="multiedit")&&typeof e=="object"){const r=n("filePath")||n("file_path")||n("path");if(r)return`File path: ${r}`}if(t==="write"&&typeof e=="object"){const r=n("content");if(r)return r}return typeof e=="object"?Object.entries(e).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>{const i=s.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,l=>l.toUpperCase());let a=o;return typeof o=="object"?a=JSON.stringify(o,null,2):typeof o=="boolean"&&(a=o?"Yes":"No"),`${i}: ${a}`}).join(`
69
- `):String(e)}const D3="p-1.5 max-w-[260px] overflow-hidden rounded-xl bg-popover/95 border border-border shadow-lg";function O3({imageUrl:e,filename:t,metaLine:n}){return e?c.jsxs("div",{children:[c.jsx("img",{src:e,alt:t,loading:"lazy",decoding:"async",className:"max-h-48 w-auto rounded-lg object-contain mx-auto"}),c.jsxs("div",{className:"mt-1 px-1 py-0.5",children:[c.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:t}),n?c.jsx("p",{className:"typography-micro text-muted-foreground",children:n}):null]})]}):c.jsxs("p",{children:[t,n?` (${n})`:""]})}const S1=new Set(["3d","3d_light","abap","abap_light","abc","abc_light","actionscript","actionscript_light","ada","ada_light","adobe-illustrator","adobe-illustrator_light","adobe-photoshop","adobe-photoshop_light","adobe-swc","adobe-swc_light","adonis","adonis_light","advpl","advpl_light","amplify","amplify_light","android","android_light","angular","angular_light","antlr","antlr_light","apiblueprint","apiblueprint_light","apollo","apollo_light","applescript","applescript_light","apps-script","apps-script_light","appveyor","appveyor_light","architecture","architecture_light","arduino","arduino_light","asciidoc","asciidoc_light","assembly","assembly_light","astro","astro_light","astro-config","astro-config_light","astyle","astyle_light","audio","audio_light","aurelia","aurelia_light","authors","authors_light","auto","auto_light","autohotkey","autohotkey_light","autoit","autoit_light","azure","azure_light","azure-pipelines","azure-pipelines_light","babel","babel_light","ballerina","ballerina_light","bazel","bazel_light","bbx","bbx_light","beancount","beancount_light","bench-js","bench-js_light","bench-jsx","bench-jsx_light","bench-ts","bench-ts_light","bibliography","bibliography_light","bibtex-style","bibtex-style_light","bicep","bicep_light","biome","biome_light","bitbucket","bitbucket_light","bithound","bithound_light","blender","blender_light","blink","blink_light","blitz","blitz_light","bower","bower_light","brainfuck","brainfuck_light","browserlist","browserlist_light","bruno","bruno_light","buck","buck_light","bucklescript","bucklescript_light","buildkite","buildkite_light","bun","bun_light","c","c_light","c3","c3_light","cabal","cabal_light","caddy","caddy_light","cadence","cadence_light","cairo","cairo_light","cake","cake_light","capacitor","capacitor_light","capnp","capnp_light","cbx","cbx_light","cds","cds_light","certificate","certificate_light","changelog","changelog_light","chess","chess_light","chrome","chrome_light","circleci","circleci_light","citation","citation_light","clangd","clangd_light","claude","claude_light","cline","cline_light","clojure","clojure_light","cloudfoundry","cloudfoundry_light","cmake","cmake_light","coala","coala_light","cobol","cobol_light","coconut","coconut_light","code-climate","code-climate_light","codecov","codecov_light","codeowners","codeowners_light","coderabbit-ai","coderabbit-ai_light","coffee","coffee_light","coldfusion","coldfusion_light","coloredpetrinets","coloredpetrinets_light","command","command_light","commitizen","commitizen_light","commitlint","commitlint_light","concourse","concourse_light","conduct","conduct_light","console","console_light","contentlayer","contentlayer_light","context","context_light","contributing","contributing_light","controller","controller_light","copilot","copilot_light","cpp","cpp_light","craco","craco_light","credits","credits_light","crystal","crystal_light","csharp","csharp_light","css","css_light","css-map","css-map_light","cucumber","cucumber_light","cuda","cuda_light","cursor","cursor_light","cypress","cypress_light","d","d_light","dart","dart_generated","dart_generated_light","dart_light","database","database_light","deepsource","deepsource_light","denizenscript","denizenscript_light","deno","deno_light","dependabot","dependabot_light","dependencies-update","dependencies-update_light","dhall","dhall_light","diff","diff_light","dinophp","dinophp_light","disc","disc_light","django","django_light","dll","dll_light","docker","docker_light","doctex-installer","doctex-installer_light","document","document_light","dotjs","dotjs_light","drawio","drawio_light","drizzle","drizzle_light","drone","drone_light","duc","duc_light","dune","dune_light","edge","edge_light","editorconfig","editorconfig_light","ejs","ejs_light","elixir","elixir_light","elm","elm_light","email","email_light","ember","ember_light","epub","epub_light","erlang","erlang_light","esbuild","esbuild_light","eslint","eslint_light","excalidraw","excalidraw_light","exe","exe_light","fastlane","fastlane_light","favicon","favicon_light","figma","figma_light","firebase","firebase_light","flash","flash_light","flow","flow_light","folder","folder_light","folder-admin","folder-admin_light","folder-admin-open","folder-admin-open_light","folder-android","folder-android_light","folder-android-open","folder-android-open_light","folder-angular","folder-angular_light","folder-angular-open","folder-angular-open_light","folder-animation","folder-animation_light","folder-animation-open","folder-animation-open_light","folder-ansible","folder-ansible_light","folder-ansible-open","folder-ansible-open_light","folder-api","folder-api_light","folder-api-open","folder-api-open_light","folder-apollo","folder-apollo_light","folder-apollo-open","folder-apollo-open_light","folder-app","folder-app_light","folder-app-open","folder-app-open_light","folder-archive","folder-archive_light","folder-archive-open","folder-archive-open_light","folder-astro","folder-astro_light","folder-astro-open","folder-astro-open_light","folder-atom","folder-atom_light","folder-atom-open","folder-atom-open_light","folder-attachment","folder-attachment_light","folder-attachment-open","folder-attachment-open_light","folder-audio","folder-audio_light","folder-audio-open","folder-audio-open_light","folder-aurelia","folder-aurelia_light","folder-aurelia-open","folder-aurelia-open_light","folder-aws","folder-aws_light","folder-aws-open","folder-aws-open_light","folder-azure-pipelines","folder-azure-pipelines_light","folder-azure-pipelines-open","folder-azure-pipelines-open_light","folder-backup","folder-backup_light","folder-backup-open","folder-backup-open_light","folder-base","folder-base_light","folder-base-open","folder-base-open_light","folder-batch","folder-batch_light","folder-batch-open","folder-batch-open_light","folder-benchmark","folder-benchmark_light","folder-benchmark-open","folder-benchmark-open_light","folder-bibliography","folder-bibliography_light","folder-bibliography-open","folder-bibliography-open_light","folder-bicep","folder-bicep_light","folder-bicep-open","folder-bicep-open_light","folder-blender","folder-blender_light","folder-blender-open","folder-blender-open_light","folder-bloc","folder-bloc_light","folder-bloc-open","folder-bloc-open_light","folder-bower","folder-bower_light","folder-bower-open","folder-bower-open_light","folder-buildkite","folder-buildkite_light","folder-buildkite-open","folder-buildkite-open_light","folder-cart","folder-cart_light","folder-cart-open","folder-cart-open_light","folder-changesets","folder-changesets_light","folder-changesets-open","folder-changesets-open_light","folder-ci","folder-ci_light","folder-ci-open","folder-ci-open_light","folder-circleci","folder-circleci_light","folder-circleci-open","folder-circleci-open_light","folder-class","folder-class_light","folder-class-open","folder-class-open_light","folder-claude","folder-claude_light","folder-claude-open","folder-claude-open_light","folder-client","folder-client_light","folder-client-open","folder-client-open_light","folder-cline","folder-cline_light","folder-cline-open","folder-cline-open_light","folder-cloud-functions","folder-cloud-functions_light","folder-cloud-functions-open","folder-cloud-functions-open_light","folder-cloudflare","folder-cloudflare_light","folder-cloudflare-open","folder-cloudflare-open_light","folder-cluster","folder-cluster_light","folder-cluster-open","folder-cluster-open_light","folder-cobol","folder-cobol_light","folder-cobol-open","folder-cobol-open_light","folder-command","folder-command_light","folder-command-open","folder-command-open_light","folder-components","folder-components_light","folder-components-open","folder-components-open_light","folder-config","folder-config_light","folder-config-open","folder-config-open_light","folder-connection","folder-connection_light","folder-connection-open","folder-connection-open_light","folder-console","folder-console_light","folder-console-open","folder-console-open_light","folder-constant","folder-constant_light","folder-constant-open","folder-constant-open_light","folder-container","folder-container_light","folder-container-open","folder-container-open_light","folder-content","folder-content_light","folder-content-open","folder-content-open_light","folder-context","folder-context_light","folder-context-open","folder-context-open_light","folder-contract","folder-contract_light","folder-contract-open","folder-contract-open_light","folder-controller","folder-controller_light","folder-controller-open","folder-controller-open_light","folder-core","folder-core_light","folder-core-open","folder-core-open_light","folder-coverage","folder-coverage_light","folder-coverage-open","folder-coverage-open_light","folder-css","folder-css_light","folder-css-open","folder-css-open_light","folder-cursor","folder-cursor_light","folder-cursor-open","folder-cursor-open_light","folder-custom","folder-custom_light","folder-custom-open","folder-custom-open_light","folder-cypress","folder-cypress_light","folder-cypress-open","folder-cypress-open_light","folder-dart","folder-dart_light","folder-dart-open","folder-dart-open_light","folder-database","folder-database_light","folder-database-open","folder-database-open_light","folder-debug","folder-debug_light","folder-debug-open","folder-debug-open_light","folder-decorators","folder-decorators_light","folder-decorators-open","folder-decorators-open_light","folder-delta","folder-delta_light","folder-delta-open","folder-delta-open_light","folder-desktop","folder-desktop_light","folder-desktop-open","folder-desktop-open_light","folder-directive","folder-directive_light","folder-directive-open","folder-directive-open_light","folder-dist","folder-dist_light","folder-dist-open","folder-dist-open_light","folder-docker","folder-docker_light","folder-docker-open","folder-docker-open_light","folder-docs","folder-docs_light","folder-docs-open","folder-docs-open_light","folder-download","folder-download_light","folder-download-open","folder-download-open_light","folder-drizzle","folder-drizzle_light","folder-drizzle-open","folder-drizzle-open_light","folder-dump","folder-dump_light","folder-dump-open","folder-dump-open_light","folder-element","folder-element_light","folder-element-open","folder-element-open_light","folder-enum","folder-enum_light","folder-enum-open","folder-enum-open_light","folder-environment","folder-environment_light","folder-environment-open","folder-environment-open_light","folder-error","folder-error_light","folder-error-open","folder-error-open_light","folder-event","folder-event_light","folder-event-open","folder-event-open_light","folder-examples","folder-examples_light","folder-examples-open","folder-examples-open_light","folder-expo","folder-expo_light","folder-expo-open","folder-expo-open_light","folder-export","folder-export_light","folder-export-open","folder-export-open_light","folder-fastlane","folder-fastlane_light","folder-fastlane-open","folder-fastlane-open_light","folder-favicon","folder-favicon_light","folder-favicon-open","folder-favicon-open_light","folder-firebase","folder-firebase_light","folder-firebase-open","folder-firebase-open_light","folder-firestore","folder-firestore_light","folder-firestore-open","folder-firestore-open_light","folder-flow","folder-flow_light","folder-flow-open","folder-flow-open_light","folder-flutter","folder-flutter_light","folder-flutter-open","folder-flutter-open_light","folder-font","folder-font_light","folder-font-open","folder-font-open_light","folder-forgejo","folder-forgejo_light","folder-forgejo-open","folder-forgejo-open_light","folder-functions","folder-functions_light","folder-functions-open","folder-functions-open_light","folder-gamemaker","folder-gamemaker_light","folder-gamemaker-open","folder-gamemaker-open_light","folder-generator","folder-generator_light","folder-generator-open","folder-generator-open_light","folder-gh-workflows","folder-gh-workflows_light","folder-gh-workflows-open","folder-gh-workflows-open_light","folder-git","folder-git_light","folder-git-open","folder-git-open_light","folder-gitea","folder-gitea_light","folder-gitea-open","folder-gitea-open_light","folder-github","folder-github_light","folder-github-open","folder-github-open_light","folder-gitlab","folder-gitlab_light","folder-gitlab-open","folder-gitlab-open_light","folder-global","folder-global_light","folder-global-open","folder-global-open_light","folder-godot","folder-godot_light","folder-godot-open","folder-godot-open_light","folder-gradle","folder-gradle_light","folder-gradle-open","folder-gradle-open_light","folder-graphql","folder-graphql_light","folder-graphql-open","folder-graphql-open_light","folder-guard","folder-guard_light","folder-guard-open","folder-guard-open_light","folder-gulp","folder-gulp_light","folder-gulp-open","folder-gulp-open_light","folder-helm","folder-helm_light","folder-helm-open","folder-helm-open_light","folder-helper","folder-helper_light","folder-helper-open","folder-helper-open_light","folder-home","folder-home_light","folder-home-open","folder-home-open_light","folder-hook","folder-hook_light","folder-hook-open","folder-hook-open_light","folder-husky","folder-husky_light","folder-husky-open","folder-husky-open_light","folder-i18n","folder-i18n_light","folder-i18n-open","folder-i18n-open_light","folder-images","folder-images_light","folder-images-open","folder-images-open_light","folder-import","folder-import_light","folder-import-open","folder-import-open_light","folder-include","folder-include_light","folder-include-open","folder-include-open_light","folder-intellij","folder-intellij_light","folder-intellij-open","folder-intellij-open_light","folder-interceptor","folder-interceptor_light","folder-interceptor-open","folder-interceptor-open_light","folder-interface","folder-interface_light","folder-interface-open","folder-interface-open_light","folder-ios","folder-ios_light","folder-ios-open","folder-ios-open_light","folder-java","folder-java_light","folder-java-open","folder-java-open_light","folder-javascript","folder-javascript_light","folder-javascript-open","folder-javascript-open_light","folder-jinja","folder-jinja_light","folder-jinja-open","folder-jinja-open_light","folder-job","folder-job_light","folder-job-open","folder-job-open_light","folder-json","folder-json_light","folder-json-open","folder-json-open_light","folder-jupyter","folder-jupyter_light","folder-jupyter-open","folder-jupyter-open_light","folder-keys","folder-keys_light","folder-keys-open","folder-keys-open_light","folder-kubernetes","folder-kubernetes_light","folder-kubernetes-open","folder-kubernetes-open_light","folder-kusto","folder-kusto_light","folder-kusto-open","folder-kusto-open_light","folder-layout","folder-layout_light","folder-layout-open","folder-layout-open_light","folder-lefthook","folder-lefthook_light","folder-lefthook-open","folder-lefthook-open_light","folder-less","folder-less_light","folder-less-open","folder-less-open_light","folder-lib","folder-lib_light","folder-lib-open","folder-lib-open_light","folder-link","folder-link_light","folder-link-open","folder-link-open_light","folder-linux","folder-linux_light","folder-linux-open","folder-linux-open_light","folder-liquibase","folder-liquibase_light","folder-liquibase-open","folder-liquibase-open_light","folder-log","folder-log_light","folder-log-open","folder-log-open_light","folder-lottie","folder-lottie_light","folder-lottie-open","folder-lottie-open_light","folder-lua","folder-lua_light","folder-lua-open","folder-lua-open_light","folder-luau","folder-luau_light","folder-luau-open","folder-luau-open_light","folder-macos","folder-macos_light","folder-macos-open","folder-macos-open_light","folder-mail","folder-mail_light","folder-mail-open","folder-mail-open_light","folder-mappings","folder-mappings_light","folder-mappings-open","folder-mappings-open_light","folder-markdown","folder-markdown_light","folder-markdown-open","folder-markdown-open_light","folder-mercurial","folder-mercurial_light","folder-mercurial-open","folder-mercurial-open_light","folder-messages","folder-messages_light","folder-messages-open","folder-messages-open_light","folder-meta","folder-meta_light","folder-meta-open","folder-meta-open_light","folder-middleware","folder-middleware_light","folder-middleware-open","folder-middleware-open_light","folder-mjml","folder-mjml_light","folder-mjml-open","folder-mjml-open_light","folder-mobile","folder-mobile_light","folder-mobile-open","folder-mobile-open_light","folder-mock","folder-mock_light","folder-mock-open","folder-mock-open_light","folder-mojo","folder-mojo_light","folder-mojo-open","folder-mojo-open_light","folder-molecule","folder-molecule_light","folder-molecule-open","folder-molecule-open_light","folder-moon","folder-moon_light","folder-moon-open","folder-moon-open_light","folder-netlify","folder-netlify_light","folder-netlify-open","folder-netlify-open_light","folder-next","folder-next_light","folder-next-open","folder-next-open_light","folder-ngrx-store","folder-ngrx-store_light","folder-ngrx-store-open","folder-ngrx-store-open_light","folder-node","folder-node_light","folder-node-open","folder-node-open_light","folder-nuxt","folder-nuxt_light","folder-nuxt-open","folder-nuxt-open_light","folder-obsidian","folder-obsidian_light","folder-obsidian-open","folder-obsidian-open_light","folder-open","folder-open_light","folder-organism","folder-organism_light","folder-organism-open","folder-organism-open_light","folder-other","folder-other_light","folder-other-open","folder-other-open_light","folder-packages","folder-packages_light","folder-packages-open","folder-packages-open_light","folder-pdf","folder-pdf_light","folder-pdf-open","folder-pdf-open_light","folder-pdm","folder-pdm_light","folder-pdm-open","folder-pdm-open_light","folder-php","folder-php_light","folder-php-open","folder-php-open_light","folder-phpmailer","folder-phpmailer_light","folder-phpmailer-open","folder-phpmailer-open_light","folder-pipe","folder-pipe_light","folder-pipe-open","folder-pipe-open_light","folder-plastic","folder-plastic_light","folder-plastic-open","folder-plastic-open_light","folder-plugin","folder-plugin_light","folder-plugin-open","folder-plugin-open_light","folder-policy","folder-policy_light","folder-policy-open","folder-policy-open_light","folder-powershell","folder-powershell_light","folder-powershell-open","folder-powershell-open_light","folder-prisma","folder-prisma_light","folder-prisma-open","folder-prisma-open_light","folder-private","folder-private_light","folder-private-open","folder-private-open_light","folder-project","folder-project_light","folder-project-open","folder-project-open_light","folder-prompts","folder-prompts_light","folder-prompts-open","folder-prompts-open_light","folder-proto","folder-proto_light","folder-proto-open","folder-proto-open_light","folder-public","folder-public_light","folder-public-open","folder-public-open_light","folder-python","folder-python_light","folder-python-open","folder-python-open_light","folder-pytorch","folder-pytorch_light","folder-pytorch-open","folder-pytorch-open_light","folder-quasar","folder-quasar_light","folder-quasar-open","folder-quasar-open_light","folder-queue","folder-queue_light","folder-queue-open","folder-queue-open_light","folder-react-components","folder-react-components_light","folder-react-components-open","folder-react-components-open_light","folder-redux-reducer","folder-redux-reducer_light","folder-redux-reducer-open","folder-redux-reducer-open_light","folder-repository","folder-repository_light","folder-repository-open","folder-repository-open_light","folder-resolver","folder-resolver_light","folder-resolver-open","folder-resolver-open_light","folder-resource","folder-resource_light","folder-resource-open","folder-resource-open_light","folder-review","folder-review_light","folder-review-open","folder-review-open_light","folder-robot","folder-robot_light","folder-robot-open","folder-robot-open_light","folder-routes","folder-routes_light","folder-routes-open","folder-routes-open_light","folder-rules","folder-rules_light","folder-rules-open","folder-rules-open_light","folder-rust","folder-rust_light","folder-rust-open","folder-rust-open_light","folder-sandbox","folder-sandbox_light","folder-sandbox-open","folder-sandbox-open_light","folder-sass","folder-sass_light","folder-sass-open","folder-sass-open_light","folder-scala","folder-scala_light","folder-scala-open","folder-scala-open_light","folder-scons","folder-scons_light","folder-scons-open","folder-scons-open_light","folder-scripts","folder-scripts_light","folder-scripts-open","folder-scripts-open_light","folder-secure","folder-secure_light","folder-secure-open","folder-secure-open_light","folder-seeders","folder-seeders_light","folder-seeders-open","folder-seeders-open_light","folder-server","folder-server_light","folder-server-open","folder-server-open_light","folder-serverless","folder-serverless_light","folder-serverless-open","folder-serverless-open_light","folder-shader","folder-shader_light","folder-shader-open","folder-shader-open_light","folder-shared","folder-shared_light","folder-shared-open","folder-shared-open_light","folder-snapcraft","folder-snapcraft_light","folder-snapcraft-open","folder-snapcraft-open_light","folder-snippet","folder-snippet_light","folder-snippet-open","folder-snippet-open_light","folder-src","folder-src_light","folder-src-open","folder-src-open_light","folder-src-tauri","folder-src-tauri_light","folder-src-tauri-open","folder-src-tauri-open_light","folder-stack","folder-stack_light","folder-stack-open","folder-stack-open_light","folder-stencil","folder-stencil_light","folder-stencil-open","folder-stencil-open_light","folder-store","folder-store_light","folder-store-open","folder-store-open_light","folder-storybook","folder-storybook_light","folder-storybook-open","folder-storybook-open_light","folder-stylus","folder-stylus_light","folder-stylus-open","folder-stylus-open_light","folder-sublime","folder-sublime_light","folder-sublime-open","folder-sublime-open_light","folder-supabase","folder-supabase_light","folder-supabase-open","folder-supabase-open_light","folder-svelte","folder-svelte_light","folder-svelte-open","folder-svelte-open_light","folder-svg","folder-svg_light","folder-svg-open","folder-svg-open_light","folder-syntax","folder-syntax_light","folder-syntax-open","folder-syntax-open_light","folder-target","folder-target_light","folder-target-open","folder-target-open_light","folder-taskfile","folder-taskfile_light","folder-taskfile-open","folder-taskfile-open_light","folder-tasks","folder-tasks_light","folder-tasks-open","folder-tasks-open_light","folder-television","folder-television_light","folder-television-open","folder-television-open_light","folder-temp","folder-temp_light","folder-temp-open","folder-temp-open_light","folder-template","folder-template_light","folder-template-open","folder-template-open_light","folder-terraform","folder-terraform_light","folder-terraform-open","folder-terraform-open_light","folder-test","folder-test_light","folder-test-open","folder-test-open_light","folder-theme","folder-theme_light","folder-theme-open","folder-theme-open_light","folder-tools","folder-tools_light","folder-tools-open","folder-tools-open_light","folder-trash","folder-trash_light","folder-trash-open","folder-trash-open_light","folder-trigger","folder-trigger_light","folder-trigger-open","folder-trigger-open_light","folder-turborepo","folder-turborepo_light","folder-turborepo-open","folder-turborepo-open_light","folder-typescript","folder-typescript_light","folder-typescript-open","folder-typescript-open_light","folder-ui","folder-ui_light","folder-ui-open","folder-ui-open_light","folder-unity","folder-unity_light","folder-unity-open","folder-unity-open_light","folder-update","folder-update_light","folder-update-open","folder-update-open_light","folder-upload","folder-upload_light","folder-upload-open","folder-upload-open_light","folder-utils","folder-utils_light","folder-utils-open","folder-utils-open_light","folder-vercel","folder-vercel_light","folder-vercel-open","folder-vercel-open_light","folder-verdaccio","folder-verdaccio_light","folder-verdaccio-open","folder-verdaccio-open_light","folder-video","folder-video_light","folder-video-open","folder-video-open_light","folder-views","folder-views_light","folder-views-open","folder-views-open_light","folder-vm","folder-vm_light","folder-vm-open","folder-vm-open_light","folder-vscode","folder-vscode_light","folder-vscode-open","folder-vscode-open_light","folder-vue","folder-vue_light","folder-vue-directives","folder-vue-directives_light","folder-vue-directives-open","folder-vue-directives-open_light","folder-vue-open","folder-vue-open_light","folder-vuepress","folder-vuepress_light","folder-vuepress-open","folder-vuepress-open_light","folder-vuex-store","folder-vuex-store_light","folder-vuex-store-open","folder-vuex-store-open_light","folder-wakatime","folder-wakatime_light","folder-wakatime-open","folder-wakatime-open_light","folder-webpack","folder-webpack_light","folder-webpack-open","folder-webpack-open_light","folder-windows","folder-windows_light","folder-windows-open","folder-windows-open_light","folder-wordpress","folder-wordpress_light","folder-wordpress-open","folder-wordpress-open_light","folder-yarn","folder-yarn_light","folder-yarn-open","folder-yarn-open_light","folder-zeabur","folder-zeabur_light","folder-zeabur-open","folder-zeabur-open_light","font","font_light","forth","forth_light","fortran","fortran_light","foxpro","foxpro_light","freemarker","freemarker_light","fsharp","fsharp_light","fusebox","fusebox_light","gamemaker","gamemaker_light","garden","garden_light","gatsby","gatsby_light","gcp","gcp_light","gemfile","gemfile_light","gemini","gemini_light","gemini-ai","gemini-ai_light","git","git_light","github-actions-workflow","github-actions-workflow_light","github-sponsors","github-sponsors_light","gitlab","gitlab_light","gitpod","gitpod_light","gleam","gleam_light","gnuplot","gnuplot_light","go","go_gopher","go_gopher_light","go_light","go-mod","go-mod_light","godot","godot_light","godot-assets","godot-assets_light","gradle","gradle_light","grafana-alloy","grafana-alloy_light","grain","grain_light","graphcool","graphcool_light","graphql","graphql_light","gridsome","gridsome_light","groovy","groovy_light","grunt","grunt_light","gulp","gulp_light","h","h_light","hack","hack_light","hadolint","hadolint_light","haml","haml_light","handlebars","handlebars_light","hardhat","hardhat_light","harmonix","harmonix_light","haskell","haskell_light","haxe","haxe_light","hcl","hcl_light","helm","helm_light","heroku","heroku_light","hex","hex_light","histoire","histoire_light","hjson","hjson_light","horusec","horusec_light","hosts","hosts_light","hpp","hpp_light","html","html_light","http","http_light","huff","huff_light","hurl","hurl_light","husky","husky_light","i18n","i18n_light","idris","idris_light","ifanr-cloud","ifanr-cloud_light","image","image_light","imba","imba_light","installation","installation_light","ionic","ionic_light","istanbul","istanbul_light","jar","jar_light","java","java_light","javaclass","javaclass_light","javascript","javascript_light","javascript-map","javascript-map_light","jenkins","jenkins_light","jest","jest_light","jinja","jinja_light","jsconfig","jsconfig_light","json","json_light","jsr","jsr_light","julia","julia_light","jupyter","jupyter_light","just","just_light","karma","karma_light","kcl","kcl_light","key","key_light","keystatic","keystatic_light","kivy","kivy_light","kl","kl_light","knip","knip_light","kotlin","kotlin_light","kubernetes","kubernetes_light","kusto","kusto_light","label","label_light","laravel","laravel_light","latexmk","latexmk_light","lbx","lbx_light","lefthook","lefthook_light","lerna","lerna_light","less","less_light","liara","liara_light","lib","lib_light","lighthouse","lighthouse_light","lilypond","lilypond_light","lintstaged","lintstaged_light","liquid","liquid_light","lisp","lisp_light","livescript","livescript_light","lock","lock_light","log","log_light","lolcode","lolcode_light","lottie","lottie_light","lua","lua_light","luau","luau_light","lyric","lyric_light","makefile","makefile_light","markdoc","markdoc_light","markdoc-config","markdoc-config_light","markdown","markdown_light","markdownlint","markdownlint_light","markojs","markojs_light","mathematica","mathematica_light","matlab","matlab_light","maven","maven_light","mdsvex","mdsvex_light","mdx","mdx_light","mercurial","mercurial_light","merlin","merlin_light","mermaid","mermaid_light","meson","meson_light","minecraft","minecraft_light","minecraft-fabric","minecraft-fabric_light","mint","mint_light","mjml","mjml_light","mocha","mocha_light","modernizr","modernizr_light","mojo","mojo_light","moon","moon_light","moonscript","moonscript_light","mxml","mxml_light","nano-staged","nano-staged_light","ndst","ndst_light","nest","nest_light","netlify","netlify_light","next","next_light","nginx","nginx_light","ngrx-actions","ngrx-actions_light","ngrx-effects","ngrx-effects_light","ngrx-entity","ngrx-entity_light","ngrx-reducer","ngrx-reducer_light","ngrx-selectors","ngrx-selectors_light","ngrx-state","ngrx-state_light","nim","nim_light","nix","nix_light","nodejs","nodejs_alt","nodejs_alt_light","nodejs_light","nodemon","nodemon_light","npm","npm_light","nuget","nuget_light","nunjucks","nunjucks_light","nuxt","nuxt_light","nx","nx_light","objective-c","objective-c_light","objective-cpp","objective-cpp_light","ocaml","ocaml_light","odin","odin_light","opa","opa_light","opam","opam_light","openapi","openapi_light","otne","otne_light","oxlint","oxlint_light","packship","packship_light","palette","palette_light","panda","panda_light","parcel","parcel_light","pascal","pascal_light","pawn","pawn_light","payload","payload_light","pdf","pdf_light","pdm","pdm_light","percy","percy_light","perl","perl_light","php","php_elephant","php_elephant_light","php_elephant_pink","php_elephant_pink_light","php_light","php-cs-fixer","php-cs-fixer_light","phpstan","phpstan_light","phpunit","phpunit_light","pinejs","pinejs_light","pipeline","pipeline_light","pkl","pkl_light","plastic","plastic_light","playwright","playwright_light","plop","plop_light","pm2-ecosystem","pm2-ecosystem_light","pnpm","pnpm_light","poetry","poetry_light","postcss","postcss_light","posthtml","posthtml_light","powerpoint","powerpoint_light","powershell","powershell_light","pre-commit","pre-commit_light","prettier","prettier_light","prisma","prisma_light","processing","processing_light","prolog","prolog_light","prompt","prompt_light","proto","proto_light","protractor","protractor_light","pug","pug_light","puppet","puppet_light","puppeteer","puppeteer_light","purescript","purescript_light","python","python_light","python-misc","python-misc_light","pytorch","pytorch_light","qsharp","qsharp_light","quarto","quarto_light","quasar","quasar_light","quokka","quokka_light","qwik","qwik_light","r","r_light","racket","racket_light","raml","raml_light","razor","razor_light","rbxmk","rbxmk_light","rc","rc_light","react","react_light","react_ts","react_ts_light","readme","readme_light","reason","reason_light","red","red_light","redux-action","redux-action_light","redux-reducer","redux-reducer_light","redux-selector","redux-selector_light","redux-store","redux-store_light","regedit","regedit_light","remark","remark_light","remix","remix_light","renovate","renovate_light","replit","replit_light","rescript","rescript_light","rescript-interface","rescript-interface_light","restql","restql_light","riot","riot_light","roadmap","roadmap_light","roblox","roblox_light","robot","robot_light","robots","robots_light","rocket","rocket_light","rojo","rojo_light","rollup","rollup_light","rome","rome_light","routing","routing_light","rspec","rspec_light","rubocop","rubocop_light","ruby","ruby_light","ruff","ruff_light","rust","rust_light","salesforce","salesforce_light","san","san_light","sas","sas_light","sass","sass_light","sbt","sbt_light","scala","scala_light","scheme","scheme_light","scons","scons_light","screwdriver","screwdriver_light","search","search_light","semantic-release","semantic-release_light","semgrep","semgrep_light","sentry","sentry_light","sequelize","sequelize_light","serverless","serverless_light","settings","settings_light","shader","shader_light","silverstripe","silverstripe_light","simulink","simulink_light","siyuan","siyuan_light","sketch","sketch_light","slim","slim_light","slint","slint_light","slug","slug_light","smarty","smarty_light","sml","sml_light","snakemake","snakemake_light","snapcraft","snapcraft_light","snowpack","snowpack_light","snyk","snyk_light","solidity","solidity_light","sonarcloud","sonarcloud_light","spwn","spwn_light","stackblitz","stackblitz_light","stan","stan_light","steadybit","steadybit_light","stencil","stencil_light","stitches","stitches_light","storybook","storybook_light","stryker","stryker_light","stylable","stylable_light","stylelint","stylelint_light","stylus","stylus_light","sublime","sublime_light","subtitles","subtitles_light","supabase","supabase_light","svelte","svelte_light","svg","svg_light","svgo","svgo_light","svgr","svgr_light","swagger","swagger_light","sway","sway_light","swc","swc_light","swift","swift_light","syncpack","syncpack_light","systemd","systemd_light","table","table_light","tailwindcss","tailwindcss_light","taskfile","taskfile_light","tauri","tauri_light","taze","taze_light","tcl","tcl_light","teal","teal_light","templ","templ_light","template","template_light","terraform","terraform_light","test-js","test-js_light","test-jsx","test-jsx_light","test-ts","test-ts_light","tex","tex_light","textlint","textlint_light","tilt","tilt_light","tldraw","tldraw_light","tobi","tobi_light","tobimake","tobimake_light","todo","todo_light","toml","toml_light","travis","travis_light","tree","tree_light","trigger","trigger_light","tsconfig","tsconfig_light","tsdoc","tsdoc_light","tsil","tsil_light","tune","tune_light","turborepo","turborepo_light","twig","twig_light","twine","twine_light","typescript","typescript_light","typescript-def","typescript-def_light","typst","typst_light","umi","umi_light","uml","uml_light","unity","unity_light","unocss","unocss_light","url","url_light","uv","uv_light","vagrant","vagrant_light","vala","vala_light","vanilla-extract","vanilla-extract_light","varnish","varnish_light","vedic","vedic_light","velite","velite_light","velocity","velocity_light","vercel","vercel_light","verdaccio","verdaccio_light","verified","verified_light","verilog","verilog_light","vfl","vfl_light","video","video_light","vim","vim_light","virtual","virtual_light","visualstudio","visualstudio_light","vite","vite_light","vitest","vitest_light","vlang","vlang_light","vscode","vscode_light","vue","vue_light","vue-config","vue-config_light","vuex-store","vuex-store_light","wakatime","wakatime_light","wallaby","wallaby_light","wally","wally_light","watchman","watchman_light","webassembly","webassembly_light","webhint","webhint_light","webpack","webpack_light","wepy","wepy_light","werf","werf_light","windicss","windicss_light","wolframlanguage","wolframlanguage_light","word","word_light","wrangler","wrangler_light","wxt","wxt_light","xaml","xaml_light","xmake","xmake_light","xml","xml_light","yaml","yaml_light","yang","yang_light","yarn","yarn_light","zeabur","zeabur_light","zig","zig_light","zip","zip_light"]),Op="oc-file-type-icon-sprite-root",_y="http://www.w3.org/2000/svg";let C1=null,Mi=null,ha=null;const Sd=new Set,pa=new Set;let H3=0;const Hp=new Set,jy=()=>H3,mP=e=>(Hp.add(e),()=>{Hp.delete(e)}),gP=()=>{H3+=1;for(const e of Array.from(Hp))e()},yP=()=>mt(()=>import("./sprite-HGQGInUp.js"),[]);let vP=yP;const xP=e=>{const t=new Map;for(const n of e.matchAll(/<symbol\b[^>]*\bid="([^"]+)"[^>]*>[\s\S]*?<\/symbol>/g))t.set(n[1],n[0]);return t},F3=()=>{if(typeof document>"u"||!document.body)return null;const e=document.getElementById(Op),t=e?.querySelector("defs");if(t)return t;e?.remove(),Sd.clear();const n=document.createElement("div");n.id=Op,n.setAttribute("aria-hidden","true"),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden";const r=document.createElementNS(_y,"svg");r.setAttribute("width","0"),r.setAttribute("height","0");const s=document.createElementNS(_y,"defs");return r.appendChild(s),n.appendChild(r),document.body.appendChild(n),s},bP=()=>typeof document>"u"||!document.body?!1:!!document.getElementById(Op)?.querySelector("defs"),k1=e=>{const t=F3();if(!t||Sd.has(e)||!ha)return;const n=ha.get(e);if(n){Sd.add(e),t.insertAdjacentHTML("beforeend",n);for(const r of n.matchAll(/href="#([^"]+)"/g))ha.has(r[1])&&k1(r[1])}},wP=e=>{if(!(Sd.has(e)&&bP())){if(C1===null||ha===null){pa.add(e),B3().catch(()=>{});return}pa.delete(e),k1(e)}},SP=e=>{if(C1=e,ha=xP(e),pa.size>0&&F3()!==null){const t=Array.from(pa);pa.clear();for(const n of t)k1(n)}gP()},B3=()=>C1!==null?Promise.resolve():(Mi||(Mi=vP().then(e=>{Mi=null,SP(typeof e=="string"?e:e.default)},()=>{throw Mi=null,new Error("file-type sprite failed to load")})),Mi),CP=()=>{if(typeof window>"u"||typeof document>"u")return;const e=()=>{B3().catch(()=>{})};if(typeof window.requestIdleCallback=="function"){window.requestIdleCallback(()=>e());return}window.setTimeout(e,0)};CP();const Ty={dockerfile:"docker",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake","package-lock.json":"npm","yarn.lock":"yarn","pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","tsconfig.json":"tsconfig","jsconfig.json":"jsconfig",".gitignore":"git",".gitattributes":"git",".gitmodules":"git",".editorconfig":"editorconfig",".npmrc":"npm",".yarnrc":"yarn",".prettierrc":"prettier",".eslintrc":"eslint",".babelrc":"babel"},Ay={javascript:"javascript",jsx:"react",typescript:"typescript",tsx:"react_ts",html:"html",handlebars:"handlebars",twig:"twig",liquid:"liquid",css:"css",scss:"sass",sass:"sass",less:"less",stylus:"stylus",json:"json",yaml:"yaml",toml:"toml",xml:"xml",ini:"settings",properties:"settings",bash:"console",powershell:"powershell",batch:"console",python:"python",ruby:"ruby",erb:"ruby",php:"php",java:"java",kotlin:"kotlin",scala:"scala",groovy:"groovy",c:"c",cpp:"cpp",objectivec:"objective-c",csharp:"csharp",fsharp:"fsharp",go:"go",rust:"rust",swift:"swift",dart:"dart",lua:"lua",perl:"perl",r:"r",julia:"julia",haskell:"haskell",elixir:"elixir",erlang:"erlang",clojure:"clojure",lisp:"lisp",scheme:"scheme",ocaml:"ocaml",reason:"reason",nim:"nim",zig:"zig",v:"vlang",crystal:"crystal",d:"d",sql:"database",graphql:"graphql",solidity:"solidity",nasm:"assembly",nix:"nix",hcl:"terraform",puppet:"puppet",latex:"tex",bibtex:"bibliography",markdown:"markdown",asciidoc:"asciidoc",text:"document",vim:"vim",makefile:"makefile",cmake:"cmake",diff:"diff",prisma:"prisma",protobuf:"proto",thrift:"document",wasm:"webassembly",glsl:"shader",hlsl:"shader",cg:"shader",apacheconf:"settings",nginx:"nginx"},Ny={yml:"yaml",mdx:"mdx",md:"markdown",lock:"lock",env:"settings",zip:"zip",tgz:"zip",gz:"zip",rar:"zip","7z":"zip",png:"image",jpg:"image",jpeg:"image",gif:"image",svg:"svg",webp:"image",avif:"image",bmp:"image",ico:"favicon",mp3:"audio",wav:"audio",flac:"audio",ogg:"audio",mp4:"video",mov:"video",avi:"video",mkv:"video",webm:"video",pdf:"pdf",doc:"word",docx:"word",ppt:"powerpoint",pptx:"powerpoint"},Cd="document",kP=(e,t)=>{if(!e)return t==="light"?`${Cd}_light`:Cd;if(t==="light"){const n=e.endsWith("_light")?e:`${e}_light`;return S1.has(n)?n:e}return e},MP=e=>typeof e=="string"&&e.trim().length>0,IP=(e,t)=>{const r=e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()||"";if(Ty[r])return Ty[r];if(r.startsWith(".env"))return"settings";const s=L3(e);if(s&&Ay[s])return Ay[s];const o=MP(t)?t.toLowerCase():r.includes(".")&&r.split(".").pop()?.toLowerCase()||"";return o&&Ny[o]?Ny[o]:o&&S1.has(o)?o:Cd},EP=(e,t)=>{const n=IP(e,t?.extension),r=S1.has(n)?n:Cd,s=kP(r,t?.themeVariant);return wP(s),`#${s}`},pr=({filePath:e,extension:t,className:n})=>{const r=Dw(),s=H.useSyncExternalStore(mP,jy,jy),o=r?.currentTheme.metadata.variant==="light"?"light":"dark",i=EP(e,{extension:t,themeVariant:o});return c.jsx("svg",{className:R("block h-4 w-4 flex-shrink-0",n),"aria-hidden":"true",focusable:"false",children:c.jsx("use",{href:i,xlinkHref:i},s)})},_P=e=>e===null?null:Math.min(100,Math.max(0,e));function jP({filename:e,progress:t}){const n=_P(t);return c.jsx("span",{role:"progressbar","aria-label":`Uploading ${e}`,"aria-valuemin":0,"aria-valuemax":100,...n!==null?{"aria-valuenow":n}:{},className:"relative block size-6 shrink-0",children:c.jsx("span",{className:"block size-6",style:n===null?void 0:{opacity:.35+.65*n/100,filter:`saturate(${n/100})`},children:c.jsx(pr,{filePath:e,className:"size-6 shrink-0"})})})}const TP=H.memo(()=>{const e=H.useRef(null),t=Ye(a=>a.addAttachedFile),n=re(a=>a.isMobile),r=n?"h-9 w-9":"h-7 w-7",s=n?"h-5 w-5":"h-[18px] w-[18px]",o=async a=>{await Promise.all(Array.from(a).map(async l=>{try{await t(l)}catch(d){console.error("File attach failed",d),Ce.error(d instanceof Error?d.message:"Failed to attach file")}}))},i=async a=>{const l=a.target.files;l&&(await o(l),e.current&&(e.current.value=""))};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:e,type:"file",multiple:!0,className:"hidden",onChange:i}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("button",{type:"button",onClick:()=>e.current?.click(),className:R("flex items-center justify-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring","hover:bg-muted text-muted-foreground",r),"aria-label":"Attach files",children:c.jsx($,{name:"attachment-2",className:s})})}),c.jsx(Ct,{side:"top",children:c.jsx("p",{children:"Attach files"})})]})]})});TP.displayName="FileAttachmentButton";const AP=e=>!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,NP=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},V3=H.memo(({file:e,onRemove:t,onRetry:n,onShowPopup:r,gallery:s,galleryIndex:o})=>{const{isMobile:i,isTablet:a}=Dn(),l=i||a,d=e.uploadState,f=d?.status==="ready"&&d.expiresAt<=Date.now(),u=e.mimeType.startsWith("image/"),h=u&&e.previewUrl?e.previewUrl:u&&e.dataUrl.startsWith("data:image/")?e.dataUrl:u&&e.serverPath||"",m=NP(e.filename),g=AP(e.size),x=d?.status==="preparing"?"Preparing attachment":d?.status==="uploading"?"Uploading attachment":d?.status==="failed"||f?"Attachment upload failed":d?.status==="ready"?"Attachment ready":"Server attachment ready",b=d?.status==="uploading"?d.progress:null,S=d?.status==="uploading"||d?.status==="preparing",y=d?.status==="failed"?d.error:f?"Upload expired.":null,v=()=>{!r||!h||r({open:!0,title:e.filename||"Image",content:"",metadata:{tool:"image-preview",filename:e.filename,mime:e.mimeType,size:e.size},image:{url:h,mimeType:e.mimeType,filename:e.filename,size:e.size,gallery:s,index:o}})};return c.jsxs("article",{className:R("group relative min-w-0 overflow-hidden rounded-xl border w-full",y?"border-[var(--status-error)]/50 bg-[var(--status-error-background)]/40":"border-border/60 bg-[var(--surface-elevated)]"),children:[c.jsx("span",{className:"sr-only","aria-live":"polite",children:x}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("div",{role:h&&r?"button":void 0,tabIndex:h&&r?0:void 0,onClick:v,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),v())},className:R("flex min-h-14 items-center gap-2.5 px-3 py-2",y?"pr-14":"pr-8",h&&r&&"cursor-pointer select-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),"aria-label":h?`Preview ${e.filename}`:void 0,children:[S?c.jsx(jP,{filename:e.filename,progress:b}):c.jsx(pr,{filePath:e.filename,extension:m,className:"size-6 shrink-0"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"truncate typography-ui-label text-foreground",title:e.filename,children:e.filename}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:[m.toUpperCase(),g].filter(Boolean).join(" · ")})]})]})}),c.jsx(Ct,{side:"top",className:R(h&&!y?D3:void 0),children:y?c.jsx("p",{children:y}):c.jsx(O3,{imageUrl:h||void 0,filename:e.filename,metaLine:h?[m.toUpperCase(),g].filter(Boolean).join(" · "):g})})]}),S?c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 overflow-hidden rounded-xl",children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}):null,c.jsx(be,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),t()},className:R("absolute right-1 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Remove ${e.filename}`,title:`Remove ${e.filename}`,children:c.jsx($,{name:"close",className:"size-3.5"})}),y?c.jsx(be,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),n()},className:R("absolute right-8 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Retry upload of ${e.filename}`,title:"Retry upload",children:c.jsx($,{name:"refresh",className:"size-3.5"})}):null]})});V3.displayName="DraftAttachmentCard";const $3=H.memo(({onShowPopup:e,className:t,isInline:n=!1,isMobile:r=!1})=>{const s=Ye(h=>h.attachedFiles),o=Ye(h=>h.removeAttachedFile),i=Ye(h=>h.retryAttachmentUpload),[,a]=p.useState(0);if(p.useEffect(()=>{const h=s.reduce((g,x)=>x.uploadState?.status!=="ready"||x.uploadState.expiresAt<=Date.now()?g:g===null?x.uploadState.expiresAt:Math.min(g,x.uploadState.expiresAt),null);if(h===null)return;const m=setTimeout(()=>a(g=>g+1),Math.max(0,h-Date.now()+1));return()=>clearTimeout(m)},[s]),s.length===0)return null;const d=s.filter(h=>h.mimeType.startsWith("image/")).flatMap(h=>{const m=h.previewUrl||h.dataUrl||h.serverPath||"";return m?[{file:h,image:{url:m,mimeType:h.mimeType,filename:h.filename,size:h.size}}]:[]}),f=d.map(h=>h.image),u=new Map(d.map((h,m)=>[h.file.id,m]));return c.jsx("div",{className:R("grid w-full gap-2 grid-cols-2 sm:grid-cols-3",n?"px-1.5 pt-1.5 pb-1":r?"px-3 pt-2.5 pb-1.5":"px-3 pt-3 pb-1.5",t),"data-no-drawer-swipe":"true",children:s.map(h=>c.jsx(V3,{file:h,onRemove:()=>o(h.id),onRetry:()=>i(h.id),onShowPopup:e,gallery:f,galleryIndex:u.get(h.id)??0},h.id))})});$3.displayName="AttachedFilesList";const LP="application/vnd.github.issue-link",RP="application/vnd.github.pull-request-link",sh=e=>e.mime===LP?"issue":e.mime===RP?"pr":null,M1=H.memo(({files:e,onShowPopup:t,compact:n=!1})=>{const r=e.filter(u=>u.type==="file"&&(u.mime||u.url)),s=u=>{if(!u)return"Unnamed file";const m=u.replace(/\\/g,"/").split("/");return m[m.length-1]||u},o=p.useCallback(u=>sh(u)!==null&&typeof u.filename=="string"&&u.filename.trim().length>0?u.filename.trim():s(u.filename||u.url),[]),i=u=>!u||!Number.isFinite(u)||u<=0?"":u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:`${(u/(1024*1024)).toFixed(1)} MB`,a=r.filter(u=>u.mime?.startsWith("image/")&&u.url),l=r.filter(u=>!u.mime?.startsWith("image/")),d=p.useMemo(()=>a.flatMap(u=>{if(!u.url)return[];const h=o(u)||"Image";return[{url:u.url,mimeType:u.mime,filename:h,size:u.size}]}),[a,o]),f=p.useCallback(u=>{if(!t)return;const h=d[u];if(!h?.url)return;const m=h.filename||"Image";t({open:!0,title:m,content:"",metadata:{tool:"image-preview",filename:m,mime:h.mimeType,size:h.size},image:{url:h.url,mimeType:h.mimeType,filename:m,size:h.size,gallery:d,index:u}})},[d,t]);return r.length===0?null:n?c.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[l.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map((u,h)=>{const m=o(u),g=m.split(".").pop()||"",x=i(u.size),b=sh(u);return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:b&&u.url?c.jsxs("button",{type:"button",onClick:()=>{ja(u.url||"")},className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg text-foreground hover:text-primary transition-colors",children:[b==="pr"?c.jsx($,{name:"git-pull-request",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx($,{name:"github",className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[220px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]}):c.jsxs("div",{className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg",children:[u.mime?.includes("pdf")?c.jsx($,{name:"file-pdf",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx(pr,{filePath:m,extension:g,className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[140px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},`file-${u.url||u.filename||h}`)})}),a.length>0&&c.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-0.5 scrollbar-thin","data-no-drawer-swipe":"true",children:c.jsx("div",{className:"flex snap-x snap-mandatory gap-2",children:a.map((u,h)=>{const m=o(u)||"Image";return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>f(h),className:"relative flex-none border border-border/40 bg-muted/10 overflow-hidden snap-start h-12 w-12 sm:h-14 sm:w-14 md:h-16 md:w-16 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[u.url?c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:g=>{const x=g.target;x.style.visibility="hidden"}}):c.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:c.jsx($,{name:"file-image",className:"h-6 w-6"})}),c.jsx("span",{className:"sr-only",children:m})]})}),c.jsx(Ct,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u.url||u.filename||h}`)})})})]}):c.jsx("div",{className:R("grid gap-2",n?"grid-cols-1":"grid-cols-1 sm:grid-cols-2"),children:r.map((u,h)=>{const m=o(u),g=u.mime?.startsWith("image/"),x=i(u.size),b=sh(u);if(g&&u.url)return c.jsxs("div",{className:"relative aspect-video rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity"}),c.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-2 text-white opacity-0 group-hover:opacity-100 transition-opacity",children:[c.jsx("p",{className:"text-xs font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs opacity-80",children:x})]})]},u.url||`${m}-${h}`);if(b&&u.url)return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{ja(u.url||"")},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:b==="pr"?c.jsx($,{name:"git-pull-request",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx($,{name:"github",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`);const S=u.source,y=typeof S?.type=="string"?S.type:void 0,v=S&&typeof S.path=="string"?S.path:void 0,C=y==="file"&&v?v:u.url||"";return C&&R3(C)?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{re.getState().navigateToDiagram(C)},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left cursor-pointer",n?"text-xs":"text-sm"),children:[c.jsx($,{name:"file",className:R("text-muted-foreground shrink-0",n?"h-3.5 w-3.5":"h-4 w-4")}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),c.jsx("p",{className:"text-xs text-status-info",children:"Open in diagram view"})]}),c.jsx($,{name:"external-link",className:R("text-muted-foreground shrink-0",n?"h-3 w-3":"h-3.5 w-3.5")})]})}),c.jsx(Ct,{children:c.jsx("p",{children:"Open in diagram view"})})]},u.url||`${m}-${h}`):c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{t&&u.url&&t({open:!0,title:m,content:"",image:{url:u.url,mimeType:u.mime,filename:m}})},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:u.mime?.startsWith("image/")?c.jsx($,{name:"file-image",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):u.mime?.includes("pdf")?c.jsx($,{name:"file-pdf",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx($,{name:"file",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(Ct,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`)})})});M1.displayName="MessageFilesDisplay";const PP=H.memo(({urls:e,caption:t,onShowPopup:n})=>{if(e.length===0)return null;const r=()=>e.length===1?"grid-cols-1":e.length===2||e.length<=4?"grid-cols-2":"grid-cols-3";return c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:R("grid gap-2",r()),children:e.map((s,o)=>c.jsxs("button",{type:"button",onClick:()=>n?.({open:!0,title:t||`Image ${o+1} of ${e.length}`,content:"",image:{url:s,gallery:e.map(i=>({url:i})),index:o}}),className:"relative aspect-square rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:s,alt:t||`Image ${o+1}`,className:"h-full w-full object-cover transition-transform group-hover:scale-105",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors"})]},s))}),t&&c.jsx("p",{className:"text-sm text-muted-foreground italic",children:t})]})});PP.displayName="ImageGallery";const z3=H.memo(({message:e,target:t,sending:n,checking:r,canSteer:s,onEdit:o,onSend:i,onCheck:a})=>{const l=ft(C=>C.removeFromQueue),{attributes:d,listeners:f,setNodeRef:u,transform:h,transition:m,isDragging:g}=km({id:e.id}),x=p.useMemo(()=>{const C=e.content.split(`
70
- `),w=C[0]||"",I=100;return w.length>I?w.substring(0,I)+"...":w+(C.length>1?"...":"")},[e.content]),b=e.attachments?.length??0,S=e.deliveryAttempt!==void 0,y=e.sendFailed===!0,v=n||r;return c.jsxs("div",{ref:u,style:{transform:Mm.Translate.toString(h),transition:m},className:R("flex min-w-0 flex-col gap-1 py-1",g&&"z-10 opacity-60"),children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("button",{type:"button",...d,...f,className:"flex flex-shrink-0 cursor-grab touch-none select-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing","aria-label":"Drag to reorder",children:c.jsx($,{name:"draggable",className:"h-4 w-4","aria-hidden":"true"})}),c.jsxs("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:[x||"(empty)",b>0&&c.jsx("span",{className:"ml-1 text-muted-foreground",children:b===1?"+1 file":`+${b} files`})]}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>o(e),disabled:v,children:[c.jsx($,{name:"edit",className:"h-3 w-3","aria-hidden":"true"}),"Edit"]}),S?c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>a(e),disabled:v,"aria-label":"Check delivery status",title:"Check delivery status",children:[c.jsx($,{name:"refresh",className:"h-3 w-3","aria-hidden":"true"}),"Check status"]}):s?c.jsxs(be,{type:"button",variant:"secondary",size:"xs",onClick:()=>i(e),disabled:v,"aria-label":"Send now with steering",title:"Send now with steering",children:[c.jsx($,{name:"send-plane",className:"h-3 w-3","aria-hidden":"true"}),"Steer"]}):null,c.jsx("button",{type:"button",onClick:()=>l(t,e.id),disabled:v,className:"flex items-center justify-center h-6 w-6 flex-shrink-0 hover:bg-[var(--interactive-hover)] rounded-full transition-colors disabled:pointer-events-none disabled:opacity-50","aria-label":"Remove follow-up",children:c.jsx($,{name:"close",className:"h-4 w-4 text-muted-foreground"})})]}),(n||r||y||S)&&c.jsx("p",{className:R("typography-micro pl-6",y&&!n&&!r?"text-[var(--status-error)]":S&&!n&&!r?"text-[var(--status-warning)]":"text-muted-foreground"),role:y||S?"status":void 0,children:n?"Sending…":r?"Checking status…":y?"Send failed. Retry with Steer or remove.":"Delivery uncertain. Check status before retrying."})]})});z3.displayName="QueuedMessageChip";const Ly=[],Ry=[],U3=H.memo(({onEditMessage:e,onSendMessage:t})=>{const n=he(k=>k.currentSessionId),r=uu(n??""),s=he(p.useCallback(k=>n?k.getDirectoryForSession(n):null,[n])),o=n?ym(n,s):null,i=o?L5(o):null,a=ft(p.useCallback(k=>i?k.queuedMessages[i]??Ly:Ly,[i])),l=ft(p.useCallback(k=>i?k.sendingIds[i]??Ry:Ry,[i])),d=ft(k=>k.popToInput),f=ft(k=>k.reorderQueue),[u,h]=p.useState([]),m=n?`session:${n}`:"*",g=ze(k=>k.reducer.bySession,(k,_)=>{if(Object.is(k,_)||!n)return!0;const M=k.get(n)?.queue,L=_.get(n)?.queue;return!M&&!L?!0:!M||!L?!1:M.steering===L.steering&&M.followUp===L.followUp},m),x=n?g.get(n)?.queue:void 0,b=x?.steering??0,S=x?.followUp??0,y=b>0||S>0,v=!!o&&a.length>0,C=b===1?"1 steering message waiting":`${b} steering messages waiting`,w=S===1?"1 follow-up message waiting":`${S} follow-up messages waiting`,I=bm(wa(V5,{activationConstraint:{distance:8}}),wa(B5,{activationConstraint:{delay:200,tolerance:6}})),E=p.useCallback(k=>{const{active:_,over:M}=k;!M||_.id===M.id||!o||f(o,String(_.id),String(M.id))},[o,f]),T=p.useCallback(k=>{if(!o)return;const _=d(o,k.id);if(_){if(_.attachments&&_.attachments.length>0){const M=Ye.getState().attachedFiles;Ye.getState().setAttachedFiles([...M,..._.attachments])}e(_.content,_.attachments)}},[o,d,e]),A=p.useCallback(k=>{t(k.id)},[t]),j=p.useCallback(async k=>{if(!o||!i||u.includes(k.id)||l.includes(k.id))return;const M=ft.getState().queuedMessages[i]?.find(L=>L.id===k.id)?.deliveryAttempt??k.deliveryAttempt;if(M){h(L=>L.includes(k.id)?L:[...L,k.id]);try{const L=await VL(o,M);L==="accepted"?ft.getState().completeQueuedSend(o,k.id):L==="pending"?Ce.info("Delivery still pending. Follow-ups are on hold. Check again later."):Ce.warning("Delivery status unknown. The message stays on hold. No resend attempted.")}finally{h(L=>L.filter(O=>O!==k.id))}}},[o,i,u,l]);return!v&&!y?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[v&&o&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Follow-up messages"," ",a.length]}),r?c.jsx("span",{className:"ml-auto min-w-0 truncate typography-meta text-muted-foreground",children:`Sends after ${r}`}):c.jsx($,{name:"time",className:"ml-auto h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),c.jsx(wm,{sensors:I,collisionDetection:Sm,onDragEnd:E,children:c.jsx(Cm,{items:a.map(k=>k.id),strategy:$5,children:c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:a.map(k=>c.jsx(z3,{message:k,target:o,sending:l.includes(k.id),checking:u.includes(k.id),canSteer:!r,onEdit:T,onSend:A,onCheck:j},k.id))})})})]}),y&&c.jsxs("div",{className:R("px-3 typography-micro text-muted-foreground",v?"pb-3 pt-1":"py-2"),children:[b>0&&c.jsx("p",{role:"status",children:C}),S>0&&c.jsx("p",{role:"status",children:w})]})]})})});U3.displayName="QueuedMessageChips";let oh=Date.now();const DP=()=>(oh=Math.max(oh+1,Date.now()),oh),Py=()=>!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus());function OP({sessionId:e,directory:t,text:n,debounceMs:r=250}){const s=ze(m=>e?m.reducer.bySession.get(e)?.extensionDraftTracked===!0:!1,Object.is,e?`session:${e}`:"chrome"),o=s?n:null,i=H.useRef(n);i.current=n;const a=H.useRef(t);a.current=t;const l=H.useRef(e);l.current=e;const d=H.useRef(new Map),f=H.useRef(null),u=H.useRef(new Set);H.useEffect(()=>{if(!e)return;const m=u.current,g=d.current;return()=>{m.delete(e),g.delete(e)}},[e]);const h=H.useCallback((m,g)=>{if(!Py())return;d.current.set(m,g);const x=DP(),b=a.current;Ie.updateExtensionDraft({sessionId:m,text:g,revision:x,...b?{directory:b}:{}}).catch(()=>{d.current.get(m)===g&&d.current.delete(m)})},[]);H.useEffect(()=>{if(!e||!s)return;const m=()=>{if(!Py())return;const g=i.current,x=d.current.get(e);g!==x&&(f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,g))};return typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("focus",m),typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",m),()=>{typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("focus",m),typeof document<"u"&&typeof document.removeEventListener=="function"&&document.removeEventListener("visibilitychange",m)}},[e,s,h]),H.useEffect(()=>{if(!e||o===null){e&&u.current.delete(e),f.current!==null&&(clearTimeout(f.current),f.current=null);return}if(!u.current.has(e)){u.current.add(e),f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,o);return}const g=d.current.get(e);if(o===g){f.current!==null&&(clearTimeout(f.current),f.current=null);return}return f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null;const x=i.current,b=l.current;!b||x===d.current.get(b)||h(b,x)},r),()=>{f.current!==null&&(clearTimeout(f.current),f.current=null)}},[e,o,r,h])}const HP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.9568%209.88184H22.1265L30.7753%2031.7848H35.4917L26.9568%209.88184ZM13.028%209.88184L4.4917%2031.7848H9.32203L11.2305%2027.1793H20.2166L22.0126%2031.6724H26.8444L18.0832%209.88184H13.028ZM12.5783%2023.1361L15.4987%2015.3853L18.5315%2023.1361H12.5783Z'%20fill='currentColor'/%3e%3c/svg%3e",FP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37.9998%2023.021C33.7998%2025.2889%2029.5698%2027.3649%2024.8614%2028.3069C23.8114%2028.5154%2022.6474%2028.5154%2021.5809%2028.3714C20.5639%2028.2439%2020.0554%2027.3484%2020.4169%2026.4064C20.7619%2025.5289%2021.2209%2024.635%2021.8119%2023.9C23.0899%2022.3025%2024.5329%2020.849%2025.8289%2019.268C26.6203%2018.2991%2027.3335%2017.2689%2027.9618%2016.187C28.4208%2015.4205%2028.2078%2014.4935%2027.4038%2014.111C26.0584%2013.4556%2024.6154%2012.9936%2023.1889%2012.4986C23.0239%2012.4341%2022.7779%2012.6096%2022.4509%2012.7221C22.8604%2013.0881%2023.1559%2013.3596%2023.5654%2013.727C19.3339%2014.447%2015.3305%2015.467%2011.4455%2016.874C11.4275%2016.9535%2011.396%2017.0165%2011.411%2017.0495C11.9855%2017.927%2011.723%2018.5975%2010.886%2019.1405C10.5611%2019.3531%2010.2732%2019.6176%2010.034%2019.9235C12.593%2020.6735%2014.873%2020.243%2017.0539%2018.821C16.9234%2018.6305%2016.7914%2018.455%2016.6609%2018.263C17.4799%2018.407%2017.9719%2018.854%2018.0379%2019.556C18.0544%2019.7165%2017.9569%2019.8755%2017.9074%2020.036C17.7919%2019.907%2017.6449%2019.781%2017.5474%2019.6355C17.4799%2019.5395%2017.4634%2019.4285%2017.4154%2019.268C14.8235%2020.993%2012.035%2021.425%208.96751%2020.531C8.96751%2021.137%208.93451%2021.6485%208.98401%2022.1435C9.01701%2022.574%208.83701%2022.766%208.44401%2022.9895C7.55752%2023.5325%206.63803%2024.092%205.90003%2024.8105C5.01504%2025.6879%205.34354%2026.7589%206.54053%2027.2059C7.90102%2027.7159%209.329%2027.7309%2010.7555%2027.5569C12.4445%2027.3484%2014.1005%2027.0769%2015.9394%2026.8219C13.79%2027.8269%2011.6735%2028.5319%209.4445%2028.8169C7.88452%2029.0269%206.32753%2029.1379%204.78554%2028.6909C2.57156%2028.0684%201.58607%2026.4394%202.16057%2024.251C2.70206%2022.2065%204.01455%2020.5775%205.42454%2019.076C10.133%2014.078%2016.0864%2011.5401%2022.9744%2011.0286C24.5824%2010.9176%2026.2069%2011.1246%2027.7143%2011.7951C29.8308%2012.7536%2030.7173%2014.78%2029.6838%2016.826C29.0118%2018.1835%2028.0758%2019.4285%2027.1413%2020.6585C26.2234%2021.872%2025.1899%2022.9895%2024.2224%2024.155C23.9434%2024.506%2023.6809%2024.875%2023.4679%2025.2724C23.0569%2026.0224%2023.3359%2026.5174%2024.2059%2026.4394C26.0254%2026.2624%2027.8808%2026.1199%2029.6358%2025.6729C32.2098%2025.0174%2034.7193%2024.092%2037.2618%2023.2775C37.5243%2023.213%2037.7703%2023.117%2037.9998%2023.0225V23.021Z'%20fill='currentColor'/%3e%3c/svg%3e",BP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCursor%3c/title%3e%3cg%20transform='translate(12%2012)%20scale(0.88)%20translate(-12%20-12)'%3e%3cpath%20d='M22.106%205.68L12.5.135a.998.998%200%2000-.998%200L1.893%205.68a.84.84%200%2000-.419.726v11.186c0%20.3.16.577.42.727l9.607%205.547a.999.999%200%2000.998%200l9.608-5.547a.84.84%200%2000.42-.727V6.407a.84.84%200%2000-.42-.726zm-.603%201.176L12.228%2022.92c-.063.108-.228.064-.228-.061V12.34a.59.59%200%2000-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264%200%20.428.286.296.514z'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",VP="data:image/svg+xml,%3csvg%20fill='%23000000'%20viewBox='0%200%2033%2025'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M79.01%205.863c-4.066%200-6.511%202.92-6.511%206.535%200%203.635%202.445%206.555%206.511%206.555%204.046%200%206.512-2.92%206.512-6.555s-2.466-6.535-6.512-6.535Zm0%2010.968c-2.633%200-4.172-1.933-4.172-4.433s1.539-4.455%204.172-4.455c2.635%200%204.151%201.933%204.151%204.434%200%202.521-1.516%204.454-4.15%204.454Zm14.393%202.096c3.393%200%205.542-1.808%205.837-4.539h-2.36c-.316%201.555-1.517%202.437-3.477%202.437-2.423%200-3.878-1.68-3.878-4.433%200-2.774%201.476-4.434%203.878-4.434%201.96%200%203.14.862%203.477%202.5h2.36c-.295-2.773-2.444-4.622-5.837-4.622-3.856%200-6.217%202.669-6.217%206.535%200%203.887%202.36%206.556%206.217%206.556Zm-29.543-.311h2.36v-6.01c0-2.752%201.348-4.244%203.772-4.244h2.276V6.177h-2.255c-2.128%200-3.288.735-3.898%202.605l-.443-.063.527-2.542h-2.36v12.439h.02Zm-24.445-7.332c.106-2.101%201.517-3.53%203.793-3.53%202.276%200%203.646%201.345%203.646%203.53h-7.439Zm9.778.4c0-3.426-2.381-5.821-5.943-5.821-3.73%200-6.174%202.563-6.174%206.535%200%204.013%202.423%206.555%206.28%206.555%202.929%200%205.247-1.597%205.669-3.887h-2.36c-.507%201.156-1.666%201.828-3.31%201.828-2.38%200-3.877-1.408-3.94-3.803h9.694c.042-.588.084-.861.084-1.408Zm5.69%206.932h1.939l5.5-12.44h-2.529L56%2015.99l-.316.021-3.793-9.833h-2.508l5.5%2012.439ZM32.23%2012.35c0-.882-.359-1.701-.99-2.437a8.594%208.594%200%200%201-1.497%201.093c.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.281.021-14.118-2.059-14.118-4.811%200-.463.168-.925.505-1.345a8.13%208.13%200%200%201-1.475-1.093c-.632.736-.99%201.555-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.87.021%2016.078-2.5%2016.078-6.535Zm-3.351%201.534c-.906-.462-1.96-.861-3.16-1.197-1.37.378-2.909.672-4.553.861%202.318.294%204.341.778%205.9%201.408.76-.336%201.37-.693%201.813-1.072Zm-17.849-.357a31.902%2031.902%200%200%201-4.467-.84c-1.18.336-2.255.735-3.16%201.197.42.379%201.01.715%201.748%201.05%201.539-.63%203.52-1.113%205.88-1.407Zm21.2-6.808c0-4.013-7.207-6.534-16.079-6.534C7.26.185.051%202.706.051%206.719c0%204.035%207.208%206.535%2016.1%206.535%208.872.021%2016.079-2.5%2016.079-6.535Zm-1.94%200c0%202.732-5.836%204.812-14.139%204.812-8.302.021-14.14-2.06-14.14-4.812%200-2.731%205.838-4.811%2014.14-4.811%207.86%200%2014.14%202.08%2014.14%204.811Zm-3.223%202.564c.758-.336%201.37-.694%201.812-1.072-2.95-1.513-7.544-2.353-12.728-2.353s-9.799.84-12.728%202.353c.422.378%201.012.715%201.75%201.05%202.507-1.05%206.363-1.68%2010.978-1.68%204.404%200%208.324.651%2010.916%201.702ZM1.042%2015.628c-.632.736-.99%201.534-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.892%200%2016.099-2.521%2016.099-6.534%200-.883-.359-1.702-.99-2.438-.422.4-.907.757-1.497%201.093.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.302%200-14.14-2.08-14.14-4.811%200-.463.17-.925.506-1.345a10.73%2010.73%200%200%201-1.475-1.093Z'/%3e%3c/svg%3e",$P="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M35.3993%2026.4544C34.2871%2028.3855%2027.8314%2032.9425%2020%2032.9425C12.1686%2032.9425%205.71288%2028.3855%204.60075%2026.4544C4.5427%2026.3532%204.50826%2026.2401%204.5%2026.1237V22.418C4.51199%2022.3209%204.53496%2022.2256%204.56846%2022.1338C5.04896%2020.9261%206.30833%2019.1733%207.93325%2018.7031C8.14896%2018.149%208.468%2017.3404%208.76508%2016.7437C8.71727%2016.2776%208.69485%2015.8094%208.69792%2015.3409C8.69792%2013.6217%209.06217%2012.113%2010.1601%2010.9906C10.6729%2010.4662%2011.3097%2010.0644%2012.064%209.76091C13.871%208.29357%2016.4453%207.05745%2019.9716%207.05745C23.4978%207.05745%2026.129%208.29357%2027.936%209.76091C28.6903%2010.0644%2029.3271%2010.4662%2029.8399%2010.9906C30.9378%2012.113%2031.3021%2013.6217%2031.3021%2015.3409C31.3021%2015.8162%2031.284%2016.2877%2031.2349%2016.7437C31.532%2017.3404%2031.851%2018.149%2032.0667%2018.7031C33.6917%2019.1733%2034.951%2020.9261%2035.4315%2022.1338C35.4677%2022.2248%2035.4908%2022.3205%2035.5%2022.418V26.1237C35.4917%2026.2401%2035.4573%2026.3532%2035.3993%2026.4544ZM20.2222%2018.7147H19.7778C19.6422%2018.945%2019.4889%2019.1644%2019.3193%2019.3709C18.3247%2020.5941%2016.8419%2021.2981%2014.7881%2021.2981C12.56%2021.2981%2010.9273%2020.8344%209.90304%2019.6719C9.86495%2019.6283%209.82833%2019.5835%209.79325%2019.5375L9.66667%2019.6719V28.1775C11.5202%2029.1837%2015.4972%2030.992%2020%2030.992C24.5028%2030.992%2028.4798%2029.1837%2030.3333%2028.1775V19.6719L30.2067%2019.5375C30.2067%2019.5375%2030.1641%2019.5957%2030.097%2019.6719C29.0727%2020.8344%2027.44%2021.2981%2025.2119%2021.2981C23.1581%2021.2981%2021.6753%2020.5941%2020.6807%2019.3709C20.5111%2019.1644%2020.3578%2018.945%2020.2222%2018.7147ZM23.2292%2022.9127C23.9383%2022.9127%2024.5208%2023.4952%2024.5208%2024.2043V26.7877C24.5208%2027.4968%2023.9383%2028.0793%2023.2292%2028.0793C22.52%2028.0793%2021.9375%2027.4968%2021.9375%2026.7877V24.2043C21.9375%2023.4952%2022.52%2022.9127%2023.2292%2022.9127ZM16.7708%2022.9127C17.48%2022.9127%2018.0625%2023.4952%2018.0625%2024.2043V26.7877C18.0625%2027.4968%2017.48%2028.0793%2016.7708%2028.0793C16.0617%2028.0793%2015.4792%2027.4968%2015.4792%2026.7877V24.2043C15.4792%2023.4952%2016.0617%2022.9127%2016.7708%2022.9127ZM21.0501%2014.9237C21.2258%2016.289%2021.5707%2017.3947%2022.1842%2018.149C22.7551%2018.8517%2023.649%2019.3606%2025.2119%2019.3606C27.2437%2019.3606%2028.1724%2018.9253%2028.6438%2018.3905C29.1398%2017.8287%2029.3646%2016.9051%2029.3646%2015.3409C29.3646%2013.8684%2029.0507%2012.9552%2028.454%2012.3455C27.8378%2011.7152%2026.7502%2011.2321%2024.8063%2011.0216C22.8856%2010.8136%2021.975%2011.1998%2021.5345%2011.7049C21.187%2012.1014%2020.97%2012.7485%2020.9688%2013.7431V13.7702C20.9688%2014.1121%2020.9959%2014.4966%2021.0501%2014.9237ZM18.9499%2014.9237C19.0041%2014.4966%2019.0312%2014.1117%2019.0312%2013.7689V13.7431C19.03%2012.7485%2018.813%2012.1014%2018.4655%2011.7049C18.025%2011.1998%2017.1144%2010.8136%2015.1937%2011.0216C13.2498%2011.2321%2012.1622%2011.7152%2011.546%2012.3455C10.9493%2012.9552%2010.6354%2013.8684%2010.6354%2015.3409C10.6354%2016.9051%2010.8615%2017.8287%2011.3562%2018.3905C11.8276%2018.9253%2012.7563%2019.3606%2014.7881%2019.3606C16.351%2019.3606%2017.2449%2018.8517%2017.8158%2018.149C18.4293%2017.3947%2018.7742%2016.289%2018.9499%2014.9237Z'%20fill='currentColor'/%3e%3c/svg%3e",zP="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",UP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37%2020.034C27.8809%2020.5837%2020.5808%2027.8809%2020.0326%2037H19.966C19.4163%2027.8809%2012.1177%2020.5837%203%2020.034V19.9674C12.1191%2019.4163%2019.4163%2012.1191%2019.966%203H20.0326C20.5822%2012.1191%2027.8809%2019.4163%2037%2019.9674V20.034Z'%20fill='currentColor'/%3e%3c/svg%3e",qP="/assets/kimi-for-coding-eVEHug_h.svg",WP="/assets/llmapi-detailed-Pup_107f.svg",KP="data:image/svg+xml,%3csvg%20width='72'%20height='72'%20viewBox='0%200%2072%2072'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20fill='white'%20stroke='black'%20stroke-width='3'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2034L36%2040V52L24%2059L12%2052V40Z'/%3e%3cpath%20d='M36%2040L48%2034L60%2040V52L48%2059L36%2052V40Z'/%3e%3c/g%3e%3cg%20stroke='black'%20stroke-width='3'%20stroke-linecap='round'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2046L36%2040M24%2046V59'/%3e%3cpath%20d='M36%2040L48%2046L60%2040M48%2046V59'/%3e%3c/g%3e%3ccircle%20cx='36'%20cy='25'%20r='16'%20fill='white'%20stroke='black'%20stroke-width='3'/%3e%3crect%20x='27'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='29.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3crect%20x='38'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='40.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3c/svg%3e",GP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eLM%20Studio%3c/title%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h14.107a1.273%201.273%200%20100-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H22.04a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h14.106a1.274%201.274%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H15.38a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h14.106a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h9.698a1.273%201.273%200%20100-2.547h-9.698z'%20fill-opacity='.3'%3e%3c/path%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h10.287a1.274%201.274%200%20000-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H18.22a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H11.56a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h5.78a1.273%201.273%200%20100-2.547h-5.78z'%3e%3c/path%3e%3c/svg%3e",ZP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",YP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",XP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z'%20fill='currentColor'/%3e%3c/svg%3e",JP="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",QP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M32.8377%2017.282C33.2127%2016.25%2033.3072%2015.218%2033.2127%2014.1875C33.1197%2013.1571%2032.7447%2012.1251%2032.2752%2011.1876C31.4322%209.78209%2030.2127%208.6571%2028.8072%208.0001C27.3072%207.34461%2025.7127%207.15711%2024.1197%207.53211C23.3698%206.78212%2022.5253%206.12512%2021.5878%205.65713C20.6503%205.18913%2019.5253%205.00013%2018.4948%205.00013C16.8851%204.99074%2015.3125%205.48246%2013.9948%206.40712C12.6824%207.34311%2011.7449%208.6571%2011.2754%2010.1571C10.1504%2010.4376%209.21289%2010.9071%208.27539%2011.4696C7.4324%2012.1251%206.77541%2012.9696%206.21291%2013.8126C5.36992%2015.2195%205.08792%2016.8125%205.27542%2018.407C5.46399%2019.9968%206.11605%2021.496%207.1504%2022.718C6.79608%2023.7086%206.66795%2024.7659%206.77541%2025.8124C6.86991%2026.8444%207.2449%2027.8749%207.7129%2028.8124C8.55739%2030.2194%209.77538%2031.3444%2011.1824%2031.9999C12.6824%2032.6569%2014.2753%2032.8444%2015.8698%2032.4694C16.6198%2033.2194%2017.4628%2033.8749%2018.4003%2034.3444C19.3378%2034.8139%2020.4628%2034.9999%2021.4948%2034.9999C23.1043%2035.0097%2024.6769%2034.5185%2025.9947%2033.5944C27.3072%2032.6569%2028.2447%2031.3444%2028.7127%2029.8444C29.7719%2029.6432%2030.7682%2029.1934%2031.6197%2028.5319C32.4627%2027.8749%2033.2127%2027.1249%2033.6822%2026.1874C34.5251%2024.7819%2034.8071%2023.1875%2034.6196%2021.5945C34.4322%2020%2033.8697%2018.5015%2032.8377%2017.282ZM21.5878%2033.0304C20.0878%2033.0304%2018.9628%2032.5609%2017.9323%2031.7179C17.9323%2031.7179%2018.0253%2031.6234%2018.1198%2031.6234L24.1197%2028.1554C24.2862%2028.0803%2024.4196%2027.9469%2024.4947%2027.7804C24.5698%2027.636%2024.6021%2027.4731%2024.5877%2027.3109V18.875L27.1197%2020.375V27.3124C27.1455%2028.0547%2027.0215%2028.7945%2026.755%2029.4878C26.4885%2030.181%2026.085%2030.8134%2025.5687%2031.3473C25.0523%2031.8811%2024.4337%2032.3054%2023.7497%2032.5949C23.0658%2032.8843%2022.3305%2033.0314%2021.5878%2033.0304ZM9.49488%2027.8749C8.83789%2026.7499%208.55739%2025.4374%208.83789%2024.125C8.83789%2024.125%208.93239%2024.2195%209.02539%2024.2195L15.0253%2027.6874C15.1693%2027.7638%2015.3325%2027.7966%2015.4948%2027.7819C15.6823%2027.7819%2015.8698%2027.7819%2015.9628%2027.6874L23.2753%2023.4695V26.3749L17.1823%2029.9374C16.5506%2030.3042%2015.8527%2030.5427%2015.1287%2030.6393C14.4046%2030.7358%2013.6686%2030.6884%2012.9629%2030.4999C11.4629%2030.1249%2010.2449%2029.1874%209.49488%2027.8749ZM7.9004%2014.8445C8.56239%2013.7234%209.58826%2012.8627%2010.8074%2012.4056V19.532C10.8074%2019.718%2010.8074%2019.907%2010.9004%2020C10.9755%2020.1665%2011.1089%2020.2998%2011.2754%2020.375L18.5878%2024.5944L16.0573%2026.0944L10.0574%2022.625C9.41842%2022.2639%208.85742%2021.7797%208.40684%2021.2004C7.95627%2020.6211%207.62506%2019.9582%207.4324%2019.25C7.05741%2017.8445%207.1504%2016.157%207.9004%2014.8445ZM28.6197%2019.625L21.3073%2015.407L23.8377%2013.9071L29.8377%2017.375C30.7752%2017.9375%2031.5252%2018.6875%2031.9947%2019.625C32.4642%2020.5625%2032.7447%2021.5945%2032.6502%2022.7195C32.5603%2023.7755%2032.1699%2024.7837%2031.5252%2025.6249C30.8697%2026.4694%2030.0252%2027.1249%2028.9947%2027.4999V20.375C28.9947%2020.1875%2028.9947%2020%2028.9002%2019.907C28.9002%2019.907%2028.8072%2019.718%2028.6197%2019.625ZM31.1502%2015.875C31.1502%2015.875%2031.0572%2015.782%2030.9627%2015.782L24.9627%2012.3126C24.7752%2012.2196%2024.6822%2012.2196%2024.4947%2012.2196C24.3072%2012.2196%2024.1197%2012.2196%2024.0252%2012.3126L16.7128%2016.532V13.6251L22.8073%2010.0626C23.7448%209.50009%2024.7752%209.31259%2025.9002%209.31259C26.9322%209.31259%2027.9627%209.68759%2028.9002%2010.3446C29.7447%2011.0001%2030.4947%2011.8446%2030.8697%2012.7821C31.2447%2013.7196%2031.3377%2014.8445%2031.1502%2015.875ZM15.4003%2021.125L12.8699%2019.625V12.5946C12.8699%2011.5626%2013.1503%2010.4376%2013.7128%209.59459C14.2753%208.6571%2015.1198%208.0001%2016.0573%207.53211C17.0127%207.05249%2018.0956%206.88812%2019.1503%207.06261C20.1823%207.15711%2021.2128%207.62511%2022.0573%208.2821C22.0573%208.2821%2021.9628%208.3751%2021.8698%208.3751L15.8698%2011.8446C15.7033%2011.9197%2015.57%2012.0531%2015.4948%2012.2196C15.4003%2012.4071%2015.4003%2012.5001%2015.4003%2012.6876V21.125ZM16.7128%2018.125L19.9948%2016.25L23.2753%2018.125V21.875L19.9948%2023.75L16.7128%2021.875V18.125Z'%20fill='currentColor'/%3e%3c/svg%3e",eD="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20fill='currentColor'/%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.6%207.43108L16.0037%2010.6622V4.20001L21.6%207.43108Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20fill='currentColor'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.4909%2016.7109L15.8945%2013.4798V19.942L21.4909%2016.7109Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3c/svg%3e",tD="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cimage%20width='24'%20height='24'%20xlink:href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABcCAYAAAAMLblmAAAACXBIWXMAAAAAAAAAAQCEeRdzAAAHhklEQVR4nO1d21HjSBRtjJhvMhgtxlX8DRsBJgIggjERwESAiWAgAjwRYCJAGwHMH1U8VhvBst+89hxzRRkwuG+rJet1qlwSM1KrdXR1+nb37as5UzCEYbi4sLAQPj4+rs7NzX17enpaxI/7i8khs6xfWuA+1oNZV4IkB0Gwit0NEN1FpVaxHf0fyB5t8W8zrKF/zIT0hGiQuoc/uR1ZcdXI/Qi5kk6yW63WDsjdTYiuI3IhfXl5uQuSd7C7mcf1io5MSYdlh/Pz83sgvJfldcqGTEgflxH8WVsZ+QjeSRcpOTIld+2yhFfSl5aWfoLwXZ9lVhFeSKd2Q06O6WP7KG8CbvlD+TEeavz2P/HvIbfsRJkSyFlq0kVOjo3HmwWJEcr8jd0IvdPzi4uL2Pbcsc7WqMOFcrq+6uULqUiHnOzgpg58VESI/vXw8DCM4/jWtRw5N5LfqG7tdpuuKn/fPVQ1NZxJB+F7IKqf8vqUjMP7+/uDNERPw/X19RCbId6CPlzYLvbZEw6zut40OJHugfBcyH4LXCvGZsAfrL9nZkS+mnQPhA+h0z80Op0FYP0DWP4Q+r8rY0C5QUU6NTwF4THO3b66uoocz/cOecv6IH8A2Tk1OVm9Nenipbg2modoIPt5SokGIjt/4B77eVi9Fen0w6WXqQW1ex/W7cXDyRqoZ7/T6QwfHx/pAodZXceKdMdXL0aHaevy8vJcXasZgvWFja1nKTdTSWfD6XDxGI3l+qwbS1dQbkh8Vr3sT0kXHe8ryyw14QnGiD/1TfynpDvoeCUIT8CGH8Rv+ZaaD0l3kJVbanhVCE+QWDyIPzOexpcmkk5vReuP00spW6NpCxIPqd3Cm3/qo7yJpHOKTVnOYVncQlewU9dutw+xu5O2rHek08qx6SnKiNGlrsXEBe8TsruWtmF9R7rWytlwpqlA2QB+ttF5OktTxivSHax8ULWGcxrYbqWVmVekK62c7uG+64XLDI4jgStOiDh5M2/lxToYCLr2q25WnoD+O7yZQ9fBsRfSZVDf9snFQRAMXC5YFXACBtZOiVFb+7ila+YPo7paeYI01j4inTPo2HRtT6qrlr+Fq7WPSJfJWitw1r7uVp6A1g5ZPjHKKINEXjZsT2CYhOYCVQeMcABO9KSzh5WsepgGSEukr1p1IcMDnIa0lpiAei7haFOB41TRVjWCSmICWYZidTDeiL9ca1VlgJdzjcRQXjSDN5G6RjWAhARaHx/g4ND24FarFTvUqfKQ8RhrXQ/wlL7aPqWqTlL4gIRxW6lGYLvKjY1oumpVGxLabUe6sZwHhbQUMjqrQLDmh6TbWvp/ztWpASAvt7YybU068K9zjeoBlaU38ABYeUN6kdGQ7glMjaLRdNVgTYMPYT/gZSxJT9ZqNpgMTVaPwNbV0QwX1BGanj0tPTZ2PanQvUq1QGh7IIcB/rE9eGVlJWzG0yfDdtyFCGSgxurgh4eHrnleh9lgDJ1O5yXvmA0oL9YDWcwg51KpqkPLS3B/f38+Pz9vdTDeiDWnWlUcUIsN1SSGhBHExqIh4AQ251SLuh50VtBm2kh6pJxYtYpCDYKgZyS7RIOXxXD6YCOj0HVcgDEyDekCbcwLMSKdOVag67Yr6bqNxDzDIZ5/hBHpouuRsYxnZOYIbPrai1UNmnDEcbyMMqKRPLFtEJjYEg8511wtBUW6+HS4jgNZiWHTKCzW3dolnj90OfeFdJEYBodaeTF1tnbRcucUJa8mMSAxQ8mJawNmGeWFf7hevKwQRQhdz39FukSgRsayQWVaV/ipJ0XKVpQ1XD2WcbybruNyc00Pi0kbUI8/6yIzkpwhFd6RrrV2IKyLzDjmvnmHiRPTWmunzOBBnV9fX1d2lYZj7puJmEi6Y/KBg06n87uKQaYpcphNxIchGA6rgheZcGxlZaUySXYIDnnklmRH/PZt7B4rygvv7u5Oq0K8JN/3nkDt02Aj5qiVDpNmJK0SxCeE5544jYDM7OL14oxRqCi31MRnnQ9+KumUGTSQW9BrvmaawXoSf0aJkqzOpYB8PCXTFLBWsYyypoZ+uLYF50M6hn/bv7m5KfzSdtwjZZQTNJmGGVoHkDILM3zV0CUBAZOwgfjNL1++FDKbneg37yuXtFiqqF3mogXxxpH4VcjN30WzevmKwE+TYwSbOlQ6DfEErV7Govf59riU4QPSw+Q9dPO+tlN8elrizbNVHYF8nr/PfAN5yY5Y9s4sP1DivCjAA/FEiN8RZIdkDLB/koWnQ6s2z1+C6ZkCxOKnWolB4jnQZfxoYo8/lMf9SPIQRIxA0wwbj39yByR/w3azaF+ETL38hZaJGz337Nt25fXfY8gfl4Dzo1KMpTfPod1vwaUnoSxcsF6GMit4WXOUw+cNFqf1Dsv0AVmvC71E56Pmg4Gfw/vqOpkvze2jHmVEZksaafXyKZu+Kcjny4qCTNeRitb35PNlfdOQP0Iui3cnkK8dKq4Ucl0xnZDPffYM4XF8F9ewUH501pjZMvXky4ncl3EQPoQ1zSq1sqIQuQHE44mSv6Xbviodnq9GOj/m+Y0o/VvxPy8IndI+RM9sAAAAAElFTkSuQmCC'/%3e%3c/svg%3e",nD="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.50002L17.4088%2011.1913H5.81625L8.5375%207.50002H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.50002L16.58%2032.5H5L23.42%207.50002H35Z'%20fill='currentColor'/%3e%3c/svg%3e",rD="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.5L17.4088%2011.1912H5.81625L8.5375%207.5H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.5L16.58%2032.5H5L23.42%207.5H35Z'%20fill='currentColor'/%3e%3c/svg%3e",sD=Object.assign({"../assets/provider-logos/anthropic.svg":HP,"../assets/provider-logos/bailian-coding-plan.svg":FP,"../assets/provider-logos/cursor.svg":BP,"../assets/provider-logos/evroc.svg":VP,"../assets/provider-logos/github-copilot.svg":$P,"../assets/provider-logos/gocode.svg":zP,"../assets/provider-logos/google.svg":UP,"../assets/provider-logos/kimi-for-coding.svg":qP,"../assets/provider-logos/llmapi-detailed.svg":WP,"../assets/provider-logos/llmapi.svg":KP,"../assets/provider-logos/lmstudio.svg":GP,"../assets/provider-logos/minimax-cn-coding-plan.svg":ZP,"../assets/provider-logos/minimax-coding-plan.svg":YP,"../assets/provider-logos/nano-gpt.svg":XP,"../assets/provider-logos/ollama.svg":JP,"../assets/provider-logos/openai.svg":QP,"../assets/provider-logos/openrouter.svg":eD,"../assets/provider-logos/wafer.ai.svg":tD,"../assets/provider-logos/zai-coding-plan.svg":nD,"../assets/provider-logos/zhipuai-coding-plan.svg":rD}),Fp=new Map,ih=new Map([["codex","openai"],["openai-codex","openai"],["openai_codex","openai"],["openai.codex","openai"],["chatgpt","openai"],["claude","anthropic"],["gemini","google"],["evroc-ai","evroc"],["evrocai","evroc"],["ollama-cloud","ollama"],["wafer-ai","wafer.ai"],["wafer","wafer.ai"]]),oD=e=>(e??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),iD=e=>{const t=oD(e);if(!t)return[];const n=t.replace(/[^a-z0-9_\-./:]/g,""),r=n.split(/[/:]/)[0]||n,s=r.split(/[-_.]/)[0]||r,o=[ih.get(n),ih.get(r),ih.get(s),t.includes("codex")?"openai":void 0,n,r,s].filter(i=>!!(i&&i.length>0));return[...new Set(o)]};for(const[e,t]of Object.entries(sD)){const n=e.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&t&&Fp.set(n[1].toLowerCase(),t)}function I1(e){const t=iD(e),n=t.find(d=>Fp.has(d))??null,r=t[0]??null,s=!!n,o=n?Fp.get(n)??null:null,[i,a]=H.useState(s?"local":"remote");H.useEffect(()=>{a(s?"local":"remote")},[s,n,r]);const l=H.useCallback(()=>{a(d=>d==="local"&&s?"remote":"none")},[s]);return!n&&!r?{src:null,onError:l,hasLogo:!1}:i==="local"&&o?{src:o,onError:l,hasLogo:!0}:i==="remote"&&r?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}}const Wo=({providerId:e,alt:t,className:n,onError:r})=>{const{src:s,onError:o,hasLogo:i}=I1(e),a=p.useCallback(()=>{o(),r?.()},[o,r]);return!i||!s?null:c.jsx("img",{src:s,alt:t||`${e} logo`,className:R("dark:invert object-contain",n),loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:a})},Dy=Et()(Gd(e=>({collapsedSections:{},toggleSection:t=>e(n=>{const r={...n.collapsedSections};return r[t]?delete r[t]:r[t]=!0,{collapsedSections:r}})}),{name:"model-picker-collapsed-sections",version:1})),Oy=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},E1=(e,t,n)=>{const r=Oy(t.limit,"context"),s=Oy(t.limit,"output"),o=r??n?.limit?.context,i=s??n?.limit?.output;return o===void 0&&i===void 0?n:{...n??{id:typeof t.id=="string"?t.id:"",providerId:e,name:typeof t.name=="string"?t.name:void 0},limit:{...n?.limit,...o!==void 0?{context:o}:{},...i!==void 0?{output:i}:{}}}},_s=e=>typeof e=="string"?e.trim():"",Hy=(e,t)=>!t||t<=0||e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`,aD={ai:"AI",api:"API",ernie:"ERNIE",glm:"GLM",gpt:"GPT",it:"IT",lfm:"LFM",lm:"LM",oss:"OSS",pdf:"PDF",rp:"RP",slerp:"SLERP",tars:"TARS",ui:"UI",vl:"VL",vlm:"VLM",aion:"Aion",anthropic:"Anthropic",chatgpt:"ChatGPT",claude:"Claude",codex:"Codex",codestral:"Codestral",command:"Command",deepseek:"DeepSeek",gemini:"Gemini",gemma:"Gemma",grok:"Grok",hunyuan:"Hunyuan",kimi:"Kimi",llama:"Llama",minimax:"MiniMax",mistral:"Mistral",mixtral:"Mixtral",nemotron:"Nemotron",openai:"OpenAI",qwen:"Qwen",rekaai:"RekaAI"},Fy=e=>e?e[0].toUpperCase()+e.slice(1).toLowerCase():"",cD=e=>{const t=e.startsWith("~")?e.slice(1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t},lD=e=>{const t=e.lastIndexOf(":");return t<=0||t>=e.length-1?{base:e,suffix:""}:{base:e.slice(0,t),suffix:e.slice(t+1)}},dD=e=>{const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").split(/[-_\s]+/).map(r=>r.trim()).filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){const s=t[r],o=t[r+1],i=t[r+2];if(/^(19|20)\d{2}$/.test(s)&&/^\d{2}$/.test(o??"")&&/^\d{2}$/.test(i??"")){n.push(`${s}-${o}-${i}`),r+=2;continue}if(/^\d$/.test(s)&&/^\d$/.test(o??"")){n.push(`${s}.${o}`),r+=1;continue}n.push(s)}return n},uD=e=>{const t=e.toLowerCase(),n=aD[t];if(n)return n;const r=t.match(/^qwen(\d(?:\.\d+)?)$/);return r?`Qwen${r[1]}`:/^o\d/.test(t)?t:/^v\d/.test(t)?`V${e.slice(1).toUpperCase()}`:/^\d+[on]$/.test(t)?t:/^[a-z]\d+[a-z]?$/.test(t)?t.toUpperCase():/^\d+(?:x\d+)?[a-z]+$/.test(t)?t.replace(/[a-z]+$/i,s=>s.toUpperCase()):/^\d+(?:\.\d+)?[a-z]$/.test(t)?t.replace(/[a-z]$/i,s=>s.toUpperCase()):/^[a-z]+\d+(?:\.\d+)?[a-z]*$/.test(t)?Fy(t).replace(/([a-z])(\d)/i,"$1$2"):Fy(e)},fD=e=>{const t=[...e];return t[0]==="GPT"&&t[1]&&/^(?:\d|\d+[a-z]|OSS$)/i.test(t[1])&&t.splice(0,2,`GPT-${t[1]}`),t[0]==="GLM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`GLM-${t[1]}`),t[0]==="LFM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`LFM${t[1]}`),t[0]==="Qwen"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`Qwen${t[1]}`),t},hD=e=>{const t=_s(e).toLowerCase();return t?t==="free"||t==="thinking"?t:q3(t):""},q3=e=>{const t=_s(e);if(!t)return"";const{base:n,suffix:r}=lD(cD(t)),s=fD(dD(n).map(uD));if(s.length>=2){const l=s[s.length-1],d=s[s.length-2];l==="Reasoning"&&d==="Non"&&s.splice(s.length-2,2,"(Non-Reasoning)")}const o=s[s.length-1];/^(19|20)\d{2}-\d{2}-\d{2}$/.test(o??"")&&(s[s.length-1]=`(${o})`);const i=s.join(" ").replace(/\s+\(/g," (").trim(),a=hD(r);return a?`${i} (${a})`:i},_1=(e,t,n={})=>{const r=_s(e?.name);if(r)return Hy(r,n.maxLength);const s=_s(e?.id)||_s(t);return s?Hy(q3(s),n.maxLength):n.fallbackLabel??""},pD=(e,t)=>{const n=e?.models;if(!(!n||!t))return Array.isArray(n)?n.find(r=>_s(r.id)===t):n[t]},j1=(e,t,n={})=>{const r=_s(t),s=pD(e,r);return _1(s,r,n)},mD=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),gD=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),Bl=e=>_1(e,void 0,{maxLength:40}),yD=e=>{if(typeof e!="number"||Number.isNaN(e))return"";if(e===0)return"0";const t=mD(e);return t.endsWith(".0")?t.slice(0,-2):t},By=e=>typeof e!="number"||!Number.isFinite(e)?"—":gD(e),vD=e=>e?!!(e.tool_call||e.reasoning||e.cost?.input!==void 0||e.cost?.output!==void 0||(e.modalities?.input?.length??0)>0||(e.modalities?.output?.length??0)>0):!1,xD=({metadata:e,active:t,labels:n,children:r})=>{const[s,o]=p.useState(!1);if(p.useEffect(()=>{if(!t){o(!1);return}const d=window.setTimeout(()=>o(!0),450);return()=>window.clearTimeout(d)},[t]),!vD(e))return r;const i=e?.modalities?.input??[],a=e?.modalities?.output??[],l=[e?.tool_call?n.capabilityToolCalling:null,e?.reasoning?n.capabilityReasoning:null].filter(Boolean);return c.jsxs(wt,{delayDuration:0,open:t&&s,onOpenChange:()=>{},children:[c.jsx(St,{asChild:!0,children:r}),t&&s?c.jsxs(Ct,{side:"right",align:"center",sideOffset:8,className:"z-[999] p-2 typography-micro space-y-1.5 shadow-md border pointer-events-none",children:[l.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.capabilities||"Capabilities",": "]}),c.jsx("span",{className:"font-medium",children:l.join(", ")})]}):null,i.length>0||a.length>0?c.jsxs("div",{className:"space-y-0.5",children:[i.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.input||"Input",": "]}),c.jsx("span",{className:"font-medium",children:i.join(", ")})]}):null,a.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.output||"Output",": "]}),c.jsx("span",{className:"font-medium",children:a.join(", ")})]}):null]}):null,e?.cost?.input!==void 0||e?.cost?.output!==void 0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.costPerMillion||"Cost / 1M tokens",": "]}),c.jsxs("span",{className:"font-medium",children:[By(e?.cost?.input)," / ",By(e?.cost?.output)]})]}):null]}):null]})},bD=p.memo(({store:e,index:t,children:n})=>{const[r,s]=p.useState(()=>e.getSnapshot()===t);return p.useEffect(()=>{const o=()=>s(e.getSnapshot()===t);return o(),e.subscribeIndex(t,o)},[t,e]),c.jsx(c.Fragment,{children:n(r)})}),wD=({id:e,disabled:t=!1,children:n})=>{const{attributes:r,listeners:s,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:l,isDragging:d}=km({id:e,disabled:t});return c.jsx("div",{ref:o,style:{transform:Mm.Transform.toString(a),transition:l},className:R(d&&"opacity-60"),children:n({attributes:r,listeners:s,setActivatorNodeRef:i,isDragging:d})})},SD=({entry:e,keyPrefix:t,showProviderLogo:n,rowIndex:r,dragHandleProps:s,selectionStore:o,modelsMetadata:i,selectedModel:a,disabled:l=!1,rowClassName:d,renderVersion:f,tooltipsEnabled:u=!0,labels:h,selectionCount:m,isFavorite:g,onToggleFavorite:x,onSelect:b,selectIndex:S,itemRefs:y,lastMousePositionRef:v,keyboardOwnsSelectionRef:C,reorderFavoriteAriaLabel:w,reorderFavoriteTitle:I,renderRowEnd:E})=>{const T=E1(e.providerID,e.model,i.get(`${e.providerID}/${e.modelID}`)),A=yD(T?.limit?.context),j=m?.(e)??0,k=a?.providerID===e.providerID&&a.modelID===e.modelID,_=g?.(e)??!1,M=L=>{const O={x:L.clientX,y:L.clientY},N=v.current,D=!N||N.x!==O.x||N.y!==O.y;v.current=O,!(C.current&&!N)&&(C.current&&!D||(C.current&&D&&(C.current=!1),S(r)))};return c.jsx(bD,{store:o,index:r,renderVersion:f,children:L=>{const O=c.jsxs("div",{ref:N=>{y.current[r]=N},role:"option","aria-selected":k,"aria-disabled":l||void 0,tabIndex:-1,onClick:()=>{l||b(e)},onKeyDown:N=>{l||(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),b(e))},onMouseEnter:M,onMouseMove:M,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!l&&(L?"bg-interactive-selection":"hover:bg-interactive-hover/50"),l&&"cursor-not-allowed opacity-60",d),children:[c.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[s?c.jsx("button",{type:"button",ref:s.setActivatorNodeRef,...s.attributes,...s.listeners,disabled:l,onClick:N=>{N.preventDefault(),N.stopPropagation()},className:"model-favorite-drag-handle flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground hover:text-foreground disabled:pointer-events-none","aria-label":w,title:I,children:c.jsx($,{name:"draggable",className:"size-3.5"})}):null,n?c.jsx(Wo,{providerId:e.providerID,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"font-medium truncate",children:Bl(e.model)}),A?c.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:A}):null]}),j>0?c.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["x",j]}):null,E?.(e,{isHighlighted:L,isSelected:k}),k?c.jsx($,{name:"check",className:"h-4 w-4 text-primary flex-shrink-0"}):null,x?c.jsx("button",{type:"button",disabled:l,onClick:N=>{N.preventDefault(),N.stopPropagation(),x(e)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80 flex-shrink-0 disabled:pointer-events-none",_?"text-primary":"text-muted-foreground"),"aria-label":_?h.unfavorite:h.favorite,title:_?h.unfavorite:h.favorite,children:c.jsx($,{name:_?"star-fill":"star",className:"h-3.5 w-3.5"})}):null]});return c.jsx(xD,{metadata:T,active:u&&L,labels:h,children:O})}},`${t}-${e.providerID}-${e.modelID}`)},CD=(e=0)=>{let t=e;const n=new Set,r=new Map,s=o=>{const i=r.get(o);if(i)for(const a of i)a()};return{getSnapshot:()=>t,subscribe:o=>(n.add(o),()=>{n.delete(o)}),subscribeIndex:(o,i)=>{let a=r.get(o);return a||(a=new Set,r.set(o,a)),a.add(i),()=>{a?.delete(i),a&&a.size===0&&r.delete(o)}},set:o=>{if(t===o)return;const i=t;t=o,s(i),s(o);for(const a of n)a()}}},kD=48,MD=32,ID=24;function ED({providers:e,favoriteModels:t,recentModels:n,searchQuery:r,hiddenModels:s=[],allowedProviderIds:o,isModelAllowed:i,stickyHeaders:a=!0,scrollRef:l,collapsedSections:d}){const f=p.useRef(0),u=p.useMemo(()=>o?new Set(o):null,[o]),h=p.useMemo(()=>new Map(e.map(E=>[E.id,E])),[e]),m=p.useCallback((E,T)=>s.some(A=>A.providerID===E&&A.modelID===T),[s]),g=p.useCallback((E,T)=>{const A=r.trim().toLowerCase();return A?E.toLowerCase().includes(A)||T.toLowerCase().includes(A):!0},[r]),x=p.useMemo(()=>t.filter(({model:E,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const j=h.get(T)?.name||T;return g(Bl(E),j)}),[u,t,m,i,g,h]),b=p.useMemo(()=>n.filter(({model:E,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const j=h.get(T)?.name||T;return g(Bl(E),j)}),[u,m,i,g,h,n]),S=p.useMemo(()=>e.filter(E=>!u||u.has(E.id)).map(E=>{const A=(Array.isArray(E.models)?E.models:[]).filter(j=>{const k=typeof j.id=="string"?j.id:"";return!k||m(E.id,k)||i&&!i(E.id,k)?!1:g(Bl(j),E.name||E.id)});return{...E,models:A}}).filter(E=>E.models.length>0),[u,m,i,g,e]),y=p.useMemo(()=>[...x.length>0?["favorites"]:[],...b.length>0?["recent"]:[],...S.map(E=>`provider:${E.id}`)],[x.length,S,b.length]),v=p.useCallback(E=>{const A=E.scrollTop>1?Math.min(MD+E.scrollTop,kD):0;f.current=A,E.style.setProperty("--scroll-shadow-top-size",`${A}px`),E.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(A-8,0),ID)}px`)},[]),C=p.useCallback(E=>{E.target.closest("[data-overlay-scrollbar-thumb], [data-model-picker-sticky-header]")||E.clientY-E.currentTarget.getBoundingClientRect().top>=f.current||(E.preventDefault(),E.stopPropagation())},[]);p.useLayoutEffect(()=>{a&&l.current&&v(l.current)},[l,a,v,y]);const w=p.useMemo(()=>{const E=[];return d.has("favorites")||x.forEach(T=>E.push(T)),d.has("recent")||b.forEach(T=>E.push(T)),S.forEach(T=>{d.has(`provider:${T.id}`)||T.models.forEach(A=>E.push({model:A,providerID:T.id,modelID:A.id}))}),E},[d,x,S,b]),I=p.useMemo(()=>new Map(x.map(E=>[`${E.providerID}:${E.modelID}`,E])),[x]);return{allowedProviderSet:u,providerById:h,filteredFavorites:x,filteredRecents:b,filteredProviders:S,visibleSectionKeys:y,flatModelList:w,favoriteLookup:I,syncStickyFade:v,blockStickyFadeInteraction:C}}const Vy=32,_D=(e,t)=>{if(!t)return;if(!e){t.scrollIntoView({block:"nearest"});return}const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),s=r.top-n.top+e.scrollTop,o=s+r.height,i=e.scrollTop,a=i+e.clientHeight,l=i+Vy,d=s<l?s-Vy:o>a?o-e.clientHeight:i,f=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.max(0,Math.min(d,f))},jD=({providers:e,favoriteModels:t,recentModels:n,modelsMetadata:r,searchQuery:s,onSearchQueryChange:o,onSelect:i,labels:a,selectedModel:l,hiddenModels:d=[],allowedProviderIds:f,isModelAllowed:u,includeNotSelected:h=!1,onSelectNone:m,selectionCount:g,disabled:x=!1,maxHeightClassName:b="max-h-[min(400px,calc(100dvh-12rem))] flex-1",maxHeightStyle:S,sectionHeaderClassName:y,rowClassName:v,stickyHeaders:C=!0,autoFocus:w=!0,onEscape:I,isFavorite:E,onToggleFavorite:T,renderRowEnd:A,onActiveKeyDown:j,onActiveEntryChange:k,onVariantKey:_,onReorderFavorite:M,reorderFavoriteAriaLabel:L,reorderFavoriteTitle:O,renderVersion:N,tooltipsEnabled:D=!0})=>{const W=p.useRef(null);W.current||(W.current=CD());const z=W.current,X=p.useRef([]),F=p.useRef(null),U=p.useRef(!1),P=p.useRef(null),q=Dy(ge=>ge.collapsedSections),B=Dy(ge=>ge.toggleSection),ee=p.useMemo(()=>new Set(Object.keys(q).filter(ge=>q[ge])),[q]),G=bm(wa(w8,{activationConstraint:{distance:8}})),{filteredFavorites:K,filteredRecents:se,filteredProviders:le,flatModelList:oe,favoriteLookup:ue,syncStickyFade:ye,blockStickyFadeInteraction:we}=ED({providers:e,favoriteModels:t,recentModels:n,searchQuery:s,hiddenModels:d,allowedProviderIds:f,isModelAllowed:u,stickyHeaders:C,scrollRef:F,collapsedSections:ee}),Me=oe.length>0,He=!!M&&s.trim().length===0&&K.length>1;p.useEffect(()=>{z.set(0)},[s,z]);const Ae=p.useCallback(ge=>{z.set(ge),k?.(oe[ge])},[oe,k,z]),Ge=p.useCallback(ge=>{const Ze=oe.length;if(Ze===0)return;U.current=!0,P.current=null;const ie=(z.getSnapshot()+ge+Ze)%Ze;z.set(ie),k?.(oe[ie]),requestAnimationFrame(()=>_D(F.current,X.current[ie]))},[oe,k,z]);p.useEffect(()=>{k?.(oe[z.getSnapshot()])},[oe,k,z]);const et=p.useCallback(ge=>{if(!ge.defaultPrevented){if(ge.stopPropagation(),ge.key==="ArrowLeft"||ge.key==="ArrowRight"){const Ze=oe[z.getSnapshot()];if(Ze&&_?.(ge,Ze))return}if(j?.(ge,oe[z.getSnapshot()]),!ge.defaultPrevented){if(ge.key==="ArrowDown"){ge.preventDefault(),Ge(1);return}if(ge.key==="ArrowUp"){ge.preventDefault(),Ge(-1);return}if(ge.key==="Enter"){ge.preventDefault();const Ze=oe[z.getSnapshot()];Ze&&!x&&i(Ze);return}ge.key==="Escape"&&(ge.preventDefault(),I?.())}}},[x,oe,Ge,j,I,i,_,z]),Xe=R("typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 px-2 py-1.5",C&&"sticky top-0 z-20",y);let te=0;const Q=(ge,Ze,Be,ie,ke)=>c.jsx(SD,{entry:ge,keyPrefix:Ze,showProviderLogo:Be,rowIndex:ie,dragHandleProps:ke,selectionStore:z,modelsMetadata:r,selectedModel:l,disabled:x,rowClassName:v,renderVersion:N,tooltipsEnabled:D,labels:a,selectionCount:g,isFavorite:E,onToggleFavorite:T,onSelect:i,selectIndex:Ae,itemRefs:X,lastMousePositionRef:P,keyboardOwnsSelectionRef:U,reorderFavoriteAriaLabel:L,reorderFavoriteTitle:O,renderRowEnd:A},`${Ze}-${ge.providerID}-${ge.modelID}`),me=ge=>{if(!M)return;const{active:Ze,over:Be}=ge;if(!Be||Ze.id===Be.id)return;const ie=ue.get(String(Ze.id)),ke=ue.get(String(Be.id));!ie||!ke||M(ie,ke)},Se=ge=>ee.has(ge),_e=ge=>B(ge),Fe=(ge,Ze,Be)=>{const ie=Se(ge),ke=ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),_e(ge))};return c.jsxs("button",{type:"button","aria-expanded":!ie,"data-model-picker-sticky-header":C?"true":void 0,className:R(Xe,"w-full text-left"),onClick:()=>_e(ge),onKeyDown:ke,children:[Ze,c.jsx("span",{className:"min-w-0 truncate",children:Be}),c.jsx("span",{className:"ml-auto flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",children:c.jsx($,{name:ie?"arrow-right-s":"arrow-down-s",className:"size-4"})})]})},ht=()=>le.map(ge=>{const Ze=Se(`provider:${ge.id}`);return c.jsxs("div",{className:"relative overflow-hidden",children:[Fe(`provider:${ge.id}`,c.jsx(Wo,{providerId:ge.id,className:"h-3.5 w-3.5 flex-shrink-0"}),ge.name||ge.id),Ze?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:ge.models.map(Be=>{const ie={model:Be,providerID:ge.id,modelID:Be.id},ke=te;return te+=1,Q(ie,ge.id,!1,ke)})})]},ge.id)});return c.jsxs("div",{className:"flex flex-col min-h-0",children:[c.jsx("div",{className:"p-2 border-b",children:c.jsx(Uo,{placeholder:a.searchPlaceholder,value:s,onChange:ge=>o(ge.target.value),onKeyDown:et,autoFocus:w,className:"h-8 typography-meta"})}),c.jsx("div",{className:"relative flex flex-col min-h-0",onMouseDown:we,onPointerDown:we,children:c.jsxs(Yn,{ref:F,className:R(b,"p-2 space-y-3 min-h-0"),style:S,onScroll:ge=>{C&&ye(ge.currentTarget)},children:[h&&m?c.jsx("div",{className:"pb-1 border-b mb-1",children:c.jsxs("button",{type:"button",disabled:x,onClick:m,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!x&&"hover:bg-interactive-hover/50",x&&"cursor-not-allowed opacity-60",v),children:[c.jsx("span",{className:"font-medium text-muted-foreground",children:a.notSelected||"Not selected"}),l?null:c.jsx($,{name:"check",className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]})}):null,K.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("favorites",c.jsx($,{name:"star-fill",className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),a.favorites),Se("favorites")?null:He?c.jsx(wm,{sensors:G,collisionDetection:Sm,onDragEnd:me,children:c.jsx(Cm,{items:K.map(ge=>`${ge.providerID}:${ge.modelID}`),strategy:$5,children:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ge=>{const Ze=`${ge.providerID}:${ge.modelID}`,Be=te;return te+=1,c.jsx(wD,{id:Ze,disabled:x,children:ie=>Q(ge,"favorite",!0,Be,ie)},`favorite-${Ze}`)})})})}):c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ge=>{const Ze=te;return te+=1,Q(ge,"favorite",!0,Ze)})})]}):null,se.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("recent",c.jsx($,{name:"history",className:"h-3.5 w-3.5 flex-shrink-0"}),a.recent),Se("recent")?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:se.map(ge=>{const Ze=te;return te+=1,Q(ge,"recent",!0,Ze)})})]}):null,ht(),Me?null:c.jsx("div",{className:"p-4 text-center typography-meta text-muted-foreground",children:a.noResults})]})})]})};function W3(){const e=qe();return H.useMemo(()=>({ensureSessionRenderable:async t=>{if(!t)return;if(e.getState().selectedSessionId!==t){await e.select(t);return}await e.ensureHydrated(t)},syncSession:async t=>{if(!t)return;e.getState().selectedSessionId!==t&&await e.select(t)}}),[e])}const TD=()=>{const e=We(a=>a.providers),t=re(a=>a.favoriteModels),n=re(a=>a.recentModels),r=re(a=>a.hiddenModels),s=p.useCallback((a,l)=>r.some(d=>d.providerID===a&&d.modelID===l),[r]),o=p.useMemo(()=>t.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null),[t,e,s]),i=p.useMemo(()=>n.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!t.some(d=>d.providerID===a&&d.modelID===l)),[n,e,t,s]);return{favoriteModelsList:o,recentModelsList:i}},AD=typeof window<"u"?p.useLayoutEffect:p.useEffect,ND=(e,t=[])=>{const[n,r]=p.useState(!1),s=p.useCallback(()=>{const o=e.current;if(!o)return;const i=o.scrollWidth>o.clientWidth+1;r(i)},[e]);return AD(()=>{s()},[s,...t]),p.useEffect(()=>{const o=e.current;if(!o||typeof ResizeObserver>"u")return;const i=new ResizeObserver(()=>{s()});return i.observe(o),()=>i.disconnect()},[s,e]),p.useEffect(()=>{if(typeof window>"u")return;const o=()=>s();return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[s]),n},T1=(e,t)=>t?[void 0,...e]:[...e],K3=e=>e??"default",LD=(e,t)=>t===0?50:e/t*100,Qc=10,RD={side:"none",align:"none",fallbackAxisSide:"none"};function $y({options:e,value:t,prefix:n="",className:r,truncateAt:s}){const o=i=>s==null||i.length<=s?i:`${i.slice(0,s)}...`;return c.jsxs("span",{className:R("grid min-w-0 justify-items-start",r),children:[e.map(i=>c.jsxs("span",{className:"invisible col-start-1 row-start-1 overflow-hidden whitespace-nowrap","aria-hidden":"true",children:[n,o(Ur(i))]},K3(i))),c.jsxs("span",{className:"col-start-1 row-start-1 truncate",children:[n,o(t)]})]})}function PD({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=p.useRef(null),i=T1(e,s),[a,l]=p.useState(null),[d,f]=p.useState(null),u=a!==null?a:t,h=Math.max(0,i.findIndex(M=>M===u)),m=Math.max(0,i.length-1),g=m===0?0:h/m,x=d!==null?d:g,b=Ur(i[h]),S=p.useRef(null),y=p.useRef(t),v=p.useRef(i),C=p.useRef(n),w=p.useRef(r),I=p.useRef(null);p.useEffect(()=>{y.current=t},[t]),p.useEffect(()=>{v.current=i},[i]),p.useEffect(()=>{C.current=n},[n]),p.useEffect(()=>{w.current=r},[r]),p.useEffect(()=>{I.current=a},[a]),p.useEffect(()=>{a!==null&&a===t&&(l(null),f(null))},[t,a]);const E=p.useCallback(M=>{const L=o.current?.getBoundingClientRect(),O=v.current;if(!L||L.width<=0||O.length===0)return{next:O[0],clamped:0};const N=Math.min(Math.max((M-L.left)/L.width,0),1),D=H6(N,O.length);return{next:O[D],clamped:N}},[]),T=M=>{M.preventDefault();const{next:L,clamped:O}=E(M.clientX);l(L),f(O),I.current=L,S.current=M.pointerId;try{M.currentTarget.setPointerCapture(M.pointerId)}catch{}!w.current&&L!==y.current&&C.current(L)},A=M=>{if(S.current!==M.pointerId)return;M.preventDefault();const{next:L,clamped:O}=E(M.clientX);f(O),L!==I.current&&(l(L),I.current=L,!w.current&&L!==y.current&&C.current(L))},j=M=>{if(S.current!==M.pointerId)return;const{next:L,clamped:O}=E(M.clientX),N=I.current??L,D=d??O;S.current=null;try{M.currentTarget.hasPointerCapture(M.pointerId)&&M.currentTarget.releasePointerCapture(M.pointerId)}catch{}w.current?(w.current(N),f(D)):N!==y.current&&C.current(N),w.current||(l(null),f(null))},k=M=>{S.current===M.pointerId&&(S.current=null,l(null),f(null))},_=M=>{let L=null;if((M.key==="ArrowRight"||M.key==="ArrowUp")&&(L=Math.min(m,h+1)),(M.key==="ArrowLeft"||M.key==="ArrowDown")&&(L=Math.max(0,h-1)),M.key==="Home"&&(L=0),M.key==="End"&&(L=m),L===null||L===h)return;M.preventDefault();const O=i[L];w.current?w.current(O):n(O)};return c.jsx("div",{role:"slider",tabIndex:0,"aria-label":"Thinking","aria-orientation":"horizontal","aria-valuemin":0,"aria-valuemax":m,"aria-valuenow":h,"aria-valuetext":b,"data-no-drawer-swipe":"true",className:"cursor-pointer touch-none select-none px-4 py-1 outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] rounded-full",style:{touchAction:"none"},onPointerDown:T,onPointerMove:A,onPointerUp:j,onPointerCancel:k,onLostPointerCapture:k,onKeyDown:_,children:c.jsxs("div",{className:"relative h-8",children:[c.jsx("div",{className:"absolute inset-x-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-muted"}),c.jsx("div",{className:"absolute left-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-primary",style:{width:`calc(${Qc}px + (100% - ${Qc*2}px) * ${x})`}}),c.jsxs("div",{ref:o,className:"absolute inset-y-0",style:{left:Qc,right:Qc},children:[i.map((M,L)=>{const O=LD(L,m),N=L<=h;return c.jsx("div",{"aria-hidden":"true",className:R("pointer-events-none absolute top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full",N?"bg-primary-foreground/50":"bg-foreground/35"),style:{left:`${O}%`}},K3(M))}),c.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-1/2 h-0",children:c.jsx("div",{className:"w-full",style:{transform:`translateX(${x*100}%)`},children:c.jsx("div",{className:"absolute left-0 top-0 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground"})})})]})]})})}function A1({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=T1(e,s);return c.jsxs("div",{className:"w-full px-4 pt-3.5 pb-2","data-no-drawer-swipe":"true",children:[c.jsx(PD,{levels:e,value:t,onChange:n,onCommit:r,allowUnset:s}),c.jsxs("div",{className:"mt-1.5 flex justify-between px-4 typography-micro text-muted-foreground",children:[c.jsx("span",{children:Ur(o[0])}),c.jsx("span",{className:"text-right",children:Ur(o[o.length-1])})]})]})}function DD({levels:e,value:t,onChange:n,compact:r,keepLabel:s=!1,onCompactOpen:o,buttonHeight:i,iconSize:a,textSize:l,isMobile:d,isDesktop:f}){const[u,h]=p.useState(!1),m=Ur(t),x=!t?"text-muted-foreground":"text-foreground",b=T1(e,!0),S=d?10:void 0,y=c.jsxs("button",{type:"button",onClick:r?o:void 0,className:R("model-controls__variant-trigger flex items-center gap-1.5 min-w-0",i,"cursor-pointer hover:bg-transparent hover:opacity-70",r?"transition-opacity focus:outline-none":"transition-opacity"),"aria-label":`Thinking: ${m}`,children:[c.jsx($,{name:"brain-ai-3",className:R(a,"flex-shrink-0",x)}),c.jsx($y,{options:b,value:m,truncateAt:S,className:R("model-controls__variant-label",l,"font-normal",s?"min-w-max whitespace-nowrap":null,r&&d&&!s&&"max-w-[60px]",!r&&f&&"max-w-[180px]",x)})]});return r?y:c.jsxs(z5,{open:u,onOpenChange:h,children:[c.jsxs(wt,{delayDuration:600,...u?{open:!1}:{},children:[c.jsx(St,{asChild:!0,children:c.jsx(U5,{render:y})}),c.jsx(Ct,{side:"top",align:"center",children:c.jsx($y,{options:b,value:m,prefix:"Thinking: ",className:"typography-meta"})})]}),c.jsx(q5,{children:c.jsx(W5,{className:"app-region-no-drag z-50",side:"top",align:"center",sideOffset:8,collisionPadding:8,collisionAvoidance:RD,children:c.jsx(K5,{className:R(i1,"w-[min(17.5rem,calc(100vw-2rem))] p-0 max-h-none"),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},children:c.jsx(A1,{levels:e,value:t,onChange:n})})})})]})}function OD(){const e=We(i=>i.isInitialized),t=We(i=>i.connectionPhase),n=We(i=>i.lastDisconnectReason),r=We(i=>i.providers.length>0),s=e||r,o=!s&&n==="init_error";return{isReady:s,isLoading:!s&&!o,isUnavailable:o,connectionPhase:t}}const HD=({authoritative:e,observed:t,composer:n})=>{if(t&&t.providerId===e.providerId&&t.modelId===e.modelId&&(t.thinking??void 0)===(e.thinking??void 0))return"ignore";const r=t?.providerId===e.providerId&&t?.modelId===e.modelId,s=n.providerId!==e.providerId||n.modelId!==e.modelId;return r&&s||n.providerId===e.providerId&&n.modelId===e.modelId&&(e.thinking===void 0||n.thinking===e.thinking)?"observe":"apply"},FD=[{key:"tool_call",icon:"tools",label:"Tool calling",isActive:e=>e?.tool_call===!0},{key:"reasoning",icon:"brain-ai-3",label:"Reasoning",isActive:e=>e?.reasoning===!0}],BD={text:{icon:"text",label:"Text"},image:{icon:"file-image",label:"Image"},video:{icon:"file-video",label:"Video"},audio:{icon:"file-music",label:"Audio"},pdf:{icon:"file-pdf",label:"PDF"}},VD=e=>e.trim().toLowerCase(),kd=(e,t)=>{const n=t==="input"?e?.modalities?.input:e?.modalities?.output;if(!Array.isArray(n)||n.length===0)return[];const r=Array.from(new Set(n.map(o=>VD(o)))),s=[];for(const o of r){const i=BD[o];i&&s.push({key:o,icon:i.icon,label:i.label})}return s},$D=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),zD=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),UD=e=>new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(e),qD=e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e),Aa=e=>{if(typeof e!="number"||Number.isNaN(e))return"—";if(e===0)return"0";const t=$D(e);return t.endsWith(".0")?t.slice(0,-2):t},el=e=>typeof e!="number"||!Number.isFinite(e)?"—":zD(e),G3=e=>{const t=[];for(const n of FD)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},Z3=e=>{if(!e)return"—";const t=e.match(/^(\d{4})-(\d{2})$/);if(t){const n=Number.parseInt(t[1],10),r=Number.parseInt(t[2],10)-1,s=new Date(Date.UTC(n,r,1));if(!Number.isNaN(s.getTime()))return UD(s)}return e},Y3=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:qD(t)},Ro=({iconName:e,label:t})=>c.jsx("span",{className:"flex size-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:t,"aria-label":t,role:"img",children:c.jsx($,{name:e,className:"size-3.5"})}),WD=({currentMetadata:e,modelDisplayName:t,providerDisplayName:n,currentCapabilityIcons:r,inputModalityIcons:s,outputModalityIcons:o,costRows:i,limitRows:a})=>c.jsx(Ct,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e?c.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"typography-micro font-semibold text-foreground",children:e.name||t}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:n})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:r.length>0?r.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:f},`cap-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Input"}),c.jsx("div",{className:"flex items-center gap-1.5",children:s.length>0?s.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} input`},`input-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Output"}),c.jsx("div",{className:"flex items-center gap-1.5",children:o.length>0?o.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} output`},`output-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]})]})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Cost ($/1M tokens)"}),i.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Limits"}),a.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground",children:"Metadata"}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z3(e.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-subtle-foreground",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y3(e.release_date)})]})]})]}):c.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),KD=({open:e,onClose:t,title:n,providerDisplayName:r,currentCapabilityIcons:s,inputModalityIcons:o,outputModalityIcons:i,currentMetadata:a})=>e?c.jsx(Ta,{open:!0,onClose:t,title:n,children:c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),c.jsx("div",{className:"typography-meta text-foreground font-medium",children:r})]}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(({key:l,icon:d,label:f})=>c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(Ro,{iconName:d,label:f},`cap-${l}`),c.jsx("span",{className:"typography-meta text-foreground",children:f})]},l))})]}),(o.length>0||i.length>0)&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[o.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground w-12",children:"Input"}),c.jsx("div",{className:"flex gap-1",children:o.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} input`},`input-${l}`))})]}),i.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground w-12",children:"Output"}),c.jsx("div",{className:"flex gap-1",children:i.map(({key:l,icon:d,label:f})=>c.jsx(Ro,{iconName:d,label:`${f} output`},`output-${l}`))})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Context"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Aa(a?.limit?.context)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Output"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Aa(a?.limit?.output)})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z3(a?.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-subtle-foreground",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y3(a?.release_date)})]})]})]})]})}):null,GD=({open:e,onClose:t,targetVariants:n,selectedVariant:r,onVariantLiveChange:s,onVariantCommit:o})=>!e||n.length===0?null:c.jsx(Ta,{open:!0,onClose:t,title:"Thinking",children:c.jsx(A1,{levels:n,value:ln(r)??void 0,onChange:s,onCommit:o})}),ZD=e=>{if(!e||e.trim().length===0)return Ur(void 0);const t=e.trim();return/^\d+(\.\d+)?$/.test(t)?t:Ur(t)},YD=(e,t)=>`${e}:${t}`,XD=({open:e,onClose:t,mobileModelQuery:n,onMobileModelQueryChange:r,filteredFavorites:s,filteredRecents:o,filteredProviders:i,expandedMobileProviders:a,onToggleMobileProviderExpansion:l,expandedMobileModelKey:d,onToggleExpandedMobileModelKey:f,currentProviderId:u,currentModelId:h,getModelDisplayName:m,getModelMetadata:g,getModelVariantOptions:x,resolveModelVariantSelection:b,pendingThinkingVariants:S,onUpdatePendingThinkingVariant:y,isFavoriteModel:v,onToggleFavoriteModel:C,onApplyModel:w})=>{if(!e)return null;const I=n.trim(),E=s.length>0||o.length>0||i.length>0,T=({model:A,providerId:j,modelId:k,showProviderLogo:_})=>{const M=YD(j,k),L=j===u&&k===h,O=E1(j,A,g(j,k)),N=x(j,k),D=N.length>0,W=b(j,k),z=S.get(M),F=S.has(M)?z:W,U=D?ZD(F):null,P=d===M,q=G3(O),B=[...kd(O,"input"),...kd(O,"output")],ee=Array.from(new Map([...q,...B].map(K=>[K.key,K])).values()),G=O?.limit?.context?`${Aa(O.limit.context)} ctx`:null;return c.jsxs("div",{className:R("border-b border-border/30 last:border-b-0",L&&"bg-interactive-selection/15 text-interactive-selection-foreground"),children:[c.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[c.jsx("button",{type:"button",onClick:()=>w(j,k,F),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-lg"),children:c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[_?c.jsx(Wo,{providerId:j,className:"size-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:m(A)}),L?c.jsx($,{name:"check",className:"size-4 flex-shrink-0 text-primary"}):null]}),G||ee.length>0?c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[G?c.jsx("span",{className:"whitespace-nowrap flex-shrink-0",children:G}):null,G&&ee.length>0?c.jsx("span",{"aria-hidden":"true",className:"h-3 w-px flex-shrink-0 bg-border/50"}):null,ee.length>0?c.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap pl-0.5",children:ee.map(({key:K,icon:se,label:le})=>c.jsx("span",{className:"flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",title:le,"aria-label":le,children:c.jsx($,{name:se,className:"size-3"})},`meta-${j}-${k}-${K}`))}):null]}):null]})}),D?c.jsxs("button",{type:"button",onClick:()=>f(d===M?null:M),className:"flex items-center gap-0.5 typography-micro font-medium text-muted-foreground hover:text-foreground flex-shrink-0","aria-expanded":P,"aria-label":P?"Hide thinking modes":"Show thinking modes",children:[c.jsx("span",{className:"whitespace-nowrap",children:U}),P?c.jsx($,{name:"arrow-down-s",className:"size-3.5"}):c.jsx($,{name:"arrow-right-s",className:"size-3.5"})]}):null,c.jsx("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:c.jsx("button",{type:"button",onClick:K=>{K.preventDefault(),K.stopPropagation(),C(j,k)},className:R("model-favorite-button flex size-5 items-center justify-center hover:text-primary/80 flex-shrink-0",v(j,k)?"text-primary":"text-muted-foreground"),"aria-label":v(j,k)?"Unfavorite":"Favorite",title:v(j,k)?"Remove from favorites":"Add to favorites",children:v(j,k)?c.jsx($,{name:"star-fill",className:"size-4"}):c.jsx($,{name:"star",className:"size-4"})})})]}),P&&D?c.jsx("div",{className:"border-t border-border/30 px-1 py-1","data-no-drawer-swipe":"true",children:c.jsx(A1,{levels:N,value:ln(F)??void 0,onChange:()=>{},onCommit:K=>y(M,K)})}):null]},`mobile-model-${j}-${k}`)};return c.jsx(Ta,{open:!0,onClose:t,title:"Select model",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("div",{children:c.jsxs("div",{className:"relative",children:[c.jsx($,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground"}),c.jsx(Uo,{value:n,onChange:A=>{r(A.target.value),f(null)},placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-[var(--surface-elevated)] typography-meta"}),n&&c.jsx("button",{type:"button",onClick:()=>{r(""),f(null)},className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:c.jsx($,{name:"close-circle",className:"size-4"})})]})}),!E&&c.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx($,{name:"star-fill",className:"size-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:s.map(({model:A,providerID:j,modelID:k})=>T({model:A,providerId:j,modelId:k,showProviderLogo:!0}))})]}),o.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx($,{name:"time",className:"size-3 inline-block mr-1.5"}),"Recent"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:o.map(({model:A,providerID:j,modelID:k})=>T({model:A,providerId:j,modelId:k,showProviderLogo:!0}))})]}),i.map(({provider:A,providerModels:j})=>{if(j.length===0)return null;const k=String(A.id||""),_=String(A.name||k),M=k===u,L=a.has(k)||I.length>0;return c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("button",{type:"button",onClick:()=>{I.length>0||l(k)},className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":L,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Wo,{providerId:k,className:"size-3.5"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:_}),M&&c.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),L?c.jsx($,{name:"arrow-down-s",className:"size-3 text-muted-foreground"}):c.jsx($,{name:"arrow-right-s",className:"size-3 text-muted-foreground"})]}),L&&j.length>0&&c.jsx("div",{className:"flex flex-col border-t border-border/30",children:j.map(O=>T({model:O,providerId:String(A.id||""),modelId:String(O.id||""),showProviderLogo:!1}))})]},k)})]})})},ah=(e,t)=>`${e}:${t}`,JD="__add_provider__",QD=({className:e,keepLabels:t=!1,mobilePanel:n,onMobilePanelChange:r})=>{const{isReady:s,isUnavailable:o}=OD(),i=o?"Unavailable":"Loading...",a=We(Z=>Z.providers),l=We(Z=>Z.currentProviderId),d=We(Z=>Z.currentModelId),f=We(Z=>Z.currentVariant),u=We(Z=>Z.settingsDefaultThinking),h=We(Z=>Z.settingsDefaultThinkingByModel),m=We(Z=>Z.setProvider),g=We(Z=>Z.setSelectedProvider),x=We(Z=>Z.setModel),b=We(Z=>Z.setCurrentVariant),S=We(Z=>Z.getCurrentModelVariants),y=We(Z=>Z.getCurrentProvider),v=We(Z=>Z.getModelMetadata),C=p.useRef(!1);p.useEffect(()=>{C.current||!s||(C.current=!0,it("ModelControls:ready",{providers:a.length,currentProviderId:l,currentModelId:d}))},[d,l,s,a.length]);const w=he(Z=>Z.currentSessionId),I=he(Z=>Z.newSessionDraft.open),E=he(Z=>Z.getDirectoryForSession),T=W3(),A=Lt(Z=>Z.getSessionModelSelection),j=Lt(Z=>Z.saveSessionModelSelection),k=Lt(Z=>Z.hasHydrated),_=re(Z=>Z.toggleFavoriteModel),M=re(Z=>Z.reorderFavoriteModel),L=re(Z=>Z.isFavoriteModel),O=re(Z=>Z.addRecentModel),N=re(Z=>Z.addRecentEffort),D=re(Z=>Z.isModelSelectorOpen),W=re(Z=>Z.setModelSelectorOpen),z=re(Z=>Z.setSettingsDialogOpen),X=re(Z=>Z.setSettingsPage),F=re(Z=>Z.hiddenModels),{favoriteModelsList:U,recentModelsList:P}=TD(),{isMobile:q}=Dn(),{enabled:B}=mu(),ee=re(Z=>Z.isMobile),G=(q||ee)&&!B,K=p.useMemo(()=>xt(),[]),se=G,[le,oe]=p.useState(null),ue=n!==void 0&&typeof r=="function",ye=ue?n:le,we=ue?r:oe,[Me,He]=p.useState(null),[Ae,Ge]=p.useState(""),[et,Xe]=p.useState(null),te=p.useRef(!1),Q=p.useCallback(()=>we(null),[we]),me=p.useCallback(()=>He(null),[]),Se=p.useRef(void 0),[_e,Fe]=p.useState(()=>{const Z=new Set;return l&&Z.add(l),Z}),ht=p.useCallback(()=>{g(JD),X("providers"),z(!0),W(!1),Q()},[g,X,z,W,Q]),[ge,Ze]=p.useState(""),Be=p.useRef(!1),ie=p.useRef(null),ke=p.useRef(void 0),ve=p.useRef(null),[xe,je]=p.useState(new Map),[ce,J]=p.useState(new Set),[ne,fe]=p.useState(0);p.useEffect(()=>{ye==="model"&&(We.getState().ensureModelMetadata(),Fe(()=>{const Z=new Set;return l&&Z.add(l),Z}))},[ye,l]),p.useEffect(()=>{ye===null&&Xe(null)},[ye]),p.useEffect(()=>{ye!=="model"&&(Ge(""),Xe(null),je(new Map),J(new Set))},[ye]);const De=p.useRef(D);p.useEffect(()=>{const Z=De.current;De.current=D,D&&We.getState().ensureModelMetadata(),D||(Ze(""),Be.current=!1,ie.current=null,je(new Map),J(new Set),Z&&!se&&requestAnimationFrame(To))},[D,se]);const Ue=G?"mobile":"default",st=Ue==="mobile"?"h-9":"h-7",Ee="size-3.5",Ke="typography-meta",_t=Ue==="mobile"?"gap-x-1":"gap-x-3",fn=y(),Sn=Array.isArray(fn?.models)?fn.models:[],Vs=p.useMemo(()=>{const Z=[];for(const pe of a){const Ne=(Array.isArray(pe.models)?pe.models:[]).filter(ct=>{const ot=typeof ct?.id=="string"?ct.id:"";return!F.some(dt=>dt.providerID===String(pe.id)&&dt.modelID===ot)});Ne.length>0&&Z.push({...pe,models:Ne})}return Z},[a,F]),$s=p.useCallback(Z=>{const pe=Z.toLowerCase().trim(),Re=pe.replace(/[^a-z0-9]/g,""),Ne=pe.split(/[^a-z0-9]+/).filter(Boolean);return{lower:pe,compact:Re,tokens:Ne}},[]),On=p.useCallback((Z,pe)=>{const Re=$s(pe);if(!Re.lower)return!0;const Ne=$s(Z);return Ne.lower.includes(Re.lower)||Re.compact.length>=2&&Ne.compact.includes(Re.compact)?!0:Re.tokens.length===0?!1:Re.tokens.every(ct=>Ne.tokens.some(ot=>ot.startsWith(ct)||ot.includes(ct)))},[$s]),Ja=d?Sn.find(Z=>Z.id===d):void 0,Ot=l&&d&&Ja?E1(l,Ja,v(l,d)):l&&d?v(l,d):void 0,en=p.useCallback(Z=>Z==="Tool calling"?"Tool calling":Z==="Reasoning"?"Reasoning":Z==="Text"?"Text":Z==="Image"?"Image":Z==="Video"?"Video":Z==="Audio"?"Audio":Z==="PDF"?"PDF":Z,[]),Xr=p.useMemo(()=>G3(Ot).map(Z=>({...Z,label:en(Z.label)})),[Ot,en]),ti=p.useMemo(()=>kd(Ot,"input").map(Z=>({...Z,label:en(Z.label)})),[Ot,en]),ni=p.useMemo(()=>kd(Ot,"output").map(Z=>({...Z,label:en(Z.label)})),[Ot,en]),xr=S().filter(Ht),Qa=xr.length>0,ec=[{label:"Input",value:el(Ot?.cost?.input)},{label:"Output",value:el(Ot?.cost?.output)},{label:"Cache read",value:el(Ot?.cost?.cache_read)},{label:"Cache write",value:el(Ot?.cost?.cache_write)}],tc=[{label:"Context",value:Aa(Ot?.limit?.context)},{label:"Output",value:Aa(Ot?.limit?.output)}],Hn=p.useRef(null),Jr=p.useRef(null);w&&E(w);const Fn=jw(w??""),Pt=ze(Z=>{if(!w)return null;const pe=Z.reducer.bySession.get(w);return pe?{model:pe.model,thinking:pe.thinking}:null},(Z,pe)=>Z===pe?!0:!Z||!pe?!1:Z.model?.providerId===pe.model?.providerId&&Z.model?.modelId===pe.model?.modelId&&Z.thinking===pe.thinking,w?`session:${w}`:"*"),br=p.useCallback((Z,pe)=>{if(!Z||!pe)return"model-missing";const Re=a.find(Qe=>Qe.id===Z);if(!Re)return"provider-missing";const ct=(Array.isArray(Re.models)?Re.models:[]).find(Qe=>Qe.id===pe);if(!ct)return"model-missing";if(l===Z&&d===pe)return"applied";m(Z),x(pe);const Oe=_c({providerId:Z,modelId:pe,thinkingLevels:ct.thinkingLevels,reasoning:ct.reasoning,supportsThinking:ct.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f});return b(Oe),w&&j(w,Z,pe),"applied"},[a,l,d,f,m,x,b,w,j,u,h]),Vt=p.useCallback((Z,pe)=>{const Re=a.find(ct=>ct.id===Z),Ne=(Array.isArray(Re?.models)?Re.models:[]).find(ct=>ct.id===pe);return _m(Ne)},[a]),Qr=p.useCallback((Z,pe,Re)=>{if(!Z||!pe)return"model-missing";const Ne=a.find(dt=>dt.id===Z);if(!Ne)return"provider-missing";if(!(Array.isArray(Ne.models)?Ne.models:[]).some(dt=>dt.id===pe))return"model-missing";l!==Z&&m(Z),(l!==Z||d!==pe)&&x(pe),w&&j(w,Z,pe);const ot=Vt(Z,pe);return b(Re&&ot.includes(Re)?Re:void 0),Jr.current={...Z?{providerId:Z}:{},...pe?{modelId:pe}:{},...Re?{thinking:Re}:{}},"applied"},[d,l,w,Vt,a,j,b,x,m]),ri=p.useCallback((Z,pe)=>{const Re=Vt(Z,pe);if(Re.length!==0){if(l===Z&&d===pe&&Ht(f)&&Re.includes(f))return f;if(!w){const Ne=a.find(ot=>ot.id===Z),ct=(Array.isArray(Ne?.models)?Ne.models:[]).find(ot=>ot.id===pe);return _c({providerId:Z,modelId:pe,thinkingLevels:ct?.thinkingLevels,reasoning:ct?.reasoning,supportsThinking:ct?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u})}}},[d,l,w,f,Vt,a,u,h]),es=p.useCallback((Z,pe,Re)=>{const Ne=Vt(Z,pe);if(Ne.length===0){te.current=!1,Hi(void 0);return}const ct=Ht(Re)&&Ne.includes(Re)?Re:void 0;te.current=!0,Hi(ct),N(Z,pe,Re)},[N,Vt]),nc=p.useCallback((Z,pe,Re)=>{const Ne=br(Z,pe);return Ne!=="applied"?Ne:(O(Z,pe),es(Z,pe,Re),"applied")},[O,es,br]);p.useEffect(()=>{if(!w){Hn.current=null;return}if(!k||a.length===0)return;if(!Fn){T.ensureSessionRenderable(w);return}if(Hn.current===w)return;const Z=Ne=>{if(Ne&&l&&d){const ct=Vt(l,d);b(ct.includes(Ne)?Ne:void 0);return}b(void 0)},pe=Pt?.model;if(pe){if(Qr(pe.providerId,pe.modelId,Pt?.thinking)==="provider-missing")return;Hn.current=w;return}if(Pt?.thinking){Z(Pt.thinking),Hn.current=w;return}const Re=A(w);Re&&Qr(Re.providerId,Re.modelId,Pt?.thinking)==="provider-missing"||(Hn.current=w)},[Qr,k,d,l,w,Pt,Vt,A,Fn,a.length,b,T]),p.useEffect(()=>{if(!w||!k||a.length===0||!Fn||Hn.current!==w)return;const Z=Pt?.model,pe=Pt?.thinking??void 0;if(!Z?.providerId||!Z?.modelId){Jr.current=null;return}const Re=HD({authoritative:{providerId:Z.providerId,modelId:Z.modelId,thinking:pe},observed:Jr.current,composer:{providerId:l,modelId:d,thinking:ln(f)??void 0}});if(Re!=="ignore"){if(Re==="apply"){Qr(Z.providerId,Z.modelId,pe);return}Jr.current={providerId:Z.providerId,modelId:Z.modelId,...pe?{thinking:pe}:{}}}},[Qr,k,d,l,w,f,Pt,Fn,a.length]),p.useEffect(()=>{if(!k){te.current=!1,b(void 0);return}if(!l||!d){te.current=!1,b(void 0);return}const Z=a.find(Ne=>Ne.id===l),pe=(Array.isArray(Z?.models)?Z.models:[]).find(Ne=>Ne.id===d),Re=Em(pe);if(!Xd(Re)){f&&Ht(f)&&b(void 0);return}if(!w&&!f&&!te.current){const Ne=_c({providerId:l,modelId:d,thinkingLevels:pe?.thinkingLevels,reasoning:pe?.reasoning,supportsThinking:pe?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u});Ne&&b(Ne);return}if(f&&Ht(f)&&!Re.includes(f)){b(_c({providerId:l,modelId:d,thinkingLevels:pe?.thinkingLevels,reasoning:pe?.reasoning,supportsThinking:pe?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f}));return}if(w&&!f&&!te.current){const Ne=ln(Pt?.thinking);Ne&&Re.includes(Ne)&&b(Ne)}},[k,w,l,d,f,Pt,a,b,u,h]),p.useEffect(()=>{te.current=!1},[l,d]);const Lu=p.useCallback(Z=>{l&&d&&es(l,d,Z)},[es,d,l]),zs=p.useCallback(Z=>{if(!l||!d)return;const pe=Vt(l,d);if(pe.length===0){te.current=!1,Hi(void 0);return}const Re=Ht(Z)&&pe.includes(Z)?Z:void 0;te.current=!0,Hi(Re)},[l,d,Vt]),Ru=p.useCallback(Z=>{Z!==f&&zs(Z),l&&d&&N(l,d,Z)},[zs,l,d,f,N]),Pu=(Z,pe,Re)=>{try{const Ne=Re?.applyVariant?nc(Z,pe,Re.variant):br(Z,pe);if(Ne!=="applied"){Ne==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",Z):Ne==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:Z,modelId:pe});return}Re?.applyVariant||O(Z,pe),W(!1),se&&Q(),requestAnimationFrame(To)}catch(Ne){console.error("[ModelControls] Handle model change error:",Ne)}},Jn=(Z,pe)=>_1(Z,pe,{maxLength:40}),ts=()=>a.find(pe=>pe.id===l)?.name||l||"",tn=()=>{if(!d)return"Select model";const Z=Sn.find(pe=>pe.id===d);return Jn(Z,d)||"Select model"},si=p.useCallback((Z,pe)=>!G||Z.length<=pe?Z:`${Z.slice(0,pe)}...`,[G])(tn(),16),Bn=p.useRef(null),rc=ND(Bn,[si,se]),wr=p.useCallback(Z=>{Fe(pe=>{const Re=new Set(pe);return Re.has(Z)?Re.delete(Z):Re.add(Z),Re})},[]),Us=p.useCallback(Z=>{Se.current&&clearTimeout(Se.current),Se.current=setTimeout(()=>{He(Z)},500)},[]),sc=p.useCallback(()=>{Se.current&&clearTimeout(Se.current)},[]);p.useEffect(()=>()=>{Se.current&&clearTimeout(Se.current)},[]);const oc=()=>!se||Me!=="model"?null:c.jsx(KD,{open:!0,onClose:me,title:Ot?.name||tn(),providerDisplayName:ts(),currentCapabilityIcons:Xr,inputModalityIcons:ti,outputModalityIcons:ni,currentMetadata:Ot}),ic=()=>{if(!se)return null;const Z=Ae.trim(),pe=U.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=Jn(ot);return Z.length===0||On(String(kt||""),Z)||On(String(Qe||""),Z)}),Re=P.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=Jn(ot);return Z.length===0||On(String(kt||""),Z)||On(String(Qe||""),Z)}),Ne=[];for(const ot of Vs){const dt=Array.isArray(ot.models)?ot.models:[],Oe=Z.length===0?!0:On(String(ot.name||""),Z)||On(String(ot.id||""),Z),Qe=Z.length===0?dt:dt.filter(jt=>{const Cn=Jn(jt),nn=typeof jt.id=="string"?jt.id:"";return On(String(Cn||""),Z)||On(String(nn||""),Z)}),kt=Oe&&Z.length>0?dt:Qe;(Oe||kt.length>0)&&Ne.push({provider:ot,providerModels:kt,matchesProvider:Oe})}const ct=(ot,dt,Oe)=>{const Qe=nc(ot,dt,Oe);if(Qe!=="applied"){Qe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ot):Qe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ot,modelId:dt});return}Xe(null),Q(),requestAnimationFrame(To)};return c.jsx(XD,{open:ye==="model",onClose:Q,mobileModelQuery:Ae,onMobileModelQueryChange:Ge,filteredFavorites:pe,filteredRecents:Re,filteredProviders:Ne,expandedMobileProviders:_e,onToggleMobileProviderExpansion:wr,expandedMobileModelKey:et,onToggleExpandedMobileModelKey:Xe,currentProviderId:l,currentModelId:d,getModelDisplayName:Jn,getModelMetadata:v,getModelVariantOptions:Vt,resolveModelVariantSelection:ri,pendingThinkingVariants:xe,onUpdatePendingThinkingVariant:(ot,dt)=>{je(Oe=>{const Qe=new Map(Oe);return Qe.set(ot,dt),Qe}),J(Oe=>{const Qe=new Set(Oe);return Qe.add(ot),Qe}),fe(Oe=>Oe+1)},isFavoriteModel:L,onToggleFavoriteModel:_,onApplyModel:ct})},ac=()=>{if(!se||!l||!d)return null;const Z=Vt(l,d);return c.jsx(GD,{open:ye==="variant",onClose:Q,targetVariants:Z,selectedVariant:f,onVariantLiveChange:zs,onVariantCommit:Ru})},cc=()=>c.jsx(WD,{currentMetadata:Ot,modelDisplayName:tn(),providerDisplayName:ts(),currentCapabilityIcons:Xr,inputModalityIcons:ti,outputModalityIcons:ni,costRows:ec,limitRows:tc}),lc=()=>{const Z=(Oe,Qe)=>{if(Be.current=!0,Oe.key!=="ArrowLeft"&&Oe.key!=="ArrowRight")return!1;const{providerID:kt,modelID:jt}=Qe,Cn=Vt(kt,jt);if(Cn.length===0)return!1;Oe.preventDefault(),Oe.stopPropagation();const nn=ah(kt,jt),qs=xe.has(nn),Ws=xe.get(nn),Qn=qs?Ws:l===kt&&d===jt?f:void 0,oi=jm(Cn,Ht(Qn)?Qn:void 0,Oe.key==="ArrowRight"?1:-1);return je(Sr=>{const Cr=new Map(Sr);return Cr.set(nn,oi),Cr}),J(Sr=>{const Cr=new Set(Sr);return Cr.add(nn),Cr}),fe(Sr=>Sr+1),!0},pe=(Oe,Qe)=>{Qe&&Z(Oe,Qe)},Re=Oe=>{const Qe=ah(Oe.providerID,Oe.modelID),kt=xe.get(Qe),jt=ce.has(Qe);Pu(Oe.providerID,Oe.modelID,jt?{applyVariant:!0,variant:kt}:void 0)},Ne=Oe=>{ve.current={category:Oe.key.length===1?"printable":Oe.key.startsWith("Arrow")||Oe.key==="Escape"||Oe.key==="Enter"?"navigation":"other",modifiers:Oe.altKey||Oe.ctrlKey||Oe.metaKey||Oe.shiftKey}},ct=(Oe,Qe)=>{if(!Oe){const kt=document.activeElement;console.info("[DEBUG-model-picker-close]",{reason:Qe.reason??"unknown",eventType:Qe.event?.type??"none",draftOpen:I,focusInsidePicker:kt instanceof Element&&!!kt.closest('[data-model-picker-popup="true"]'),precedingKey:ve.current})}W(Oe)},ot={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},dt=(Oe,{isHighlighted:Qe,isSelected:kt})=>{const jt=Vt(Oe.providerID,Oe.modelID).length>0,Cn=ah(Oe.providerID,Oe.modelID),nn=ce.has(Cn);if(!jt||!Qe&&!kt)return null;const qs=xe.has(Cn),Ws=xe.get(Cn),Qn=qs?Ws:kt?f:void 0,oi=Ur(Ht(Qn)?Qn:void 0);return c.jsxs("span",{className:R("typography-micro whitespace-nowrap",nn?"text-foreground":"text-muted-foreground"),children:["Thinking: ",oi]})};return c.jsxs(wt,{delayDuration:600,children:[se?c.jsx("button",{type:"button",onClick:s?()=>we("model"):void 0,onTouchStart:s?()=>Us("model"):void 0,onTouchEnd:s?sc:void 0,onTouchCancel:s?sc:void 0,disabled:!s,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",s?"cursor-pointer hover:bg-transparent hover:opacity-70":"opacity-60 cursor-not-allowed",st),children:s?c.jsxs(c.Fragment,{children:[l?c.jsx(Wo,{providerId:l,className:R(Ee,"flex-shrink-0")}):c.jsx($,{name:"pencil-ai",className:R(Ee,"text-muted-foreground")}),c.jsx("span",{ref:Bn,className:R("model-controls__model-label typography-meta font-normal overflow-hidden",t?"whitespace-nowrap":"min-w-0",!t&&(G?"max-w-[120px]":"max-w-[220px]")),children:c.jsx("span",{className:R("marquee-text",rc&&"marquee-text--active"),children:si})}),c.jsx($,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"})]}):c.jsxs(c.Fragment,{children:[c.jsx($,{name:"loader-4",className:R(Ee,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:"typography-meta font-normal text-muted-foreground min-w-0",children:i})]})}):c.jsxs(Fa,{open:s&&D,onOpenChange:s?ct:void 0,children:[c.jsx(St,{asChild:!0,children:c.jsx(Ba,{asChild:!0,children:c.jsxs("button",{type:"button",className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",st),children:[s?l?c.jsxs(c.Fragment,{children:[c.jsx(Wo,{providerId:l,className:R(Ee,"flex-shrink-0")}),c.jsx($,{name:"pencil-ai",className:R(Ee,"text-primary/60 hidden")})]}):c.jsx($,{name:"pencil-ai",className:R(Ee,"text-muted-foreground")}):c.jsxs(c.Fragment,{children:[c.jsx($,{name:"loader-4",className:R(Ee,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:R("model-controls__model-label",Ke,"font-normal whitespace-nowrap text-muted-foreground min-w-0"),children:i})]}),s&&c.jsx("span",{ref:Bn,className:R("model-controls__model-label overflow-hidden",Ke,"font-normal whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:c.jsx("span",{className:R("marquee-text",rc&&"marquee-text--active"),children:si})},`${l}-${d}`),s?c.jsx($,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"}):null]})})}),c.jsxs(Va,{"data-model-picker-popup":"true",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,onKeyDownCapture:Ne,children:[c.jsx("div",{className:"p-1 border-b border-border/40",children:c.jsxs("button",{type:"button",onClick:ht,className:"typography-meta group flex w-full items-center gap-1 rounded-md px-2 py-1.5 cursor-pointer hover:bg-interactive-hover/50",children:[c.jsx("span",{className:"flex size-4 items-center justify-center text-muted-foreground",children:c.jsx($,{name:"add",className:"size-4 -mr-0.5"})}),c.jsx("span",{className:"font-medium text-foreground",children:"Add new provider"})]})}),c.jsx(jD,{providers:a,favoriteModels:U,recentModels:P,modelsMetadata:We.getState().modelsMetadata,searchQuery:ge,onSearchQueryChange:Ze,onSelect:Re,labels:ot,selectedModel:l&&d?{providerID:l,modelID:d}:null,hiddenModels:F,onActiveKeyDown:pe,onActiveEntryChange:Oe=>{ke.current=Oe},onVariantKey:Z,isFavorite:Oe=>L(Oe.providerID,Oe.modelID),onToggleFavorite:Oe=>_(Oe.providerID,Oe.modelID),renderRowEnd:dt,renderVersion:ne,onReorderFavorite:(Oe,Qe)=>M(Oe.providerID,Oe.modelID,Qe.providerID,Qe.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",tooltipsEnabled:D,onEscape:()=>W(!1)})]})]}),cc()]})},dc=()=>!s||!Qa?null:c.jsx(DD,{levels:xr,value:ln(f)??void 0,onChange:Lu,compact:se,keepLabel:t,onCompactOpen:()=>we("variant"),buttonHeight:st,iconSize:Ee,textSize:Ke,isMobile:G,isDesktop:K}),uc=R(!t&&"@container/model-controls","flex items-center",t?"w-max shrink-0":"min-w-0",G&&!t&&"w-full",e);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:uc,children:c.jsxs("div",{className:R("flex items-center justify-start",_t,t?"w-max shrink-0":"min-w-0",G&&!t&&"overflow-hidden"),children:[lc(),dc()]})}),ic(),ac(),oc()]})},eO=1e9,tO=1e12,ch="thinking",nO=e=>e>=tO?e:e>=eO?e*1e3:Date.now()+e,rO=e=>{if(e<60)return`${e}s`;if(e<3600){const r=Math.floor(e/60),s=e%60;return s>0?`${r}m ${s}s`:`${r}m`}if(e<86400){const r=Math.floor(e/3600),s=Math.floor(e%3600/60);return s>0?`${r}h ${s}m`:`${r}h`}const t=Math.floor(e/86400),n=Math.floor(e%86400/3600);return n>0?`${t}d ${n}h`:`${t}d`};function X3({isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:s,modelName:o,providerId:i,startedAt:a=null}){const{src:l,onError:d,hasLogo:f}=I1(i??null),{currentTheme:u}=vr(),h=u?.metadata.variant==="dark",m=p.useRef(null),[g,x]=p.useState(null);if(p.useEffect(()=>{const I=s?.next;if(!I||I<=0){x(null);return}const E=nO(I),T=()=>{const j=Math.max(0,E-Date.now());x(Math.ceil(j/1e3))};T();const A=setInterval(T,500);return()=>clearInterval(A)},[s?.next,s?.attempt]),!e)return m.current=null,null;if(s){m.current=null;const I=s.attempt&&s.attempt>1?` (attempt ${s.attempt})`:"",T=`Retrying${g!==null&&g>0?` in ${rO(g)}`:""}${I}`;return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":"polite","aria-label":`${T}...`,"data-agent-thinking-row":"true",children:c.jsx(yy,{text:T,variant:"inline",showElapsed:!1,className:"min-w-0"})})}const b=r?"waiting for permission":t,S=!!r,y=!!n&&!S;m.current===null?m.current={text:y?ch:b??ch,permission:S}:b&&(!y||S)?m.current={text:b,permission:S}:y&&m.current.permission&&(m.current={text:ch,permission:!1});const v=m.current;if(!v)return null;const C=typeof o=="string"?o.trim():"",w=C.length>0?`${C} is ${v.text}`:v.text.charAt(0).toUpperCase()+v.text.slice(1);return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":v.permission?"assertive":"polite","aria-label":w,"data-agent-thinking-row":"true","data-waiting":v.permission?"true":void 0,children:c.jsxs("span",{className:"typography-markdown inline-flex min-w-0 items-center gap-1.5 leading-5",children:[f&&l?c.jsx("img",{src:l,alt:"","aria-hidden":"true",className:"inline-block h-3.5 w-3.5 mr-0.5 align-[-2px]",style:{filter:h?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:d}):null,c.jsx(yy,{text:w,variant:"inline",animationType:"spinner",animateText:!0,startedAt:a,className:"min-w-0"})]})})}const sO={containerType:"inline-size",containerName:"status-row"},zy={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Uy={high:"text-[var(--status-warning)]",medium:"text-muted-foreground",low:"text-subtle-foreground"},qy={high:c.jsx($,{name:"arrow-up-double",className:"h-3.5 w-3.5","aria-hidden":"true"}),medium:c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5","aria-hidden":"true"}),low:c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5","aria-hidden":"true"})},Wy={in_progress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},Ky={high:"High priority",medium:"Medium priority",low:"Low priority"},oO=({todo:e})=>{const t=String(e.status||"pending"),n=String(e.priority||"medium"),r=zy[t]||zy.pending,s=Wy[t]??Wy.pending,o=Ky[n]??Ky.medium,i=t==="in_progress"?c.jsx($,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]","aria-hidden":"true"}):t==="completed"?c.jsx($,{name:"checkbox-circle",className:"h-3.5 w-3.5 text-[var(--status-success)]","aria-hidden":"true"}):c.jsx($,{name:"time",className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"});return c.jsxs("div",{className:"flex items-center min-w-0 py-0.5 gap-2",children:[c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("span",{className:"flex-shrink-0",children:i})}),c.jsx(Ct,{side:"left",sideOffset:6,children:s})]}),c.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:e.content}),c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("span",{className:R("typography-meta flex items-center justify-center flex-shrink-0 leading-none",Uy[n]??Uy.medium),children:qy[n]??qy.medium})}),c.jsx(Ct,{side:"right",sideOffset:6,children:o})]})]})},iO=[],J3=({isWorking:e=!1,statusText:t=null,isGenericStatus:n,isWaitingForPermission:r,wasAborted:s,abortActive:o,retryInfo:i,showAbort:a,onAbort:l,showAbortStatus:d,showAssistantStatus:f=!0,showTodos:u=!0,agentName:h,modelName:m,providerId:g,leftAccessory:x,turnStartedAt:b=null})=>{const[S,y]=p.useState(!1),v=he(P=>P.currentSessionId),C=iO,w=re(P=>P.isMobile),{enabled:I}=mu(),E=w&&!I,T=E,A=p.useMemo(()=>C.filter(P=>P.status!=="cancelled"),[C]),j=p.useMemo(()=>A.find(P=>P.status==="in_progress")||A.find(P=>P.status==="pending")||null,[A]),k=p.useMemo(()=>{const P=C.filter(B=>B.status!=="cancelled").length;return{completed:C.filter(B=>B.status==="completed").length,total:P}},[C]),_=p.useMemo(()=>{const P=A.filter(B=>B.status==="in_progress").length,q=A.filter(B=>B.status==="in_progress"||B.status==="pending").length;return{active:P,left:q}},[A]),M=u&&_.left>0,L=f&&(e||!!s||!!d),O=!!x,N=!d&&(s||!o),D=L||M||O,W=p.useRef(null);p.useEffect(()=>{if(!S)return;const P=q=>{W.current&&!W.current.contains(q.target)&&y(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[S]);const z=()=>y(P=>!P),X=`${_.active} active · ${_.left} left`,F=a&&l?c.jsx("button",{type:"button",onClick:l,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:c.jsx($,{name:"close-circle","aria-hidden":"true"})}):null,U=M?c.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground","aria-label":X,title:X,children:[!T&&j?c.jsx("span",{className:"status-row__active-todo typography-ui-label text-foreground truncate max-w-[200px]",children:j.content}):c.jsx("span",{className:"typography-ui-label",children:"Tasks"}),c.jsxs("span",{className:"typography-meta flex items-center gap-1 tabular-nums","aria-hidden":"true",children:[c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx($,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]"}),_.active]}),c.jsx("span",{children:"·"}),c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx($,{name:"time",className:"h-3.5 w-3.5"}),_.left]})]}),S?c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"})]}):null;return D?c.jsx("div",{className:R("mb-1",E&&"mt-2",!O&&"chat-column"),style:sO,children:c.jsxs("div",{className:R("flex min-h-5 items-center justify-between gap-2 py-0.5",O&&"px-0.5"),children:[c.jsx("div",{className:R("flex min-w-0 flex-1 items-center gap-2",O?"pl-1.5":"overflow-x-hidden"),children:f&&d?c.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-0.5",children:c.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[c.jsx($,{name:"close-circle","aria-hidden":"true"}),"Aborted"]})}):f&&N?c.jsx(X3,{isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:i,agentName:h,modelName:m,providerId:g,startedAt:b},`${v??"no-session"}:${b??"no-start"}`):x||null}),c.jsxs("div",{className:R("relative flex items-center gap-2 flex-shrink-0",O?"pr-1.5":"-mr-3"),ref:W,children:[F,U,S&&M&&c.jsxs("div",{style:{maxWidth:"min(28rem, calc(100cqw - 4ch))",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px] rounded-xl p-1","shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)]","dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Tasks"}),c.jsxs("span",{className:"typography-meta tabular-nums",children:[k.completed,"/",k.total]})]}),c.jsx("div",{className:"px-1 max-h-[200px] overflow-y-auto",children:A.map((P,q)=>c.jsx(oO,{todo:P},P.id??`todo-${q}`))})]})]})]})}):null},aO=1e4,cO=6e4,lO=5e3,dO=15e3,uO=3e4,fO=6e4,Gy=5*6e4,hO=3e4,pO=10,Zy=25,mO=40,gO=2,Yy=15e3,yO=500,vO=30,Md=20*1024*1024,Xy=200,Jy=e=>JSON.stringify({from:e.from??null,to:e.to??null,all:e.all??!1,file:e.file??null,maxCount:e.maxCount??null}),Nt=()=>({isGitRepo:null,status:null,branches:null,log:null,remotes:null,remoteUrl:null,lastRemotesFetch:0,isLoadingRemotes:!1,logQueryCache:new Map,diffCache:new Map,indexRevision:0,lastRepoCheckAt:0,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,lastBranchesFetch:0,logMaxCount:25,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1}),Qy="oc.gitBranchCache",Vl="oc.gitBranchCache.v2",xO=8,bO=50,lh=()=>({version:2,legacyClaimed:!1,runtimes:{}}),Q3=e=>{try{const t=Gt(),n=t.getItem(Vl),r=n?JSON.parse(n):lh(),s=r?.version===2&&r.runtimes&&typeof r.runtimes=="object"?{version:2,legacyClaimed:!!r.legacyClaimed,runtimes:r.runtimes}:lh();if(!s.legacyClaimed){const o=t.getItem(Qy);if(o){const a=JSON.parse(o),l={};for(const[d,f]of Object.entries(a??{}))d&&f&&Array.isArray(f.all)&&(l[d]={branches:f,updatedAt:0});Object.keys(l).length>0&&(s.runtimes[e]={updatedAt:0,directories:l})}s.legacyClaimed=!0;const i=JSON.stringify(s);t.setItem(Vl,i),t.getItem(Vl)===i&&t.removeItem(Qy)}return s}catch{return lh()}},wO=(e,t,n)=>{if(!(!t||!n))try{const r=Q3(e),s=Date.now(),i={...r.runtimes[e]?.directories??{},[t]:{branches:n,updatedAt:s}},a=Object.fromEntries(Object.entries(i).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,bO));r.runtimes[e]={updatedAt:s,directories:a},r.runtimes=Object.fromEntries(Object.entries(r.runtimes).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,xO)),Gt().setItem(Vl,JSON.stringify(r))}catch{}},ev=e=>{const t=new Map,n=Q3(e).runtimes[e]?.directories??{};for(const[r,s]of Object.entries(n)){const o=s.branches;!r||!o||!Array.isArray(o.all)||t.set(r,{...Nt(),isGitRepo:!0,branches:o})}return t},e4=e=>{const t=new TextEncoder;return t.encode(e.original??"").byteLength+t.encode(e.modified??"").byteLength},tv=(e,t=vO,n=Md)=>{let r=0;for(const a of e.values())r+=new TextEncoder().encode(a.original??"").byteLength+new TextEncoder().encode(a.modified??"").byteLength;if(e.size<=t&&r<=n)return e;const s=Array.from(e.entries()).sort((a,l)=>a[1].fetchedAt-l[1].fetchedAt),o=new Map;let i=0;for(let a=s.length-1;a>=0;a--){const[l,d]=s[a],f=new TextEncoder().encode(d.original??"").byteLength+new TextEncoder().encode(d.modified??"").byteLength;if(o.size>=t)break;i+f>n||(o.set(l,d),i+=f)}return o},nv=e=>{const t=[];let n=0;for(const[o,i]of e)for(const[a,l]of i.diffCache){const d=e4(l);t.push({directory:o,path:a,fetchedAt:l.fetchedAt,size:d}),n+=d}if(t.length<=Xy&&n<=Md)return e;const r=new Map(e);t.sort((o,i)=>o.fetchedAt-i.fetchedAt);let s=t.length;for(const o of t){if(s<=Xy&&n<=Md)break;const i=r.get(o.directory);if(!i?.diffCache.has(o.path))continue;const a=new Map(i.diffCache);a.delete(o.path),r.set(o.directory,{...i,diffCache:a}),s-=1,n-=o.size}return r},SO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n){const s=e[r],o=t[r];if(!(!s&&!o)&&(!s||!o||s.insertions!==o.insertions||s.deletions!==o.deletions))return!0}return!1},CO=(e,t)=>!e&&!t?!1:!e||!t?!0:e.remote!==t.remote||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind,kO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[];if(n.length!==r.length||e.ahead!==t.ahead||e.behind!==t.behind||e.current!==t.current||e.tracking!==t.tracking||e.isClean!==t.isClean||t.upstreamComparison!==void 0&&CO(e.upstreamComparison,t.upstreamComparison))return!0;const s=new Set(n.map(o=>`${o.path}:${o.index}:${o.working_dir}`));for(const o of r)if(!s.has(`${o.path}:${o.index}:${o.working_dir}`))return!0;return!!(t.diffStats!==void 0&&SO(e.diffStats,t.diffStats))},MO=(e,t)=>{const n=new Set;if(!t)return n;const r=e?.files??[],s=t.files??[],o=new Map(r.map(l=>[l.path,l])),i=new Map(s.map(l=>[l.path,l])),a=new Set([...o.keys(),...i.keys()]);for(const l of a){const d=o.get(l),f=i.get(l);if(!d||!f){n.add(l);continue}if(d.index!==f.index||d.working_dir!==f.working_dir){n.add(l);continue}}if(t.diffStats!==void 0){const l=e?.diffStats??{},d=t.diffStats??{},f=new Set([...Object.keys(l),...Object.keys(d)]);for(const u of f){const h=l[u],m=d[u];if(!h||!m){n.add(u);continue}(h.insertions!==m.insertions||h.deletions!==m.deletions)&&n.add(u)}}return n},IO=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[],s=l=>{const d=l?.trim()??"";return d==="?"?"":d},o=new Map(n.map(l=>[l.path,s(l.index)])),i=new Map(r.map(l=>[l.path,s(l.index)])),a=new Set([...o.keys(),...i.keys()]);for(const l of a)if((o.get(l)??"")!==(i.get(l)??""))return!0;return!1},rv=e=>!e||e.trim().length===0,Id=e=>(e||"").trim()==="U",EO=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Id(t)||Id(n)?e:{...e,index:t==="?"||n==="?"?"A":t||n||" ",working_dir:" "}},_O=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Id(t)||Id(n)?e:{...e,index:" ",working_dir:n||(t==="A"||t==="?"?"?":t)||" "}},jO=e=>rv(e.index)&&rv(e.working_dir),Bp=new Map,N1=new Map,lo=new Map,Vi=new Map,$i=new Map,zi=new Map,Ui=new Map,qi=new Map,Ed=new Map,Na=new Map;let L1=0,R1=Y();const TO=()=>R1,AO=e=>{L1+=1,R1=e,Ed.clear(),Na.clear(),lo.clear(),Vi.clear(),$i.clear(),zi.clear(),Ui.clear(),qi.clear(),Bp.clear(),N1.clear()},hr=(e,t)=>JSON.stringify([e,t]),sv=(e,t,n)=>JSON.stringify([e,t,n]),NO=(e,t,n)=>JSON.stringify([e,t,n]),LO=(e,t,n)=>JSON.stringify([e,t,n]),RO=(e,t,n)=>JSON.stringify([e,t,n]),ls=(e,t,n=!1)=>{const r=Y(),s=RO(r,e,t),o=(Ed.get(s)??0)+1;return Ed.set(s,o),{runtimeKey:r,runtimeGeneration:L1,channelKey:s,requestGeneration:o,...n?{statusMutationRevision:Na.get(hr(r,e))??0}:{}}},yn=(e,t)=>e.runtimeKey===Y()&&e.runtimeKey===R1&&e.runtimeGeneration===L1&&Ed.get(e.channelKey)===e.requestGeneration&&(e.statusMutationRevision===void 0||e.statusMutationRevision===(Na.get(hr(e.runtimeKey,t))??0)),dh=(e,t)=>{const n=hr(e,t);Na.set(n,(Na.get(n)??0)+1)},$l=e=>N1.get(hr(Y(),e))??0,tl=e=>{const t=$l(e)+1;return N1.set(hr(Y(),e),t),t},PO=e=>{const t=hr(Y(),e),n=Bp.get(t);if(n)return n;const r=new Set;return Bp.set(t,r),r},ov=TO(),vt=Et()(gr((e,t)=>({runtimeKey:ov,directories:ev(ov),activeDirectory:null,resetForRuntimeSwitch:n=>{AO(n),e({runtimeKey:n,directories:ev(n),activeDirectory:null})},setActiveDirectory:n=>{const{activeDirectory:r,directories:s}=t();if(r!==n)if(r&&tl(r),n&&tl(n),n&&!s.has(n)){const o=new Map(s);o.set(n,Nt()),e({activeDirectory:n,directories:o})}else e({activeDirectory:n})},getDirectoryState:n=>t().directories.get(n)??null,fetchStatus:async(n,r,s={})=>{const o=s.mode??"full",i=Y(),a=sv(i,n,o),l=lo.get(a)??(o==="light"?lo.get(sv(i,n,"full")):void 0);if(l)return l;const d=ls(n,"status",!0),f=(async()=>{const{silent:u=!1}=s,{directories:h}=t();let m=h.get(n);if(m||(m=Nt()),!u){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingStatus:!0}),e({directories:x})}let g=!1;try{const x=Date.now(),b=m.isGitRepo!==!0||x-(m.lastRepoCheckAt||0)>cO;let S=m.isGitRepo===!0;if(b&&(S=await r.checkIsGitRepository(n),!yn(d,n)))return!1;if(!S){const C=new Map(t().directories),w=C.get(n)??m;return C.set(n,{...w,isGitRepo:!1,status:null,isLoadingStatus:!1,lastRepoCheckAt:x,lastStatusFetch:x}),e({directories:C}),!1}const y=await r.getGitStatus(n,s.mode?{mode:s.mode}:void 0);if(!yn(d,n))return!1;const v=t().directories.get(n)??Nt();if(kO(v.status,y)){g=!0;const C=new Map(t().directories),w=C.get(n)??Nt(),I=MO(w.status,y),E=IO(w.status,y),T=new Set((w.status?.files??[]).map(M=>M.path)),A=new Set((y.files??[]).map(M=>M.path)),j=new Map(w.diffCache);for(const M of T)A.has(M)||j.delete(M);for(const M of I)j.delete(M);const k=I.size>0;k&&tl(n);const _={...y,diffStats:y.diffStats===void 0&&w.status?.diffStats!==void 0?w.status.diffStats:y.diffStats,upstreamComparison:y.upstreamComparison===void 0?w.status?.upstreamComparison:y.upstreamComparison};C.set(n,{...w,isGitRepo:!0,status:_,diffCache:j,indexRevision:E?w.indexRevision+1:w.indexRevision,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:k?Date.now():w.lastStatusChange}),e({directories:C})}else{const C=new Map(t().directories),w=C.get(n)??Nt();C.set(n,{...w,isGitRepo:!0,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:w.lastStatusChange}),e({directories:C})}}catch(x){console.error("Failed to fetch git status:",x)}finally{if(!u&&yn(d,n)){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingStatus:!1}),e({directories:x})}}return g})();lo.set(a,f);try{return await f}finally{lo.get(a)===f&&lo.delete(a)}},moveStatusPathsOptimistically:(n,r,s)=>{const o=new Set(r.map(h=>h.trim()).filter(Boolean));if(o.size===0)return null;const{directories:i}=t(),a=i.get(n),l=a?.status??null;if(!a||!l)return l;let d=!1;const f=[];for(const h of l.files){if(!o.has(h.path)){f.push(h);continue}const m=s==="stage"?EO(h):_O(h);m!==h&&(d=!0),jO(m)?d=!0:f.push(m)}if(!d)return l;dh(t().runtimeKey,n);const u=new Map(i);return u.set(n,{...a,status:{...l,files:f,isClean:f.length===0},indexRevision:a.indexRevision+1,lastStatusChange:Date.now()}),e({directories:u}),l},restoreStatus:(n,r)=>{const{directories:s}=t(),o=s.get(n);if(!o)return;dh(t().runtimeKey,n);const i=new Map(s);i.set(n,{...o,status:r,indexRevision:o.indexRevision+1,lastStatusChange:Date.now()}),e({directories:i})},bumpIndexRevision:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;dh(t().runtimeKey,n);const o=new Map(r);o.set(n,{...s,indexRevision:s.indexRevision+1}),e({directories:o})},fetchBranches:async(n,r,s={})=>{const o=Y(),i=hr(o,n),a=Vi.get(i);if(a)return a;const l=ls(n,"branches"),{silent:d=!1}=s,f=(async()=>{if(!d){const u=new Map(t().directories),h=u.get(n)??Nt();u.set(n,{...h,isLoadingBranches:!0}),e({directories:u})}try{const u=await r.getGitBranches(n);if(!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Nt();h.set(n,{...m,branches:u,isLoadingBranches:!1,lastBranchesFetch:Date.now()}),e({directories:h}),wO(l.runtimeKey,n,u)}catch(u){if(console.error("Failed to fetch git branches:",u),!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Nt();h.set(n,{...m,isLoadingBranches:!1}),e({directories:h})}})().finally(()=>{Vi.get(i)===f&&Vi.delete(i)});return Vi.set(i,f),f},fetchLog:async(n,r,s,o={})=>{const{directories:i}=t(),a=i.get(n),l=s??a?.logMaxCount??25,d=Y(),f=NO(d,n,l),u=$i.get(f);if(u)return u;const h=ls(n,"log"),{silent:m=!1}=o,g=(async()=>{if(!m){const x=new Map(t().directories),b=x.get(n)??Nt();x.set(n,{...b,isLoadingLog:!0}),e({directories:x})}try{const x=await r.getGitLog(n,{maxCount:l});if(!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Nt();b.set(n,{...S,log:x,isLoadingLog:!1,lastLogFetch:Date.now(),logMaxCount:l}),e({directories:b})}catch(x){if(console.error("Failed to fetch git log:",x),!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Nt();b.set(n,{...S,isLoadingLog:!1}),e({directories:b})}})().finally(()=>{$i.get(f)===g&&$i.delete(f)});return $i.set(f,g),g},fetchRemotes:async(n,r,s={})=>{const o=r.getRemotes;if(typeof o!="function")return;const i=r.getRemoteUrl,a=Y(),l=hr(a,n),d=zi.get(l);if(d)return d;const f=ls(n,"remotes"),{silent:u=!1}=s,h=(async()=>{if(!u){const m=new Map(t().directories),g=m.get(n)??Nt();m.set(n,{...g,isLoadingRemotes:!0}),e({directories:m})}try{const m=o(n),g=typeof i=="function"?i(n).then(v=>({ok:!0,value:v}),()=>({ok:!1,value:null})):Promise.resolve({ok:!0,value:null}),[x,b]=await Promise.all([m,g]);if(!yn(f,n))return;const S=new Map(t().directories),y=S.get(n)??Nt();S.set(n,{...y,remotes:x,remoteUrl:b.ok?b.value:y.remoteUrl,lastRemotesFetch:Date.now(),isLoadingRemotes:!1}),e({directories:S})}catch(m){if(console.error("Failed to fetch git remotes:",m),!yn(f,n))return;const g=new Map(t().directories),x=g.get(n)??Nt();g.set(n,{...x,isLoadingRemotes:!1}),e({directories:g})}})().finally(()=>{zi.get(l)===h&&zi.delete(l)});return zi.set(l,h),h},ensureRemotes:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.remotes!==null&&s?.remotes!==void 0&&o-(s?.lastRemotesFetch??0)<Gy||await t().fetchRemotes(n,r,{silent:s?.remotes!=null})},invalidateRemotes:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;const o=new Map(r);o.set(n,{...s,lastRemotesFetch:0}),e({directories:o})},fetchLogQuery:async(n,r,s,o={})=>{const{force:i=!1}=o,a=Jy(s),l=Y(),d=LO(l,n,a),f=Date.now(),u=t().directories.get(n)?.logQueryCache.get(a);if(!i&&u&&f-u.fetchedAt<hO)return u.log;const h=Ui.get(d);if(h)return h;const m=ls(n,`log-query:${a}`),g=(async()=>{try{const x=await r.getGitLog(n,{maxCount:s.maxCount,from:s.from,to:s.to,all:s.all,file:s.file});if(!yn(m,n))return u?.log??null;const b=new Map(t().directories),S=b.get(n)??Nt(),y=new Map(S.logQueryCache);if(y.set(a,{log:x,fetchedAt:Date.now()}),y.size>pO){let v=null,C=Number.POSITIVE_INFINITY;for(const[w,I]of y)I.fetchedAt<C&&(C=I.fetchedAt,v=w);v!==null&&y.delete(v)}return b.set(n,{...S,logQueryCache:y}),e({directories:b}),x}catch(x){return console.error("Failed to fetch git log query:",x),u?.log??t().directories.get(n)?.logQueryCache.get(a)?.log??null}})().finally(()=>{Ui.get(d)===g&&Ui.delete(d)});return Ui.set(d,g),g},getCachedLogQuery:(n,r)=>{const s=Jy(r);return t().directories.get(n)?.logQueryCache.get(s)?.log??null},fetchAll:async(n,r,s={})=>{const{directories:o}=t();let i=o.get(n);if(!i){i=Nt();const h=new Map(o);h.set(n,i),e({directories:h})}const{force:a=!1,silentIfCached:l=!1}=s,d=Date.now();await t().fetchStatus(n,r,{silent:l&&!!i?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;await t().fetchBranches(n,r);const u=d-(f.lastLogFetch||0);(a||u>aO||!f.log)&&await t().fetchLog(n,r)},getDiff:(n,r)=>t().directories.get(n)?.diffCache.get(r)??null,setDiff:(n,r,s,o)=>{if(o&&o!==t().runtimeKey||e4(s)>Md)return;const i=new Map(t().directories),a=i.get(n)??Nt(),l=new Map(a.diffCache);l.set(r,{...s,fetchedAt:Date.now()});const d=tv(l);i.set(n,{...a,diffCache:d}),e({directories:nv(i)})},clearDiffCache:(n,r)=>{tl(n),ls(n,"diff");const s=new Map(t().directories),o=s.get(n);if(!o||o.diffCache.size===0)return;const i=new Map(o.diffCache);if(r)for(const a of r)i.delete(a);else i.clear();i.size!==o.diffCache.size&&(s.set(n,{...o,diffCache:i}),e({directories:s}))},fetchAllDiffs:async(n,r)=>{const s=t().directories.get(n);if(!s?.status?.files||s.status.files.length===0)return;const o=s.status.files.map(i=>i.path).slice(0,Zy);await t().prefetchDiffs(n,r,o,{maxFiles:Zy})},prefetchDiffs:async(n,r,s,o={})=>{const i=ls(n,"diff"),a=t().directories.get(n);if(!a?.status?.files||a.status.files.length===0||s.length===0)return;const{maxFiles:l=mO}=o,d=new Set(a.status.files.map(k=>k.path)),f=a.status.diffStats,u=PO(n),h=[],m=new Set;for(const k of s){if(!k||m.has(k)||(m.add(k),!d.has(k))||a.diffCache.has(k)||u.has(k))continue;const _=f?.[k];_&&_.insertions+_.deletions>yO||h.push(k)}const g=h.slice(0,Math.max(1,l));if(g.length===0)return;const x=$l(n);if(typeof document<"u"&&document.hidden)return;g.forEach(k=>u.add(k));let b=0;const S=[],y=()=>{const k=b;return b+=1,k<g.length?g[k]:null},v=async k=>{const _=r.getGitFileDiff(n,{path:k}),M=new Promise((O,N)=>{setTimeout(()=>N(new Error(`Timed out after ${Yy}ms`)),Yy)}),L=await Promise.race([_,M]);return{path:k,diff:{original:L.original??"",modified:L.modified??"",isBinary:L.isBinary}}},C=async()=>{for(;;){if(x!==$l(n)||!yn(i,n))return;const k=y();if(!k)return;try{S.push(await v(k))}catch{}finally{u.delete(k)}}},w=Math.min(gO,g.length);if(await Promise.allSettled(Array.from({length:w},()=>C())),g.forEach(k=>u.delete(k)),x!==$l(n)||!yn(i,n))return;const I=new Map(t().directories),E=I.get(n);if(!E)return;const T=new Map(E.diffCache),A=Date.now();S.forEach(k=>{T.set(k.path,{...k.diff,fetchedAt:A})});const j=tv(T);I.set(n,{...E,diffCache:j}),e({directories:nv(I)})},setLogMaxCount:(n,r)=>{const s=new Map(t().directories),o=s.get(n)??Nt();s.set(n,{...o,logMaxCount:r}),e({directories:s})},ensureStatus:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.status&&o-s.lastStatusFetch<lO||await t().fetchStatus(n,r,{silent:!!s?.status})},ensureAll:(n,r)=>{const s=hr(Y(),n),o=qi.get(s);if(o)return o;const i=(async()=>{const a=t().directories.get(n),l=Date.now();(!a?.status||a.status.diffStats===void 0||l-(a?.lastStatusFetch??0)>=dO)&&await t().fetchStatus(n,r,{silent:!!a?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;const u=[];(!f.branches||l-f.lastBranchesFetch>=fO)&&u.push(t().fetchBranches(n,r,{silent:!!f.branches})),(!f.log||l-f.lastLogFetch>=uO)&&u.push(t().fetchLog(n,r,void 0,{silent:!!f.log})),(f.remotes==null||l-(f.lastRemotesFetch??0)>=Gy)&&u.push(t().fetchRemotes(n,r,{silent:f.remotes!=null})),u.length>0&&await Promise.all(u)})();return qi.set(s,i),i.finally(()=>{qi.get(s)===i&&qi.delete(s)}),i},refresh:async(n,r={})=>{const{activeDirectory:s}=t();s&&await t().fetchAll(s,n,r)}}),{name:"git-store"})),DO=e=>vt(t=>e?t.directories.get(e)?.status??null:null),t4=e=>vt(t=>e?t.directories.get(e)?.branches??null:null),OO=e=>vt(t=>e?t.directories.get(e)?.log??null:null),HO=e=>vt(t=>e?t.directories.get(e)?.remotes??null:null),FO=e=>vt(t=>e?t.directories.get(e)?.remoteUrl??null:null),BO=e=>vt(t=>e?t.directories.get(e)?.isLoadingRemotes??!1:!1),ku=e=>vt(t=>e?t.directories.get(e)?.isGitRepo??null:null),VO=e=>vt(t=>e?t.directories.get(e)?.status?.current?.trim()??null:null),iv={current:new Map},$O=new Map,zO=(e=!0)=>vt(t=>{if(!e)return $O;const n=iv.current;let r=n.size===t.directories.size;if(r){for(const[o,i]of t.directories)if(n.get(o)!==(i.status?.current??null)){r=!1;break}}if(r)return n;const s=new Map;for(const[o,i]of t.directories)s.set(o,i.status?.current??null);return iv.current=s,s}),UO=e=>{const t=p.useRef(new Map);return vt(n=>{const r=t.current;let s=r.size===e.length;if(s)for(const i of e){const a=n.directories.get(i),l=r.get(i);if(!l||(a?.isGitRepo??null)!==l.isGitRepo||(a?.status?.current??null)!==l.branch){s=!1;break}}if(s)return r;const o=new Map;for(const i of e){const a=n.directories.get(i);o.set(i,{isGitRepo:a?.isGitRepo??null,branch:a?.status?.current??null})}return t.current=o,o})},qO=e=>vt(t=>e?t.directories.get(e)?.isLoadingStatus??!1:!1),WO=e=>vt(t=>e?t.directories.get(e)?.isLoadingLog??!1:!1),KO=e=>vt(t=>e?t.directories.get(e)?.isLoadingBranches??!1:!1),eQ=Object.freeze(Object.defineProperty({__proto__:null,useGitAllBranches:zO,useGitBranchLabel:VO,useGitBranches:t4,useGitLoadingBranches:KO,useGitLoadingLog:WO,useGitLoadingRemotes:BO,useGitLoadingStatus:qO,useGitLog:OO,useGitRemoteUrl:FO,useGitRemotes:HO,useGitRepoStatusMap:UO,useGitStatus:DO,useGitStore:vt,useIsGitRepo:ku},Symbol.toStringTag,{value:"Module"})),n4=p.createContext(null),tQ=({actions:e,children:t})=>c.jsx(n4.Provider,{value:e,children:t}),Ga=()=>p.useContext(n4),GO=/^[A-Za-z]:\/$/,P1=/^[A-Za-z]:\//,Wt=e=>{if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let s=n.replace(/\/+/g,"/");r&&!s.startsWith("//")&&(s=`/${s}`);const o=s==="/",i=GO.test(s);return!o&&!i&&(s=s.replace(/\/+$/,"")),s},ZO=e=>{const t=Wt(e);return t.startsWith("/")||P1.test(t)},_d=e=>{const t=Wt(e);return P1.test(t)||t.startsWith("//")?t.toLowerCase():t},r4=e=>e.split("/").filter(Boolean),YO=(e,t)=>{const n=[...e];for(const r of r4(t))if(r!=="."){if(r===".."){n.length>0&&n.pop();continue}n.push(r)}return n},Za=(e,t)=>{const n=Wt(t);if(!n)return Wt(e);if(ZO(n))return n;const r=Wt(e);if(!r)return n;const s=P1.test(r)?r.slice(0,2):"",o=r.startsWith("//"),i=r.startsWith("/")&&!o,a=s?r.slice(2):r,d=YO(r4(a),n).join("/");return s?d?`${s}/${d}`:`${s}/`:o?`//${d}`:i?`/${d}`:d},Mu=(e,t)=>{const n=Wt(e),r=Wt(t);if(!n||!r)return!1;const s=_d(n),o=_d(r);return s===o||s.startsWith(`${o}/`)},s4=(e,t)=>{const n=Wt(e),r=Wt(t);return n?r?_d(n)===_d(r)?".":Mu(n,r)?n.slice(r.length+1):n:n:""},uh=(e,t)=>{const n=Wt(e),r=Wt(t);if(n&&(!r||Mu(r,n))||!r)return n;const s=r.lastIndexOf("/");return s===0?"/":s<0?n||r:/^[A-Za-z]:\//.test(r)&&s===2?r.slice(0,3):r.slice(0,s)},XO=new Set(["edit","multiedit","write","apply_patch","create","file_write"]),D1=e=>"insertions"in e,eo=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},JO=e=>{let t=0,n=0;for(const r of e.split(`
71
- `))r.startsWith("+")&&!r.startsWith("+++")&&t++,r.startsWith("-")&&!r.startsWith("---")&&n++;return{added:t,removed:n}},nQ=e=>{const t=[],n=new Set;for(const r of e){if(r.type!=="tool"||!r.tool||!XO.has(r.tool))continue;const s=r.tool,o=r.messageId??r.messageID??"",i=r.state;if(i?.status&&i.status!=="completed")continue;const a=t.length,l=i?.metadata,d=Array.isArray(l?.files)?l.files:[];for(const f of d){if(!f||typeof f!="object")continue;const u=f,h=u.relativePath||u.filePath||"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:eo(u.additions)??void 0,deletions:eo(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(d.length===0&&l?.filediff&&typeof l.filediff=="object"){const f=l.filediff,u=typeof f.file=="string"?f.file:"";u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o,additions:eo(f.additions)??void 0,deletions:eo(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(d.length===0&&Array.isArray(l?.results))for(const f of l.results){if(!f||typeof f!="object")continue;const u=f.filediff;if(!u||typeof u!="object")continue;const h=typeof u.file=="string"?u.file:"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:eo(u.additions)??void 0,deletions:eo(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(t.length===a){const f=i?.input,u=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o}))}if(t.length===a){const f=typeof l?.patch=="string"?l.patch.trim():typeof l?.diff=="string"?l.diff.trim():"";if(f&&!n.has("Diff")){n.add("Diff");const u=JO(f);t.push({path:"Diff",tool:s,partId:r.id,messageID:o,additions:u.added,deletions:u.removed})}}}return t},o4=(e,t,n)=>{const r=[];for(const s of e){const o=s.index?.trim()??"",i=s.working_dir?.trim()??"",a=!!(o&&o!=="?"),l=!!(i||o==="?"),d=i||o;if(!d||d==="!")continue;const f=t?.[s.path];r.push({path:Za(n,s.path),relativePath:s.path,insertions:f?.insertions??0,deletions:f?.deletions??0,status:d,hasStagedChanges:a,hasWorkingChanges:l})}return r},QO=(e,t)=>s4(e,t),eH=(e,t)=>{const n=D1(e)&&e.relativePath?e.relativePath:QO(e.path,t),r=n.split("/").pop()??n,s=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";return{fileName:r,dirPart:s}},tH=e=>D1(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},nH=({files:e,currentDirectory:t,onOpenFile:n})=>c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Changed files"}),c.jsx("span",{className:"typography-meta tabular-nums",children:e.length})]}),c.jsx("div",{className:"max-h-[260px] overflow-y-auto",children:e.map((r,s)=>{const{fileName:o,dirPart:i}=eH(r,t),a=tH(r);return c.jsxs("button",{type:"button",className:"relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none text-left hover:bg-interactive-hover",title:`Open ${r.path}`,onClick:()=>n(r),children:[c.jsx(pr,{filePath:r.path,className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 flex items-baseline overflow-hidden",title:r.path,children:i?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:o})]})]}):c.jsx("span",{className:"truncate text-foreground",children:o})}),a.additions>0||a.deletions>0?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-baseline gap-1 typography-micro tabular-nums",children:[a.additions>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.additions]}):null,a.deletions>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.deletions]}):null]}):null]},`${r.path}:${s}`)})})]}),i4="w-max min-w-[280px] max-w-full rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)] origin-[var(--transform-origin)]",a4={maxWidth:"calc(100cqw - 4ch)",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},c4=p.memo(({align:e="start"})=>{const[t,n]=p.useState(!1),r=p.useRef(null),s=Xn()??null,o=p.useContext($a),i=ku(s),a=vt(C=>s?C.directories.get(s)?.status??null:null),l=Ga(),d=re(C=>C.isMobile),{enabled:f}=mu(),u=d&&!f;p.useEffect(()=>{if(!t)return;const C=w=>{r.current&&!r.current.contains(w.target)&&n(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const h=p.useMemo(()=>!s||i!==!0||!a||a.isClean?[]:o4(a.files,a.diffStats,s),[i,a,s]),{totalAdded:m,totalRemoved:g}=p.useMemo(()=>{let C=0,w=0;for(const I of h)C+=I.insertions,w+=I.deletions;return{totalAdded:C,totalRemoved:w}},[h]);if(!s||i!==!0||h.length===0)return null;const x=C=>{if(!s||!D1(C))return;n(!1);const w=C.path;if(l){l.openChanges({diffPath:C.relativePath,staged:C.hasStagedChanges&&!C.hasWorkingChanges});return}const I=o?.editor;if(I){I.openFile(w);return}const E=re.getState(),T=C.hasStagedChanges&&!C.hasWorkingChanges;if(!E.isMobile){E.openContextDiff(s,C.relativePath,T);return}E.navigateToDiff(C.relativePath,T)},b=h.length,S=b===1?`${b} file`:`${b} files`,y=b===1?"1 change":`${b} changes`,v=c.jsxs(c.Fragment,{children:[c.jsx($,{name:"git-branch",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u?c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-meta",children:y}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-meta",children:S}),c.jsx("span",{className:"status-row__changed-label min-w-0 typography-meta text-foreground truncate",children:"changed"})]}),c.jsxs("span",{className:"inline-flex shrink-0 items-baseline gap-1 typography-meta tabular-nums",children:[m>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}):null,g>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",g]}):null]}),t?c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5 shrink-0"}):c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5 shrink-0"})]});return c.jsxs("div",{className:"relative",ref:r,children:[c.jsx("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 text-left text-muted-foreground",onClick:()=>n(C=>!C),"aria-expanded":t,children:v}),t&&c.jsx("div",{style:{...a4,maxWidth:"min(28rem, calc(100cqw - 4ch))"},className:R(i4,"absolute bottom-full mb-1 z-50",e==="end"?"right-0":"left-0","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:c.jsx(nH,{files:h,currentDirectory:s,onOpenFile:x})})]})});c4.displayName="PendingChangesBar";const rH=p.createContext("default"),Iu=()=>p.useContext(rH);let Vp=!1;const $p=new Set,jd=()=>Vp,rQ=e=>{if(Vp!==e){Vp=e;for(const t of[...$p])try{t()}catch{}}},sH=e=>($p.add(e),()=>{$p.delete(e)}),l4=()=>p.useSyncExternalStore(sH,jd,jd);function oH({className:e,style:t,...n}){return c.jsx(Os,{"data-slot":"command",style:{color:"var(--surface-elevated-foreground)",...t},className:R("flex h-full w-full flex-col overflow-hidden rounded-xl",e),...n})}const d4=H.forwardRef(({className:e,...t},n)=>c.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[c.jsx($,{name:"search",className:"size-4 shrink-0 opacity-50"}),c.jsx(Os.Input,{ref:n,"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));d4.displayName="CommandInput";function iH({className:e,children:t,scrollbarClassName:n,disableHorizontal:r,...s}){return c.jsx(Yn,{as:Os.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",e),scrollbarClassName:n??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:r??!0,...s,children:t})}function aH({...e}){return c.jsx(Os.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...e})}function cH({className:e,...t}){return c.jsx(Os.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[length:var(--text-meta)] [&_[cmdk-group-heading]]:font-medium",e),...t})}function sQ({className:e,...t}){return c.jsx(Os.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",e),...t})}function lH({className:e,...t}){return c.jsx(Os.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function oQ({className:e,...t}){const n=o=>{const i=o.trim().toLowerCase();return i==="ctrl"||i==="control"?c.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?c.jsx($,{name:"command",className:"size-3.5"}):i==="⇧"?c.jsx($,{name:"arrow-up",className:"size-3.5"}):c.jsx("span",{className:"text-xs font-medium",children:o})},r=typeof t.children=="string"?t.children:"",s=r?r.split("+").map(o=>o.trim()).filter(Boolean):[];return c.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",e),...t,children:s.length>0?s.map((o,i)=>c.jsxs(H.Fragment,{children:[i>0&&c.jsx("span",{className:"text-xs text-subtle-foreground",children:"+"}),n(o)]},`${o}-${i}`)):t.children})}const fh=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.code==="SESSION_BUSY"||typeof t.message=="string"&&t.message.includes("SESSION_BUSY")},iQ=e=>!!(e&&typeof e=="object"&&e.deferred===!0),aQ=e=>`${e} saved. It will apply when active sessions are idle.`,cQ=e=>`${e} could not be changed while a session is running. Try again when it finishes.`,dH=5e3,jn=new Map,Nr=new Map,Tr=new Map,ma=new Map,vo=(e,t)=>`${e}
72
- ${t?.trim()??""}`,Po=e=>{ma.set(e,(ma.get(e)??0)+1),Nr.delete(e)},lQ=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=vo(t,e);jn.delete(r),Po(r);return}const n=new Set([...jn.keys(),...Nr.keys(),...Tr.keys()]);for(const r of n)r.startsWith(`${t}
73
- `)&&(jn.delete(r),Po(r))},hh=e=>{const t=new Set([...jn.keys(),...Nr.keys(),...Tr.keys()]);for(const n of t)n.startsWith(`${e}
74
- `)&&(jn.delete(n),Po(n))},nl=e=>e.prompts.map(t=>({id:t.id,name:t.name,...typeof t.description=="string"?{description:t.description}:{},...typeof t.content=="string"?{content:t.content}:{},location:["global","project","package","path"].includes(t.location)?t.location:"path",editable:t.editable===!0})),zl=Et()(gr((e,t)=>({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null,setSelectedPrompt:n=>e({selectedPromptId:n}),setPromptDraft:n=>e({promptDraft:n}),resetForRuntimeSwitch:()=>{jn.clear(),Nr.clear(),Tr.clear(),ma.clear(),e({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null})},loadPrompts:async n=>{const r=Y(),s=typeof n=="string"&&n.trim().length>0?n.trim():void 0,o=vo(r,s),i=Date.now(),a=Tr.get(o);e({activeCacheKey:o,prompts:a??[],isLoading:!0});const l=jn.get(o)??0;if(l>0&&i-l<dH)return e({isLoading:!1}),!0;const d=Nr.get(o);if(d)return d;const f=ma.get(o)??0,u=(async()=>{try{const h=s?await Ie.listResources(s,{runtimeKey:r}):await Ie.listResources({runtimeKey:r});if(Y()!==r)return!1;if((ma.get(o)??0)!==f)return e(g=>g.activeCacheKey===o?{isLoading:!1}:g),!0;const m=nl(h);return Tr.set(o,m),jn.set(o,Date.now()),e(g=>g.activeCacheKey===o?{prompts:m,isLoading:!1,...g.selectedPromptId&&!m.some(x=>x.id===g.selectedPromptId)?{selectedPromptId:null}:{}}:g),!0}catch{return e(h=>h.activeCacheKey===o?{isLoading:!1}:h),!1}})();Nr.set(o,u);try{return await u}finally{Nr.get(o)===u&&Nr.delete(o)}},createPrompt:async(n,r,s)=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ie.createPromptTemplate({name:n,description:s.description,content:r,location:s.location},i,{runtimeKey:o});if(Y()!==o)return a.deferred===!0?"deferred":!0;const l=vo(o,i),d=nl(a);Po(l),Tr.set(l,d),hh(o),jn.set(l,Date.now());const f=d.find(u=>u.name===n&&u.location===s.location);return e(u=>u.activeCacheKey===l?{prompts:d,promptDraft:null,selectedPromptId:f?.id??null,isLoading:!1}:u),xl(s.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return fh(a)?"busy":!1}},updatePrompt:async(n,r,s)=>{const o=Y(),i=t().prompts.find(l=>l.id===n);if(!i||i.editable!==!0)return!1;const a=typeof s=="string"&&s.trim().length>0?s.trim():void 0;if((i.location==="project"||r.location==="project")&&!a)return!1;try{const l=await Ie.updatePromptTemplate(i.id,{...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{},...r.content!==void 0?{content:r.content}:{},...r.location!==void 0?{location:r.location}:{}},a,{runtimeKey:o});if(Y()!==o)return l.deferred===!0?"deferred":!0;const d=vo(o,a),f=nl(l);Po(d),Tr.set(d,f),hh(o),jn.set(d,Date.now());const u=f.find(h=>h.name===(r.name??i.name)&&h.location===(r.location??i.location));return e(h=>h.activeCacheKey===d?{prompts:f,selectedPromptId:u?.id??null,isLoading:!1}:h),xl(i.location==="global"||r.location==="global"?null:a),l.deferred===!0?"deferred":!0}catch(l){return fh(l)?"busy":!1}},deletePrompt:async(n,r)=>{const s=Y(),o=t().prompts.find(a=>a.id===n);if(!o||o.editable!==!0)return!1;const i=r?.trim()?r.trim():void 0;if(o.location==="project"&&!i)return!1;try{const a=await Ie.deletePromptTemplate(o.id,i,{runtimeKey:s});if(Y()!==s)return a.deferred===!0?"deferred":!0;const l=vo(s,i),d=nl(a);return Po(l),Tr.set(l,d),hh(s),jn.set(l,Date.now()),e(f=>f.activeCacheKey===l?{prompts:d,...f.selectedPromptId===n?{selectedPromptId:null}:{},isLoading:!1}:f),xl(o.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return fh(a)?"busy":!1}},getPromptById:n=>t().prompts.find(r=>r.id===n)}),{name:"prompt-templates-store"})),uH="pichamber.json",fH=".pichamber",hH=[".config","pichamber","projects"];function O1(){const e=zr();return e?.files?e.files:null}const pH=80,mH=4e3,gH=2e3,yH=300,vH=new Set(["macos","linux","windows"]),Do=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},La=(e,t)=>{const n=Do(e),r=t.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},u4=e=>La(La(e,fH),uH),Eu=()=>{const e="/api";return e.startsWith("/"),e},H1=async(e,t)=>{try{const n=await Rt(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return n.ok?{ok:!0,data:await n.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},xH=async e=>{const t=O1();if(t?.createDirectory)try{if((await t.createDirectory(e))?.success)return!0}catch{}return!!(await H1(`${Eu()}/fs/mkdir`,{path:e})).ok},f4=async(e,t)=>{try{const n=await Rt(`${Eu()}/fs/read`,{query:{path:e,optional:"true",...t?{directory:t}:{}},cache:"no-store"});return n.ok?await n.text():null}catch{return null}},bH=async(e,t)=>{const n=O1();if(n?.writeFile)try{if((await n.writeFile(e,t))?.success)return!0}catch{}return!!(await H1(`${Eu()}/fs/write`,{path:e,content:t})).ok},h4=async()=>{const e=await fC();let t=e.home?Do(e.home):null;const n=e.pichamberDataDir?Do(e.pichamberDataDir):null;if(!t)try{const r=await hC();r&&r.trim().length>0&&(t=Do(r))}catch{}return{home:t,pichamberDataDir:n}},wH=async()=>(await h4()).home,SH=async()=>(await h4()).pichamberDataDir,p4=async()=>{const e=await SH();if(e)return La(e,"projects");const t=await wH();return t?hH.reduce((n,r)=>La(n,r),t):null},CH=e=>{const t=typeof e?.path=="string"?e.path.trim():"",n=t?Do(t):"";return n&&mm(n)||null},m4=async e=>{const t=await p4();if(!t)return null;const n=CH(e);return n?La(t,`${n}.json`):null},rl=(e,t)=>e.length<=t?e:e.slice(0,t),kH=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(typeof r!="string")continue;const s=r.trim().toLowerCase();!vH.has(s)||n.has(s)||(n.add(s),t.push(s))}return t},MH=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=typeof s.id=="string"?s.id.trim():"",i=rl(typeof s.name=="string"?s.name.trim():"",pH),a=rl(typeof s.command=="string"?s.command.trim():"",mH);if(!o||!i||!a||n.has(o))continue;n.add(o);const l=typeof s.icon=="string"?s.icon.trim():"",d=kH(s.platforms),f=s.autoOpenUrl===!0,u=typeof s.openUrl=="string"?s.openUrl.trim():"",h=rl(u,gH),m=typeof s.desktopOpenSshForward=="string"?s.desktopOpenSshForward.trim():"",g=rl(m,yH);t.push({id:o,name:i,command:a,icon:l||null,...f?{autoOpenUrl:!0}:{},...h?{openUrl:h}:{},...g?{desktopOpenSshForward:g}:{},...d.length>0?{platforms:d}:{}})}return t},g4=e=>{const t=MH(e?.actions),n=typeof e?.primaryActionId=="string"?e.primaryActionId.trim():"",r=n&&t.some(s=>s.id===n)?n:null;return{actions:t,primaryActionId:r}};async function F1(e){const t=typeof e?.path=="string"?e.path.trim():"";if(!t)return null;const n=await m4(e),r=async(a,l)=>{const d=await f4(a,l);return d===null?null:d},s=a=>{if(typeof a!="string")return null;const l=a.trim();if(!l)return null;try{const d=JSON.parse(l);return!d||typeof d!="object"?null:d}catch{return null}};if(n){const a=s(await r(n));if(a)return a}const o=u4(t),i=s(await r(o,t));if(!i)return null;try{await y4(e,i)&&await _H(t)}catch{}return i}async function y4(e,t){const n=typeof e?.path=="string"?e.path.trim():"";if(!n)return!1;const r=await p4(),s=await m4(e);if(!r||!s)return!1;try{if(!await xH(r))return!1;const i=await f4(s);let a={};if(typeof i=="string"&&i.trim())try{const f=JSON.parse(i);f&&typeof f=="object"&&!Array.isArray(f)&&(a=f)}catch{a={}}const l={};a.version!==void 0&&(l.version=a.version);const d=JSON.stringify({...a,...t,...l,projectPath:Do(n)},null,2);return await bH(s,d)}catch(o){return console.error("Failed to write pichamber config:",o),!1}}async function v4(e,t){const r={...await F1(e)||{},...t};return y4(e,r)}async function IH(e){const t=await F1(e);return R5(t?.draftStarters)}async function EH(e,t){return v4(e,{draftStarters:R5(t)})}async function dQ(e){const t=await F1(e);return g4({actions:t?.projectActions,primaryActionId:t?.projectActionsPrimaryId})}async function uQ(e,t){const n=g4({actions:t.actions,primaryActionId:t.primaryActionId});return v4(e,{projectActions:n.actions,projectActionsPrimaryId:n.primaryActionId??void 0})}async function _H(e){const t=u4(e),n=O1();if(n?.delete)try{await n.delete(t);return}catch{}try{await H1(`${Eu()}/fs/delete`,{path:t})}catch{}}const jH=[],Ii=(e,t)=>`${e}:${Hh(t)}`;function TH(){const e=re(N=>N.globalDraftStarters),t=zl(N=>N.prompts),n=zl(N=>N.activeCacheKey),r=zl(N=>N.loadPrompts),s=lt(N=>N.activeProjectId),o=lt(N=>N.projects),i=Xn(),a=p.useMemo(()=>{if(!s)return null;const N=o.find(D=>D.id===s);return N?.path?{id:N.id,path:N.path}:null},[s,o]),[l,d]=p.useState([]),f=p.useRef(new Set),[u,h]=p.useState(0);p.useEffect(()=>{let N=!1;if(!a){d([]);return}return IH(a).then(D=>{N||d(D)}).catch(()=>{N||d([])}),()=>{N=!0}},[a]),p.useEffect(()=>Zt(()=>{f.current.clear(),h(D=>D+1),d([])}),[]);const m=p.useCallback(()=>{i&&r(i)},[i,r]);p.useEffect(()=>{if(!i)return;let N=!1;const D=Y();return r(i).then(W=>{N||Y()===D&&W&&(f.current.add(i),h(z=>z+1))}),()=>{N=!0}},[i,r]);const g=vo(Y(),i),x=n===g,b=x?t:jH,S=p.useMemo(()=>pC(b),[b]),y=i?x&&f.current.has(i):!1,v=p.useCallback((N,D)=>{if(N.type==="text"){const z=mC[N.key];return z?{id:Ii(D,N),ref:N,group:D,label:z.label,icon:z.icon,insertText:z.text,promptName:""}:null}return S.get(N.name)?{id:Ii(D,N),ref:N,group:D,label:Qu(N.name),icon:Ju,insertText:`/${N.name} `,promptName:N.name}:y?null:{id:Ii(D,N),ref:N,group:D,label:Qu(N.name),icon:Ju,insertText:`/${N.name} `,promptName:N.name}},[S,y]),C=p.useMemo(()=>e??Mc,[e]),w=p.useMemo(()=>C.map(N=>v(N,"global")).filter(N=>N!==null),[C,v]),I=p.useMemo(()=>l.map(N=>v(N,"project")).filter(N=>N!==null),[l,v]),{global:E,project:T}=p.useMemo(()=>gC(I,w),[I,w]),A=p.useMemo(()=>{const N=new Set;for(const D of C)N.add(Hh(D));for(const D of l)N.add(Hh(D));return N},[C,l]),j=p.useMemo(()=>{const N=new Map;for(const D of b){if(D.editable!==!0||D.location!=="global"&&D.location!=="project")continue;const W=N.get(D.name),z=D.location==="project"?"project":"user",X={type:"prompt",name:D.name,label:Qu(D.name),icon:Ju,section:"prompt",scope:z};if(!W){N.set(D.name,X);continue}z==="project"&&W.scope!=="project"&&N.set(D.name,X)}return[...N.values()].filter(D=>!A.has(`${D.type}:${D.name}`))},[b,A]),k=p.useCallback(N=>{re.getState().setGlobalDraftStarters(N),$r({draftStarters:N})},[]),_=p.useCallback(N=>{d(N),a&&EH(a,N)},[a]),M=p.useCallback(N=>{if(N.type!=="prompt")return;const D={type:"prompt",name:N.name};if(N.scope==="project"){if(!a||l.some(W=>Ic(W,D)))return;_([...l,D])}else{const W=e??Mc;if(W.some(z=>Ic(z,D)))return;k([...W,D])}},[a,l,e,_,k]),L=p.useCallback((N,D)=>{N==="project"?_(l.filter(W=>!Ic(W,D))):k((e??Mc).filter(z=>!Ic(z,D)))},[l,e,_,k]),O=p.useCallback((N,D,W)=>{const z=N==="project"?l:e??Mc,X=z.findIndex(P=>Ii(N,P)===D),F=z.findIndex(P=>Ii(N,P)===W);if(X<0||F<0||X===F)return;const U=S8([...z],X,F);N==="project"?_(U):k(U)},[l,e,_,k]);return{global:E,project:T,pinnable:j,hasProject:!!a,ensureLoaded:m,addStarter:M,removeStarter:L,reorder:O}}const x4="__draft-starter-trash__",b4="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors",AH=[{key:"prompt",headingKey:"Prompts"}],NH=({item:e,onInsert:t,onRemove:n,hideRemove:r})=>{const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:l,isDragging:d}=km({id:e.id});return c.jsxs("div",{ref:i,style:{transform:Mm.Translate.toString(a),transition:l},className:R("group/chip relative",d&&"z-10 opacity-60"),children:[c.jsxs("button",{type:"button",...s,...o,onClick:()=>t(e),className:"group inline-flex touch-none select-none items-center gap-1.5 rounded-full border border-transparent px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-[var(--interactive-hover)] hover:text-foreground",children:[c.jsx($,{name:e.icon,className:"h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"}),c.jsx("span",{className:"whitespace-nowrap",children:e.label})]}),r?null:c.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),n()},"aria-label":"Remove",title:"Remove",className:"absolute -right-1.5 -top-1.5 hidden h-4 w-4 items-center justify-center rounded-full border border-[var(--interactive-border)] bg-[var(--surface-elevated)] text-muted-foreground hover:text-foreground group-hover/chip:flex",children:c.jsx($,{name:"close",className:"h-2.5 w-2.5"})})]})},av=({items:e,onInsert:t,onRemove:n,hideRemove:r})=>c.jsx(Cm,{items:e.map(s=>s.id),strategy:k8,children:e.map(s=>c.jsx(NH,{item:s,onInsert:t,onRemove:()=>n(s),hideRemove:r},s.id))}),LH=()=>{const{currentTheme:e}=vr(),{setNodeRef:t,isOver:n}=M8({id:x4});return c.jsx("button",{type:"button",ref:t,"aria-label":"Remove",title:"Remove",className:R(b4,n?"border-destructive text-destructive":"text-muted-foreground"),style:{backgroundColor:e?.colors?.surface?.elevated,borderColor:n?void 0:e?.colors?.interactive?.border},children:c.jsx($,{name:"delete-bin",className:"h-4 w-4"})})},RH=({pinnable:e,onPick:t,className:n})=>c.jsxs(oH,{className:R("min-h-0",n),children:[c.jsx(d4,{placeholder:"Search prompts…"}),c.jsxs(iH,{children:[c.jsx(aH,{children:"Nothing to add"}),AH.map(r=>{const s=e.filter(o=>o.section===r.key);return s.length===0?null:c.jsx(cH,{heading:r.headingKey,children:s.map(o=>c.jsx(lH,{value:`${o.section} ${o.label} ${o.name}`,onSelect:()=>t(o),children:c.jsx("span",{className:"truncate",children:o.label})},`${o.type}:${o.name}`))},r.key)})]})]}),PH=({pinnable:e,onOpen:t,onAdd:n})=>{const{currentTheme:r}=vr(),[s,o]=p.useState(!1);return c.jsxs(gu,{open:s,onOpenChange:i=>{o(i),i&&t()},children:[c.jsx(Mj,{asChild:!0,children:c.jsx("button",{type:"button","aria-label":"Add a starter",title:"Add a starter",className:R(b4,"text-muted-foreground hover:bg-[var(--interactive-hover)] hover:text-foreground"),style:{backgroundColor:r?.colors?.surface?.elevated,borderColor:r?.colors?.interactive?.border},children:c.jsx($,{name:"add",className:"h-4 w-4"})})}),c.jsxs(yu,{className:"gap-0 overflow-hidden p-0 sm:max-w-sm",children:[c.jsx(vu,{className:"px-4 pb-2 pt-4 text-left",children:c.jsx(xu,{children:"Add a starter"})}),c.jsx(RH,{pinnable:e,onPick:i=>{n(i),o(!1)},className:"flex max-h-[60vh] flex-col"})]})]})},DH=({onInsert:e,className:t})=>{const{global:n,project:r,pinnable:s,ensureLoaded:o,addStarter:i,removeStarter:a,reorder:l}=TH(),{isMobile:d}=Dn(),[f,u]=p.useState(!1),h=bm(wa(V5,{activationConstraint:{distance:8}}),wa(B5,{activationConstraint:{delay:200,tolerance:6}})),m=p.useCallback(S=>n.find(y=>y.id===S)??r.find(y=>y.id===S),[n,r]),g=()=>u(!0),x=()=>u(!1),b=S=>{u(!1);const{active:y,over:v}=S;if(!v)return;const C=String(y.id),w=m(C);if(!w)return;if(String(v.id)===x4){a(w.group,w.ref);return}const I=String(v.id);if(C===I)return;const E=m(I);E&&E.group===w.group&&l(w.group,C,I)};return c.jsx(wm,{sensors:h,collisionDetection:Sm,measuring:{droppable:{strategy:C8.Always}},onDragStart:g,onDragCancel:x,onDragEnd:b,children:c.jsxs("div",{className:R("flex flex-wrap items-center justify-center gap-2",t),children:[n.length>0?c.jsx(av,{items:n,onInsert:e,onRemove:S=>a("global",S.ref),hideRemove:d}):null,r.length>0?c.jsx(av,{items:r,onInsert:e,onRemove:S=>a("project",S.ref),hideRemove:d}):null,d&&f?c.jsx(LH,{}):c.jsx(PH,{pinnable:s,onOpen:o,onAdd:i})]})})},w4=e=>re(n=>n.draftStartersVisible)?c.jsx(DH,{...e}):null,S4=()=>{const e=he(i=>i.currentSessionId),t=_w(),n=he(i=>i.newSessionDraft),r=lt(i=>i.activeProjectId),s=lt(i=>i.projects),o=nt(i=>i.currentDirectory);if(e){const i=t.find(a=>a.id===e);if(i?.directory)return i.directory}if(n?.open&&n.directoryOverride)return n.directoryOverride??void 0;if(r){const i=s.find(a=>a.id===r);if(i?.path)return i.path}return o??void 0},Ei=new Map,OH=(e,t)=>`${e}
75
- ${t?.trim()??""}`;function C4(e){const t=e?.trim()?e.trim():void 0,n=p.useSyncExternalStore(ik,sf,sf),r=zl(m=>m.prompts.map(g=>`${g.id}:${g.name}:${g.location}`).join("|")),s=Hr(m=>m.skills.map(g=>`${g.id}:${g.name}:${g.scope}`).join("|")),[o,i]=p.useState(()=>{if(!t)return Mr();const m=g0(Y(),t);return m?[...Mr(),...m]:Mr()}),[a,l]=p.useState(!1),[d,f]=p.useState(0),u=p.useRef(void 0),h=p.useRef({promptSignature:"",skillSignature:""});return p.useEffect(()=>{h.current={promptSignature:r,skillSignature:s}},[r,s]),p.useEffect(()=>Zt(()=>{fk(),Ei.clear(),u.current=void 0,i(Mr()),f(g=>g+1)}),[]),p.useEffect(()=>{const m=Y(),g=OH(m,t),x=`${g}
76
- ${n}`;if(!t){u.current=g,i(Mr());return}if(u.current!==g){u.current=g;const v=g0(m,t);i(v?[...Mr(),...v]:Mr())}const b=ck(m,t);if(b&&lk(b)){const v=b.promptSignature!==""&&b.promptSignature!==r,C=b.skillSignature!==""&&b.skillSignature!==s;if(!v&&!C){(b.promptSignature!==r||b.skillSignature!==s)&&uk(m,t,r,s),l(!1);return}}let S=!1;l(!0);const y=()=>{const v=Ei.get(x);let C;if(v)C=v;else{const w=n,I=h.current.promptSignature,E=h.current.skillSignature,T={},A=(async()=>{try{const j=await Ie.listCommands(t,{runtimeKey:m});if(Y()!==m||sf()!==w)return null;const k=sk(j.commands);return dk(m,t,k,{promptSignature:I,skillSignature:E}),k}catch{return null}finally{Ei.get(x)?.promise===T.promise&&Ei.delete(x)}})();T.promise=A,C={promise:A,promptSignature:I,skillSignature:E},Ei.set(x,C)}C.promise.then(w=>{if(!S&&Y()===m){if(w){i([...Mr(),...w]);const I=h.current,E=C.promptSignature!==""&&C.promptSignature!==I.promptSignature,T=C.skillSignature!==""&&C.skillSignature!==I.skillSignature;if(E||T){y();return}}l(!1)}}).catch(()=>{S||l(!1)})};return y(),()=>{S=!0}},[t,r,s,d,n]),{commands:o,isLoading:a}}const HH=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer"],FH=e=>typeof e=="string"&&HH.includes(e),BH=e=>{switch(e){case"concise":return"Keep replies short. Answer first, no preamble or recap of the question. Write like you're texting a colleague who already has the context — plain sentences, not headings or bullets. Reach for a list only when the content is genuinely a list; never use one to look organised.";case"detailed":return"Take the space you need to actually explain things. Walk through what's going on, why it matters, and where the real tradeoffs are. Prefer flowing prose over bullet points and headings — structure the answer with paragraphs and let the reasoning carry it. Lists are fine when something really is enumerable, but don't fragment a normal explanation into bullets.";case"mentor":return"Talk like a patient senior engineer pairing with someone less experienced. Explain the underlying idea before the answer, think out loud about how you'd approach it, and drop in a small concrete example when it actually helps. Keep it conversational — no lecture format, no checklists, no numbered steps unless the task literally is a sequence.";case"pushback":return"Don't agree automatically. If something I say sounds off — a wrong assumption, a flawed approach, a request that won't actually do what I think it will — push back first. Explain what you disagree with and why, and only proceed once I've responded. Disagreement is welcome; sycophancy is not. Don't soften it with 'you might want to consider' — just say it.";case"noFiller":return"Cut the filler. No 'Great question', no 'Certainly', no 'I'll help you with that', no restating what I just asked. No closing summary of what you did when the diff or output already shows it. No trailing 'let me know if you need anything else'. Open with the actual content and stop when you're done.";case"matchEnergy":return"Mirror the size and register of my message. A one-line question gets a one-line answer. A casual aside gets a casual reply, not a structured breakdown. If I write three words, don't respond with three paragraphs. Match the tone too — informal stays informal, technical stays technical. Don't inflate small asks into full essays.";case"warmPeer":return"Talk like a colleague, not an assistant. First person is fine and encouraged — 'I'd do this', 'I don't love that approach', 'that was sloppy of me'. Have actual opinions and share them. Push back when you disagree. Admit when you screwed up without grovelling. Skip the corporate helpfulness and performative politeness — just be a person."}},VH=({enabled:e,preset:t,customInstructions:n})=>e?t==="custom"?(typeof n=="string"?n.trim():"")||null:FH(t)?BH(t):null:null,k4=(e,t)=>{const n=e.reducer.bySession.get(t);return e.hydratedSessionIds.has(t)&&!e.sessionLoadErrorById.has(t)&&n!==void 0&&n.hasMoreBefore!==!0&&![...n.messages.values()].some(r=>r.role==="user")},$H=e=>e.newSessionDraftOpen||(e.sessionId!==null?k4(e.storeState,e.sessionId):!1),M4=e=>VH({enabled:e.responseStyleEnabled===!0,preset:e.responseStylePreset,customInstructions:e.responseStyleCustomInstructions});let ga=null,uo=null;const zH=e=>{ga={runtimeKey:Y(),value:M4(e)}};typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{zH(e.detail??{})});Zt(e=>{e.runtimeKey!==e.previousRuntimeKey&&(ga=null,uo=null)});const UH=async()=>{const e=Y();if(ga?.runtimeKey===e)return ga.value;if(uo?.runtimeKey===e)return uo.promise;const t=(async()=>{const n=await Rt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return null;const r=await n.json().catch(()=>null);if(!r||Y()!==e)return null;const s=M4(r);return ga={runtimeKey:e,value:s},s})();uo={runtimeKey:e,promise:t};try{return await t}finally{uo?.promise===t&&(uo=null)}},qH=async e=>{if(!$H({newSessionDraftOpen:e.newSessionDraftOpen,sessionId:e.sessionId,storeState:e.getStoreState()}))return null;const t=await UH().catch(()=>null);return!t||!e.newSessionDraftOpen&&e.sessionId!==null&&!k4(e.getStoreState(),e.sessionId)?null:t},cv="<system-reminder>",lv="</system-reminder>",WH=e=>{const t=e.trim();return t?t.startsWith(cv)&&t.endsWith(lv)?t:`${cv}
77
- ${t}
78
- ${lv}`:""},dv=e=>e.includes("@")?"paste":"manual",KH=({value:e,cursorPosition:t,inputSource:n="manual",insertedText:r})=>{if(n==="paste"&&r?.includes("@"))return null;const s=e.substring(0,t),o=s.lastIndexOf("@");if(o===-1)return null;const i=o>0?s[o-1]:null,a=s.substring(o+1);return!(!i||/\s/.test(i))||a.includes(" ")||a.includes(`
79
- `)?null:a},GH=/[\s()[\]{}<>"'`,.;:]/,ZH=/^[`"'<([{]+/,YH=/[)\]},.;:!?`"'>]+$/,uv=/@([^\s]+)/g;function XH(e,t){return t<=0?!0:GH.test(e[t-1])}function JH(e){return e.trim().replace(ZH,"").replace(YH,"")}function QH(e){if(!e||!e.includes("@"))return[];const t=[];uv.lastIndex=0;let n;for(;(n=uv.exec(e))!==null;){const r=n.index;if(!XH(e,r))continue;const s=n[1]??"",o=JH(s);if(!o)continue;const i=r+1+s.indexOf(o);t.push({start:r,end:i+o.length,raw:n[0],name:o})}return t}function eF(e,t){return!e||e.includes("<")||e.includes(">")?null:t.knownAgentNames.has(e.toLowerCase())?"agent":tF(e,t.confirmedMentions)?"file":null}function tF(e,t){return e.includes("/")||e.includes("\\")||e.includes(".")||t.has(e)}const nF=(e,t)=>t<=0||/\s/.test(e[t-1]);function rF(e,t){if(!e.startsWith("/")||e.indexOf(" ")!==-1)return null;const r=e.indexOf(`
80
- `),s=r===-1?e.length:r;return t>s?null:{kind:"command",query:e.substring(1,s)}}function sF(e,t,n,r){const s=e.substring(0,t),o=s.lastIndexOf(n);if(o===-1||!nF(s,o))return null;const i=s.substring(o+1);return i.includes(" ")||i.includes(`
81
- `)?null:{kind:r,query:i}}function oF(e,t,n){return n.inputMode==="shell"?null:rF(e,t)??sF(e,t,"#","snippet")??iF(e,t,n)}function iF(e,t,n){const r=KH({value:e,cursorPosition:t,inputSource:n.inputSource,insertedText:n.insertedText});return r===null?null:{kind:"mention",query:r}}const aF=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),fv=new Set(["image","screenshot","screen-shot","clipboard","pasted-image","pastedimage","untitled","unknown","file","blob"]),cF={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/heic":"heic","image/heif":"heif","image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/svg+xml":"svg","image/tiff":"tiff","image/webp":"webp"},Ps=e=>e.trim().toLowerCase(),lF=e=>e.charCodeAt(0)<32||'<>:"/\\|?*[]'.includes(e),dF=e=>{const t=e.replace(/\\/g,"/").split("/").pop()??"";return Array.from(t).map(n=>lF(n)?"-":n).join("").replace(/\s+/g," ").replace(/-+/g,"-").trim()},uF=e=>{const t=e?.trim().toLowerCase()??"";return cF[t]??"png"},I4=e=>{const t=dF(e.name),n=uF(e.type),r=t.lastIndexOf(".");if(r>0&&r<t.length-1){const s=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(s))return{base:t.slice(0,r).trim()||"image",ext:s}}return{base:t.trim()||"image",ext:n}},fF=e=>{const{base:t}=I4({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(fv.has(n))return!0;const r=n.replace(/-\(\d+\)$/g,"");return r!==n&&fv.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},Oo=(e,t)=>`${e}.${t}`,hF=(e,t,n)=>{const r=Oo(e,t);if(!n.has(Ps(r)))return r;for(let s=2;s<Number.MAX_SAFE_INTEGER;s+=1){const o=Oo(`${e}-${s}`,t);if(!n.has(Ps(o)))return o}return Oo(`${e}-${Date.now()}`,t)},pF=(e,t)=>{for(let n=1;n<Number.MAX_SAFE_INTEGER;n+=1){const r=Oo(`image-${n}`,e);if(!Array.from(t).some(o=>o.startsWith(`image-${n}.`))&&!t.has(Ps(r)))return r}return Oo(`image-${Date.now()}`,e)},mF=(e,t)=>{const n=new Set(t.map(Ps));return e.map(r=>{const{base:s,ext:o}=I4(r),i=fF(Oo(s,o))?pF(o,n):hF(s,o,n);return n.add(Ps(i)),i})},gF=e=>e.map(t=>`[${t}]`).join(" "),yF=(e,t)=>{if(!e||!e.includes("[")||t.length===0)return[];const n=new Set(t.map(Ps)),r=[];let s=0;for(;s<e.length;){const o=e.indexOf("[",s);if(o===-1)break;const i=e.indexOf("]",o+1);if(i===-1)break;if(e[i+1]!=="("){const a=e.slice(o+1,i).trim();n.has(Ps(a))&&r.push({start:o,end:i+1})}s=i+1}return r},vF=e=>{switch(e){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return"shell";case"json":case"jsonc":case"json5":return"json";case"js":case"javascript":case"jsx":case"ts":case"typescript":case"tsx":return"javascript";case"html":case"heex":case"eex":case"leex":return"html";case"css":return"css";case"py":case"python":return"python";case"md":case"markdown":case"mdown":case"mkd":return"markdown";default:return null}},E4=e=>e.trim().toLowerCase(),zp=new Map,sl=new Map;let ol=null;const xF=async(e,t)=>{switch(e){case"javascript":{const{javascript:n}=await mt(async()=>{const{javascript:r}=await import("./vendor-codemirror-lang-javascript-Bx_FIyZF.js");return{javascript:r}},__vite__mapDeps([44,45,46,5,1,6,47]));switch(t){case"jsx":return n({jsx:!0}).language;case"ts":case"typescript":return n({typescript:!0}).language;case"tsx":return n({typescript:!0,jsx:!0}).language;default:return n().language}}case"json":{const{json:n}=await mt(async()=>{const{json:r}=await import("./vendor-codemirror-lang-json-DIvqf9Pb.js");return{json:r}},__vite__mapDeps([48,49,46,5,1,6]));return n().language}case"css":{const{css:n}=await mt(async()=>{const{css:r}=await import("./vendor-codemirror-lang-css-D1wpUg3Z.js");return{css:r}},__vite__mapDeps([50,51,46,5,1,6]));return n().language}case"html":{const{html:n}=await mt(async()=>{const{html:r}=await import("./vendor-codemirror-lang-html-DbL8oT9H.js");return{html:r}},__vite__mapDeps([52,53,46,5,1,6,50,51,44,45,47]));return n().language}case"markdown":{const{markdown:n}=await mt(async()=>{const{markdown:r}=await import("./vendor-codemirror-lang-markdown-v3yG2sbf.js");return{markdown:r}},__vite__mapDeps([54,5,1,6,47,55,52,53,46,50,51,44,45]));return n().language}case"python":{const{python:n}=await mt(async()=>{const{python:r}=await import("./vendor-codemirror-lang-python-b-JqEwQy.js");return{python:r}},__vite__mapDeps([56,57,46,5,1,6,47]));return n().language}case"shell":{if(ol)return ol;const{shell:n}=await mt(async()=>{const{shell:r}=await import("./shell-CjFT_Tl9.js");return{shell:r}},[]);return ol=I8.define(n),ol}}},_4=e=>e?zp.get(E4(e))??null:null,bF=e=>{const t=E4(e);if(!t)return Promise.resolve(null);const n=zp.get(t);if(n)return Promise.resolve(n);const r=sl.get(t);if(r)return r;const s=vF(t);if(!s)return Promise.resolve(null);const o=xF(s,t).then(i=>(i&&zp.set(t,i),sl.delete(t),i)).catch(()=>(sl.delete(t),null));return sl.set(t,o),o},wF={mentionFile:100,mentionAgent:100,mentionCommand:100,mentionSnippet:100,code:90,codeFence:90,path:85,link:80,linkUrl:78,heading:70,attention:60,strong:50,emphasis:50,blockquote:40,listMarker:35,marker:10},hv={mentionFile:"text-[var(--status-info)]",mentionAgent:"text-[var(--status-success)]",mentionCommand:"text-[var(--primary)]",mentionSnippet:"text-[var(--status-warning)]",code:"rounded-[3px] bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",codeFence:"bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",path:"text-[var(--status-info)]",link:"text-[var(--status-info)] underline",linkUrl:"text-muted-foreground",heading:"text-[var(--syntax-keyword)]",attention:"font-semibold text-[var(--status-warning)]",blockquote:"text-muted-foreground",listMarker:"text-[var(--syntax-keyword)]",marker:"text-muted-foreground",strong:"font-semibold",emphasis:"italic"},SF=new Set(["strong","emphasis"]),j4="text-foreground";function CF(e,t,n){const r=t>0?e[t-1]:"",s=e[t+n];return!s||/\s/.test(s)||e[t]==="_"&&/[\w]/.test(r)?!1:r===""||!/[\w]/.test(r)||e[t]==="*"}function kF(e,t,n){const r=e[t-1],s=e[t+n];return!(!r||/\s/.test(r)||e[t]==="_"&&s&&/[\w]/.test(s))}function MF(e,t){const n=e[t],r=/^(\*{1,3}|_{1,3})/.exec(e.slice(t))?.[1]??"";if(!r||!CF(e,t,r.length))return null;let s=t+r.length;for(;s<e.length;){const o=e.indexOf(r,s);if(o===-1)return null;if(e[o+r.length]===n){s=o+r.length+1;continue}if(kF(e,o,r.length))return{end:o+r.length,runLength:r.length};s=o+r.length}return null}function fo(e,t,n){let r=0;const s=e.length;for(;r<s;){const o=e[r];if(o==="`"){const i=/^`+/.exec(e.slice(r))?.[0]??"",a=e.indexOf(i,r+i.length);if(a!==-1){const l=a+i.length;n.push({start:t+r,end:t+l,style:"code"}),r=l;continue}}if(o==="["){const i=/^\[([^\]\n]*)\]\(([^)\n]*)\)/.exec(e.slice(r));if(i){const a=t+r,l=i[1].length,d=i[2].length,f=a+1,u=f+l,h=u+2,m=h+d,g=m+1;n.push({start:a,end:f,style:"marker"}),l>0&&n.push({start:f,end:u,style:"link"}),n.push({start:u,end:h,style:"marker"}),d>0&&n.push({start:h,end:m,style:"linkUrl"}),n.push({start:m,end:g,style:"marker"}),r+=i[0].length;continue}}if(o==="*"||o==="_"){const i=MF(e,r);if(i){const a=t+r+i.runLength,l=t+i.end-i.runLength;n.push({start:t+r,end:a,style:"marker"}),i.runLength>=2&&n.push({start:a,end:l,style:"strong"}),i.runLength!==2&&n.push({start:a,end:l,style:"emphasis"}),n.push({start:l,end:t+i.end,style:"marker"}),fo(e.slice(r+i.runLength,i.end-i.runLength),a,n),r=i.end;continue}}r+=1}}const IF=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function B1(e){const t=IF.exec(e);return t?{marker:t[2],lang:t[3]||""}:null}function T4(e,t){return new RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function EF(e){const t=[];if(!e)return t;let n=0,r=!1,s="";const o=e.split(`
82
- `);for(let i=0;i<o.length;i+=1){const a=o[i],l=n,d=l+a.length;if(n=d+1,r){t.push({start:l,end:d,style:"codeFence"}),T4(a,s)&&(r=!1);continue}const f=B1(a);if(f){r=!0,s=f.marker,t.push({start:l,end:d,style:"codeFence"});continue}const u=/^(\s*)(!!!)(\s+)/.exec(a);if(u){const x=l+u[1].length,b=x+u[2].length;t.push({start:x,end:b,style:"marker"});const S=b+u[3].length;d>S&&(t.push({start:S,end:d,style:"attention"}),fo(a.slice(S-l),S,t));continue}const h=/^(\s*)(#{1,6})(\s+)/.exec(a);if(h){const x=l+h[1].length,b=x+h[2].length;t.push({start:x,end:b,style:"marker"});const S=b+h[3].length;d>S&&(t.push({start:S,end:d,style:"heading"}),fo(a.slice(S-l),S,t));continue}const m=/^(\s*)(>+)(\s?)/.exec(a);if(m){const x=l+m[1].length,b=x+m[2].length;t.push({start:x,end:b,style:"marker"});const S=b+m[3].length;d>S&&(t.push({start:S,end:d,style:"blockquote"}),fo(a.slice(S-l),S,t));continue}const g=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(a);if(g){const x=l+g[1].length,b=x+g[2].length;t.push({start:x,end:b,style:"listMarker"});const S=b+g[3].length;fo(a.slice(S-l),S,t);continue}fo(a,l,t)}return t}function _F(e,t){if(!e||t.length===0)return[];const n=e.length,r=new Set([0,n]);for(const d of t)d.start>0&&d.start<n&&r.add(d.start),d.end>0&&d.end<n&&r.add(d.end);const s=[...r].sort((d,f)=>d-f),o=t.map((d,f)=>({range:d,index:f})).filter(d=>d.range.end>d.range.start).sort((d,f)=>d.range.start-f.range.start),i=[],a=[];let l=0;for(let d=0;d<s.length-1;d+=1){const f=s[d],u=s[d+1];if(u<=f)continue;for(;l<o.length&&o[l].range.start<=f;)a.push(o[l]),l+=1;for(let v=a.length-1;v>=0;v-=1)a[v].range.end<=f&&a.splice(v,1);let h=null,m=-1,g=1/0;const x=[];for(const{range:v,index:C}of a){if(SF.has(v.style)){const I=v.className??hv[v.style];x.includes(I)||x.push(I);continue}const w=v.priority??wF[v.style];(w>m||w===m&&C<g)&&(m=w,g=C,h=v)}const b=h?h.className??hv[h.style]:j4,S=x.length>0?[b,...x].join(" "):b,y=i[i.length-1];y&&y.className===S&&y.end===f?y.end=u:i.push({start:f,end:u,className:S})}return i}const jF=j4;function TF(e){return e.map(t=>({start:t.start,end:t.end,style:t.kind==="file"?"mentionFile":"mentionAgent"}))}const ir="bg-[var(--surface-subtle)]",AF=91,NF=94,ph={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},LF={keyword:`${ir} text-[var(--syntax-keyword)]`,string:`${ir} text-[var(--syntax-string)]`,number:`${ir} text-[var(--syntax-number)]`,comment:`${ir} text-[var(--syntax-comment)]`,function:`${ir} text-[var(--syntax-function)]`,type:`${ir} text-[var(--syntax-type)]`,variable:`${ir} text-[var(--syntax-variable)]`,operator:`${ir} text-[var(--syntax-operator)]`},RF=_8([{tag:[Pe.comment,Pe.lineComment,Pe.blockComment,Pe.docComment,Pe.meta],class:"comment"},{tag:[Pe.keyword,Pe.modifier,Pe.controlKeyword,Pe.operatorKeyword,Pe.definitionKeyword,Pe.moduleKeyword,Pe.self,Pe.null],class:"keyword"},{tag:[Pe.string,Pe.special(Pe.string),Pe.docString,Pe.character,Pe.regexp],class:"string"},{tag:[Pe.number,Pe.integer,Pe.float,Pe.bool,Pe.atom],class:"number"},{tag:[Pe.function(Pe.variableName),Pe.function(Pe.propertyName),Pe.macroName,Pe.standard(Pe.variableName)],class:"function"},{tag:[Pe.typeName,Pe.className,Pe.namespace,Pe.tagName],class:"type"},{tag:[Pe.variableName,Pe.propertyName,Pe.attributeName,Pe.labelName,Pe.definition(Pe.variableName)],class:"variable"},{tag:[Pe.operator,Pe.punctuation,Pe.bracket,Pe.derefOperator,Pe.separator],class:"operator"},{tag:[Pe.heading,Pe.heading1,Pe.heading2,Pe.heading3,Pe.heading4,Pe.heading5,Pe.heading6,Pe.strong],class:"keyword"},{tag:[Pe.emphasis,Pe.quote],class:"type"},{tag:[Pe.link,Pe.url],class:"function"},{tag:[Pe.monospace],class:"string"},{tag:[Pe.strikethrough],class:"comment"}]),PF=e=>{let t=null;for(const n of e.split(" ")){const r=n;ph[r]!==void 0&&(t===null||ph[r]>ph[t])&&(t=r)}return t?LF[t]:null},DF=2e4,OF=e=>e?_4(e):null;async function HF(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return!1;const t=new Set;for(const r of e.split(`
83
- `)){const s=B1(r);s?.lang&&(_4(s.lang)||t.add(s.lang))}return t.size===0?!1:(await Promise.all([...t].map(r=>bF(r)))).some(r=>r!==null)}function FF(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return[];const t=[],n=e.split(`
84
- `);let r=0;for(let s=0;s<n.length;s+=1){const o=n[s];r+=o.length+1;const i=B1(o);if(!i)continue;const a=OF(i.lang),l=r,d=[];let f=s+1,u=r;for(;f<n.length;f+=1){const m=n[f];if(T4(m,i.marker)){u+=m.length+1;break}d.push(m),u+=m.length+1}if(s=f,r=u,!a||d.length===0)continue;const h=d.join(`
85
- `);if(h.trim()&&(t.push({start:l,end:l+h.length,style:"codeFence",className:`${ir} text-[var(--syntax-foreground)]`,priority:AF}),!(h.length>DF)))try{const m=a.parser.parse(h);E8(m,RF,(g,x,b)=>{const S=PF(b);S&&t.push({start:l+g,end:l+x,style:"codeFence",className:S,priority:NF})})}catch{}}return t}const pv=/~([^\s~]+)/g,BF=/[)\]},.;:!?`"'>]+$/,VF=/[\s()[\]{}<>"'`,;:]/;function $F(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z]/.test(e)}function zF(e){if(!e||!e.includes("~"))return[];const t=[];pv.lastIndex=0;let n;for(;(n=pv.exec(e))!==null;){const r=n.index,s=r>0?e[r-1]:"";if(s&&!VF.test(s))continue;const o=(n[1]??"").replace(BF,"");!o||!$F(o)||t.push({start:r,end:r+1+o.length,path:o})}return t}function UF(e){return zF(e).map(t=>({start:t.start,end:t.end,style:"path"}))}const qF="[A-Za-z0-9][A-Za-z0-9_-]*",WF="[A-Za-z0-9][^\\s/]*",KF={"/":new RegExp(`(^|\\s)\\/(${WF})`,"g"),"#":new RegExp(`(^|\\s)#(${qF})`,"g")};function Up(e,t){if(!e||!e.includes(t))return[];const n=KF[t],r=[];n.lastIndex=0;let s;for(;(s=n.exec(e))!==null;){const o=s[2],i=s.index+s[1].length;r.push({start:i,end:i+1+o.length,prefix:t,name:o})}return r}function qp(e,t,n="case-insensitive"){return t.size===0?[]:e.filter(r=>t.has(n==="exact"?r.name:r.name.toLowerCase()))}function GF(e,t,n,r="case-insensitive"){const s=new Set,o=[];for(const i of qp(Up(e,t),n,r))s.has(i.name)||(s.add(i.name),o.push(i.name));return o}function ZF(e,t){const n=[];for(const r of QH(e)){const s=eF(r.name,t);s&&n.push({start:r.start,end:r.end,kind:s})}return n}function YF(e,t){if(!e||t.inputMode==="shell")return[];const n=[...EF(e),...FF(e),...TF(ZF(e,t)),...UF(e)];for(const r of qp(Up(e,"/"),t.knownSlashNames))n.push({start:r.start,end:r.end,style:"mentionCommand"});for(const r of qp(Up(e,"#"),t.knownSnippetTriggers))n.push({start:r.start,end:r.end,style:"mentionSnippet"});if(t.attachmentFilenames.length>0&&e.includes("["))for(const r of yF(e,[...t.attachmentFilenames]))n.push({...r,style:"mentionFile"});return n}const V1=G5.define(),A4=G5.define(),Wp=Z5.define({create:()=>N4,update(e,t){for(const n of t.effects)if(n.is(V1))return n.value;return e}}),N4={inputMode:"normal",knownAgentNames:new Set,confirmedMentions:new Set,knownSlashNames:new Set,knownSnippetTriggers:new Set,attachmentFilenames:[]};function mv(e,t){const n=new T8;for(const r of _F(e,YF(e,t)))r.className!==jF&&n.add(r.start,r.end,A8.mark({class:r.className}));return n.finish()}const XF=Z5.define({create:e=>mv(e.doc.toString(),e.field(Wp)),update(e,t){const n=t.effects.some(s=>s.is(V1)),r=t.effects.some(s=>s.is(A4));return!t.docChanged&&!n&&!r?e:mv(t.state.doc.toString(),t.state.field(Wp))},provide:e=>bn.decorations.from(e)}),JF=j8.fromClass(class{generation=0;constructor(e){this.ensure(e)}update(e){e.docChanged&&this.ensure(e.view)}async ensure(e){const t=++this.generation,n=e.state.doc.toString();if(!n.includes("```")&&!n.includes("~~~"))return;let r=!1;try{r=await HF(n)}catch{return}t===this.generation&&r&&e.state.doc.toString()===n&&e.dispatch({effects:A4.of(void 0)})}});function QF(e=N4){return[Wp.init(()=>e),XF,JF]}const eB={"&":{backgroundColor:"transparent",color:"var(--surface-foreground)"},"&.cm-focused":{outline:"none"},".cm-content":{padding:"0",fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",minHeight:"100%"},"&.cm-editor .cm-cursor, &.cm-editor .cm-dropCursor":{borderLeftColor:"var(--surface-foreground)",borderLeftWidth:"2px",marginLeft:"0",transform:"scaleY(1.15)",transformOrigin:"center"},".cm-line":{padding:"0"},".cm-scroller":{fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",overflowX:"hidden"},".cm-placeholder":{color:"var(--surface-muted-foreground)"},"&.cm-editor .cm-selectionBackground, & .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 45%, transparent)"},"&.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 55%, transparent)"},"& ::selection":{background:"color-mix(in srgb, var(--primary) 25%, transparent)"}},tB=bn.theme(eB),nB={"& .cm-content .cm-line ::selection, & .cm-content .cm-line::selection":{backgroundColor:"color-mix(in srgb, var(--primary) 25%, transparent) !important"},"&.cm-editor.oc-native-range .cm-content, &.cm-editor.oc-native-range .cm-content .cm-line":{caretColor:"var(--surface-foreground) !important"},"&.oc-native-range .cm-scroller > .cm-cursorLayer":{display:"none"},"& .cm-scroller > .cm-selectionLayer":{display:"none"}},rB=bn.theme(nB),sB=[rB,bn.editorAttributes.of(e=>e.state.selection.main.empty?null:{class:"oc-native-range"})];function oB(e,t){if(!e||e.state.readOnly||!e.contentDOM.isContentEditable||e.contentDOM.contains(t.target))return;t.preventDefault();const n=e.posAtCoords({x:t.clientX,y:t.clientY})??e.state.doc.length;e.focus(),e.dispatch({selection:{anchor:n}})}function iB(e){let t="";return e.changes.iterChanges((n,r,s,o,i)=>{t+=i.toString()}),t}function gv(e){return!!e.synthetic}const yv=new Y5,vv=new Y5,aB=p.forwardRef(function(t,n){const{value:r,languageContext:s,placeholder:o,editable:i=!0,spellCheck:a=!1,autoCorrect:l=!1,autoCapitalize:d="none",fillContainer:f=!1,maxLines:u=8,boundSelector:h,boundGapPx:m=0,className:g,contentClassName:x,commandComboboxExpanded:b,commandComboboxListboxId:S,commandComboboxActiveOptionId:y}=t,v=p.useRef(null),C=p.useRef(null),w=p.useRef(!1),I=p.useRef({element:null,role:null}),E=p.useRef(t),T=t.viewStore??null;T&&!T.handlers&&(T.handlers={current:t});const A=T?.handlers??E;A.current=t,p.useLayoutEffect(()=>{const k=v.current;if(!k)return;const _=T?.view;if(_){k.appendChild(_.dom),_.requestMeasure();const{anchor:N,head:D}=_.state.selection.main;return _.dispatch({selection:{anchor:N,head:D}}),C.current=_,()=>{_.dom.remove(),C.current=null}}const M=[{any:(N,D)=>(D.key==="Enter"&&gv(D)&&w.current&&Object.defineProperty(D,"shiftKey",{value:!0}),A.current.onKeyDown?.(D)??!1)}],L=new bn({state:N8.create({doc:A.current.value,extensions:[L8(),R8(),sB,bn.lineWrapping,P8.highest(n0.of(M)),n0.of([...D8,...O8]),QF(A.current.languageContext),yv.of(bn.editable.of(A.current.editable??!0)),vv.of(r0(A.current.placeholder??"")),tB,bn.updateListener.of(N=>{const D=A.current,W=bv(N.state);if(N.docChanged){const z=N.transactions.some(F=>F.isUserEvent("input.paste"));let X="";for(const F of N.transactions)X+=iB(F);D.onChange({value:N.state.doc.toString(),selection:W,fromPaste:z,insertedText:X})}else N.selectionSet&&D.onSelectionChange?.(W);(N.docChanged||N.heightChanged||N.geometryChanged)&&D.onVisualLineCount?.(xv(N.view))}),bn.domEventHandlers({focus:()=>(A.current.onFocus?.(),!1),blur:()=>(A.current.onBlur?.(),!1),paste:N=>(A.current.onPaste?.(N),!1)}),bn.contentAttributes.of({spellcheck:String(A.current.spellCheck??!1),autocorrect:A.current.autoCorrect?"on":"off",autocapitalize:A.current.autoCapitalize??"none",...A.current["aria-label"]?{"aria-label":A.current["aria-label"]}:{}})]}),parent:k});C.current=L,T&&(T.view=L);const O=N=>{N.key!=="Enter"||gv(N)||(w.current=N.shiftKey)};return L.contentDOM.addEventListener("keydown",O),()=>{if(C.current=null,T){L.dom.remove();return}L.destroy()}},[]),p.useEffect(()=>{const k=C.current;if(!k)return;const _=k.state.doc.toString();_!==r&&(k.dispatch({changes:{from:0,to:_.length,insert:r},selection:{anchor:r.length}}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{C.current===k&&(k.scrollDOM.scrollTop=k.scrollDOM.scrollHeight)})}))},[r]),p.useEffect(()=>{C.current?.dispatch({effects:V1.of(s)})},[s]),p.useEffect(()=>{C.current?.dispatch({effects:yv.reconfigure(bn.editable.of(i))})},[i]),p.useEffect(()=>{C.current?.dispatch({effects:vv.reconfigure(r0(o??""))})},[o]),p.useEffect(()=>{const k=C.current,_=v.current;if(!k||!_)return;if(f){k.scrollDOM.style.maxHeight="";return}const M=h?_.closest(h):null;let L=null;if(M)for(L=_;L.parentElement&&L.parentElement!==M;)L=L.parentElement;const O=()=>{const D=parseFloat(getComputedStyle(k.contentDOM).lineHeight||"");if(!Number.isFinite(D)||D<=0)return;let W=D*u;if(M&&L){const X=L.offsetHeight-k.scrollDOM.offsetHeight,F=M.clientHeight-X-m;F>0&&(W=Math.min(W,F))}const z=`${W}px`;k.scrollDOM.style.maxHeight!==z&&(k.scrollDOM.style.maxHeight=z)};if(O(),A.current.onVisualLineCount?.(xv(k)),typeof ResizeObserver>"u")return;const N=new ResizeObserver(O);return N.observe(_),L&&N.observe(L),M&&N.observe(M),()=>N.disconnect()},[m,h,f,u]),p.useEffect(()=>{const k=C.current;if(!k)return;const _=k.contentDOM;_.setAttribute("spellcheck",String(a)),_.setAttribute("autocorrect",l?"on":"off"),_.setAttribute("autocapitalize",d)},[d,l,a]),p.useLayoutEffect(()=>{const k=C.current;if(!k)return;const _=k.contentDOM;if(I.current.element!==_){const D=I.current;D.element&&D.element!==_&&(D.role===null?D.element.getAttribute("role")==="combobox"&&D.element.removeAttribute("role"):D.element.setAttribute("role",D.role),D.element.removeAttribute("aria-expanded"),D.element.removeAttribute("aria-controls"),D.element.removeAttribute("aria-activedescendant")),I.current={element:_,role:_.getAttribute("role")}}const M=I.current.role,L=()=>{M===null?_.getAttribute("role")==="combobox"&&_.removeAttribute("role"):_.getAttribute("role")!==M&&_.setAttribute("role",M)},O=()=>{_.removeAttribute("aria-expanded"),_.removeAttribute("aria-controls"),_.removeAttribute("aria-activedescendant"),L()};return!!(b&&S)&&S?(_.setAttribute("role","combobox"),_.setAttribute("aria-expanded","true"),_.setAttribute("aria-controls",S),y?_.setAttribute("aria-activedescendant",y):_.removeAttribute("aria-activedescendant"),O):(O(),O)},[b,S,y]);const j=p.useCallback(k=>{oB(C.current,k)},[]);return p.useImperativeHandle(n,()=>({focus(k){const _=C.current;_&&_.contentDOM.focus({preventScroll:k?.preventScroll})},blur(){C.current?.contentDOM.blur()},isFocused(){return C.current?.hasFocus??!1},getValue(){return C.current?.state.doc.toString()??""},getSelection(){const k=C.current;return k?bv(k.state):{start:0,end:0}},setSelection(k,_=k){const M=C.current;if(!M)return;const L=M.state.doc.length;M.dispatch({selection:{anchor:Math.min(Math.max(k,0),L),head:Math.min(Math.max(_,0),L)}})},selectAll(){const k=C.current;k&&k.dispatch({selection:{anchor:0,head:k.state.doc.length}})},insertText(k){const _=C.current;if(!_||!k)return;const{from:M,to:L}=_.state.selection.main;_.dispatch({changes:{from:M,to:L,insert:k},selection:{anchor:M+k.length},userEvent:"input.type"})},replaceRange(k,_,M,L){const O=C.current;O&&O.dispatch({changes:{from:k,to:_,insert:M},selection:{anchor:L??k+M.length},userEvent:"input.type"})},caretCoords(k){const _=C.current;if(!_)return null;const M=k??_.state.selection.main.head,L=_.coordsAtPos(M);return L?{top:L.top,bottom:L.bottom,left:L.left}:null},getScrollDOM(){return C.current?.scrollDOM??null}}),[]),c.jsx("div",{ref:v,"data-testid":t["data-testid"],"data-chat-input":"true",onMouseDown:j,className:R("composer-editor w-full","[&_.cm-editor]:h-full",f&&"flex min-h-0 flex-1 flex-col",g,x)})});function xv(e){const t=e.defaultLineHeight;return!Number.isFinite(t)||t<=0?1:Math.max(1,Math.round(e.contentHeight/t))}function bv(e){const t=e.selection.main;return{start:t.from,end:t.to}}function cB(){return{view:null,handlers:null}}function lB(e,t){const n=e?e.endsWith(`
86
-
87
- `)?"":e.endsWith(`
88
- `)?`
89
- `:`
90
-
91
- `:"",r=t.endsWith(`
92
-
93
- `)?t:t.endsWith(`
94
- `)?`${t}
95
- `:`${t}
96
-
97
- `;return`${e}${n}${r}`}function L4(e,t){const n=t.trim();if(!n)return e;if(!e)return`${n} `;const r=/[\s\n]$/.test(e)?"":" ";return`${e}${r}${n} `}function R4(e,t,n){if(!e)return e;const r=t.length>0&&!/\s$/.test(t)&&!/^\s/.test(e)&&!/[([{]$/.test(t),s=n.length>0&&!/\s$/.test(e)&&!/^\s/.test(n)&&!/^[\])}.,;:!?]/.test(n);return`${r?" ":""}${e}${s?" ":""}`}function dB(e,t){return e?`${e}${/\s$/.test(e)?"":" "}${t}`:t}const uB=/^(https?:\/\/|mailto:)\S+$/i;function fB(e,t){return uB.test(e)&&!/\s/.test(e)&&t.trim().length>0&&!t.includes("](")}const hB="application/x-pichamber-file-path",pB=["files","text/uri-list","codefiles",hB];function mB(e,t){try{return e.getData(t)}catch{return""}}function il(e){if(!e)return!1;if(e.files&&e.files.length>0)return!0;if(e.types){const t=Array.from(e.types).map(n=>n.toLowerCase());if(pB.some(n=>t.includes(n))||t.some(n=>n.includes("vnd.code.tree")))return!0}for(const t of ML){const n=mB(e,t);if(n&&CL(n).length>0)return!0}return!1}function gB(e){if(!e)return[];const t=Array.from(e.files||[]);return t.length>0?t:Array.from(e.items||[]).filter(n=>n.kind==="file").map(n=>n.getAsFile()).filter(n=>!!n)}function yB({enabled:e,composerRef:t,messageRef:n,cursorPosRef:r,confirmedMentionsRef:s,setMessage:o,addAttachedFile:i}){const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(0),h=p.useCallback(y=>{if(!il(y.dataTransfer))return;y.preventDefault(),y.stopPropagation(),u.current++;const v=y.dataTransfer.types?.includes("application/x-pichamber-file-path")??!1;v!==d&&f(v),e&&!a&&l(!0)},[e,a,d]),m=p.useCallback(y=>{il(y.dataTransfer)&&(y.preventDefault(),y.stopPropagation(),y.dataTransfer.dropEffect="copy",e&&!a&&l(!0))},[e,a]),g=p.useCallback(y=>{y.preventDefault(),y.stopPropagation(),u.current--,u.current<=0&&(u.current=0,l(!1),f(!1))},[]),x=p.useCallback(()=>{u.current=0,l(!1),f(!1)},[]),b=p.useCallback(async y=>{if(u.current=0,!il(y.dataTransfer)||(y.preventDefault(),y.stopPropagation(),l(!1),!e))return;const C=y.dataTransfer.getData("application/x-pichamber-file-path");if(C&&C!=="."){s.current.add(C);const I=`@${C}`,E=t.current,T=n.current;if(E){const{start:A,end:j}=E.getSelection(),k=T.slice(0,A),_=T.slice(j),M=k.length>0&&!/\s$/.test(k),L=_.length>0&&!/^\s/.test(_),O=`${M?" ":""}${I}${L?" ":""}`;E.replaceRange(A,j,O),r.current=A+O.length,E.focus()}else o(A=>L4(A,I));return}const w=gB(y.dataTransfer);w.length>0&&((await Promise.all(w.map(async E=>{try{return await i(E)}catch(T){return console.error("File attach failed",T),!1}}))).some(Boolean)||Ce.error("Failed to attach file"))},[i,t,s,r,e,n,o]),S=p.useCallback(y=>{il(y.dataTransfer)&&y.preventDefault()},[]);return{isDragging:a,isInternalDrag:d,handleDragEnter:h,handleDragOver:m,handleDragLeave:g,handleDragEnd:x,handleDrop:b,handleDropCapture:S}}const vB=16e3,xB="pasted-text.txt";function bB(e){return e.length>vB}function wv(e){return new File([e],xB,{type:"text/plain"})}function wB({inputMode:e,enabled:t,composerRef:n,message:r,setMessage:s,insertTextAtSelection:o,updateAutocompleteState:i,markFileMentionPasteSuppression:a,attachedFiles:l,addAttachedFile:d}){const f=p.useRef(new Set);return p.useCallback(async u=>{const h=u.clipboardData;if(!h)return;const m={...u,clipboardData:h,preventDefault:()=>u.preventDefault()},g=m.clipboardData.getData("text"),x=bB(g);if(e==="normal"&&t&&!x){const j=n.current,k=j?.getSelection().start??-1,_=j?.getSelection().end??-1;if(j&&_>k){const M=g.trim(),L=r.slice(k,_);if(fB(M,L)){m.preventDefault();const O=`${r.slice(0,k)}[${L}](${M})${r.slice(_)}`,N=k+1+L.length+2+M.length+1;s(O),n.current?.setSelection(N,N),i(O,N,dv(M),M);return}}}const b=new Map;Array.from(m.clipboardData.files||[]).forEach(j=>{j.type.startsWith("image/")&&b.set(`${j.name}-${j.size}`,j)}),Array.from(m.clipboardData.items||[]).forEach(j=>{if(j.kind==="file"&&j.type.startsWith("image/")){const k=j.getAsFile();k&&b.set(`${k.name}-${k.size}`,k)}});const S=Array.from(b.values());if(x){if(!t){g.includes("@")&&a();return}if(m.preventDefault(),S.length===0){const j=wv(g);try{await d(j)||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}return}}else{if(S.length===0){g.includes("@")&&a();return}if(!t){g.includes("@")&&a();return}m.preventDefault()}const y=mF(S,[...l.map(j=>j.filename),...f.current]),v=gF(y),C=n.current,w=C?.getSelection().start??r.length,I=C?.getSelection().end??r.length,E=R4(dB(x?"":g,v),r.slice(0,w),r.slice(I));o(E,dv(E));const T=x?(async()=>{try{await d(wv(g))||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}})():null,A=S.map(async(j,k)=>{const _=y[k],M=aF(j,_);f.current.add(_);try{await d(M)}catch(L){console.error("Clipboard image attach failed",L),Ce.error(L instanceof Error?L.message:"Failed to attach image from clipboard")}finally{f.current.delete(_)}});await Promise.all(T?[T,...A]:A)},[d,l,n,t,e,o,a,r,s,i])}const SB=(e,t)=>{if(t.size===0)return[];const n=new Map;for(const a of t){const l=a.toLowerCase();n.has(l)||n.set(l,a)}const r=new Set;for(const a of n.keys())r.add(`skill:${a}`);const s=GF(e,"/",r,"case-insensitive"),o=new Set,i=[];for(const a of s){const l=a.slice(6),d=n.get(l.toLowerCase())??l,f=d.toLowerCase();o.has(f)||(o.add(f),i.push(d))}return i},CB=e=>e.length===0?null:`The user explicitly mentioned these skills in their message: ${e.map(n=>`/skill:${n}`).join(", ")}. Use the corresponding skill tool when it is relevant to accomplishing the user's request.`;function kB(e,t){let n="",r=[],s;const o=[],i=[],a=u=>{for(const h of t.collectSkillNames(u))i.includes(h)||i.push(h)},l=u=>{!s&&u&&(s=u)},d=u=>{const h=t.parseAgentMention(u);l(h.agentName);const m=t.extractFileMentions(h.text);return a(m.text),m};if(e.queued.forEach((u,h)=>{const m=d(u.content),g=[...t.sanitizeAttachments(u.attachments),...m.attachments];if(h===0){n=m.text,r=g;return}o.push({text:m.text,attachments:g})}),e.composerText!==null){const u=d(e.composerText.replace(/^\n+|\n+$/g,"")),h=[...t.sanitizeAttachments(e.composerAttachments),...u.attachments];e.queued.length===0?(n=u.text,r=h):o.push({text:u.text,attachments:h})}for(const u of e.syntheticTexts)o.push({text:u,synthetic:!0});const f=t.buildSkillInstruction(i);return f&&o.push({text:f,synthetic:!0}),{primaryText:n,primaryAttachments:r,additionalParts:o,agentMentionName:s,isEmpty:!n&&r.length===0&&o.length===0}}function Sv(e){const t=e.trimStart();if(!t.startsWith("/"))return null;const n=t.slice(1),r=n.trim().split(/\s+/)[0]?.toLowerCase()??"";return r?{name:r,argument:n.slice(r.length).trim()}:null}const MB=["undo","redo","timeline","compact"];function P4(e){return MB.includes(e)}async function IB({command:e,currentSessionId:t,scrollToBottom:n,setTimelineDialogOpen:r,onCompactSession:s,onUndoSession:o,onRedoSession:i}){const{name:a,argument:l}=e;return P4(a)?a==="undo"&&t?(await o(t),n?.(),!0):a==="redo"&&t?(await i(t),n?.(),!0):a==="timeline"&&t?(r(!0),!0):a==="compact"?t?(await s(t,l.trim()||void 0),!0):(Ce.error("Open a session before compacting."),!0):!1:!1}function EB(e){const{enabled:t,openAutocomplete:n,message:r,editorRef:s,containerRef:o}=e,[i,a]=p.useState(null),l=p.useCallback(()=>{if(!t){a(null);return}if(n===null){a(null);return}const d=s.current,f=o.current;if(!d||!f)return;const u=d.caretCoords();if(!u)return;const h=f.getBoundingClientRect(),m=u.top-h.top,g=u.left-h.left,x=8,b=260,S=m-x,y=h.height-m-x,v=y>=b||y>=S?"below":"above",C=n==="mention"?520:450,w=Math.max(x,Math.min(g-24,h.width-C-x)),I=Math.max(120,Math.min(b,v==="below"?y:S));a({top:v==="below"?m+22:m-6,left:w,place:v,maxHeight:I})},[o,s,t,n]);return p.useLayoutEffect(()=>{l()},[l,r,n,t]),p.useEffect(()=>{if(!t)return;const d=()=>l();return window.addEventListener("resize",d),()=>{window.removeEventListener("resize",d)}},[t,l]),{position:i,update:l}}const _u=-1,Kp={index:_u,stashedDraft:""},Gp=e=>({state:e,text:null});function _B(e,t,n){if(t.length===0)return Gp(e);if(e.index===_u)return{state:{index:0,stashedDraft:n},text:t[0]};if(e.index>=t.length-1)return Gp(e);const r=e.index+1;return{state:{...e,index:r},text:t[r]}}function jB(e,t){if(e.index===_u)return Gp(e);if(e.index===0)return{state:Kp,text:e.stashedDraft};const n=e.index-1;return{state:{...e,index:n},text:t[n]}}function TB(e){const[t,n]=p.useState(Kp),r=p.useCallback(i=>{const a=_B(t,e,i);return a.text===null?null:(n(a.state),a.text)},[e,t]),s=p.useCallback(()=>{const i=jB(t,e);return i.text===null?null:(n(i.state),i.text)},[e,t]),o=p.useCallback(()=>n(Kp),[]);return{isBrowsing:t.index!==_u,older:r,newer:s,reset:o}}const AB=500;function Cv(e,t){return`${e}\0${[...t].sort().join("\0")}`}function NB(e){const{message:t,messageRef:n,setMessage:r,confirmedMentionsRef:s,identity:o,persistEnabled:i,initialDraft:a,onIdentityChange:l,onDraftRestored:d}=e,f=p.useRef(null),u=p.useRef(!1),h=p.useRef(new Map),m=p.useRef(a.identity),g=p.useRef({onIdentityChange:l,onDraftRestored:d});g.current={onIdentityChange:l,onDraftRestored:d},p.useEffect(()=>{m.current=o},[o]);const x=p.useCallback((v,C)=>{if(!v)return;const w=Qt(v),I=new Set;for(const T of s.current)C.includes(`@${T}`)&&I.add(T);s.current=I;const E=Cv(C,I);h.current.get(w)!==E&&(As(v,C,I),h.current.set(w,E))},[s]),b=p.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=p.useRef(!1);p.useEffect(()=>{if(!S.current&&(S.current=!0,!!a.text)){if(!i){r(""),As(a.identity,"",[]);return}requestAnimationFrame(()=>g.current.onDraftRestored?.())}},[i]);const y=p.useRef(a.identity);return p.useEffect(()=>{const v=y.current,C=v?Qt(v):null,w=o?Qt(o):null;if(C===w)return;if(y.current=o,g.current.onIdentityChange?.(),b(),u.current=!0,!i){r(""),s.current=new Set;return}x(v,n.current);const I=ru(o);r(I.text),s.current=I.confirmedMentions,I.text&&requestAnimationFrame(()=>g.current.onDraftRestored?.())},[b,s,o,n,i,x,r]),p.useEffect(()=>YM(v=>{const C=Qt(v);h.current.set(C,Cv("",[]));const w=m.current;!w||Qt(w)!==C||(b(),u.current=!0,n.current="",s.current=new Set,r(""))}),[b,s,n,r]),p.useEffect(()=>{if(!i){b(),x(o,"");return}if(u.current){u.current=!1;return}b();const v=t,C=o;return f.current=setTimeout(()=>{f.current=null,x(C,v)},AB),b},[b,o,t,i,x]),p.useEffect(()=>{const v=()=>{b(),i&&x(m.current,n.current)},C=()=>{document.visibilityState==="hidden"&&v()};return document.addEventListener("visibilitychange",C),document.addEventListener("freeze",v),window.addEventListener("pagehide",v),()=>{document.removeEventListener("visibilitychange",C),document.removeEventListener("freeze",v),window.removeEventListener("pagehide",v),v()}},[b,n,i,x]),{persistNow:x}}function LB(e,t,n){const s=e.substring(0,t).lastIndexOf("@");if(s!==-1){const a=e.substring(0,s)+`@${n} `+e.substring(t),l=s+n.length+2;return{newMessage:a,nextCursor:l}}const o=e.substring(0,t)+`@${n} `+e.substring(t),i=t+n.length+2;return{newMessage:o,nextCursor:i}}function kv(e,t,n,r){const o=e.substring(0,t).lastIndexOf(n),i=o!==-1?o:t,a=`${e.substring(0,i)}${n}${r} ${e.substring(t)}`,l=i+r.length+2;return{newMessage:a,nextCursor:l}}function RB({composerRef:e,message:t,setMessage:n,updateAutocompleteState:r,closeAutocomplete:s,confirmedMentionsRef:o,toMentionPath:i}){const a=p.useCallback(u=>{const h=e.current?.getSelection().start||0,m=u.relativePath&&u.relativePath.trim().length>0?u.relativePath.trim():i(u.path)||u.name;o.current.add(m);const{newMessage:g,nextCursor:x}=LB(t,h,m);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,o,t,n,i,r]),l=p.useCallback(u=>{const h=e.current?.getSelection().start??t.length,{newMessage:m,nextCursor:g}=kv(t,h,"@",u);n(m),requestAnimationFrame(()=>{e.current&&e.current.setSelection(g),r(m,g)}),s(),e.current?.focus()},[s,e,t,n,r]),d=p.useCallback((u,h)=>{const m=e.current?.getSelection().start??t.length,{newMessage:g,nextCursor:x}=kv(t,m,"#",h);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,t,n,r]),f=p.useCallback(u=>{const h=u.invocationName??u.name;n(`/${h} `),s();const m=()=>{if(e.current){try{e.current.focus({preventScroll:!0})}catch{e.current.focus()}e.current.setSelection(e.current.getValue().length,e.current.getValue().length)}};requestAnimationFrame(()=>{m(),requestAnimationFrame(m)}),setTimeout(m,60)},[s,e,n]);return{handleFileSelect:a,handleAgentSelect:l,handleSnippetSelect:d,handleCommandSelect:f}}const PB=e=>{const t="nativeEvent"in e?e.nativeEvent:e;return t.isComposing||t.keyCode===229},DB={"`":["`","`"],"*":["*","*"],_:["_","_"],"~":["~","~"],"(":["(",")"],"[":["[","]"],"{":["{","}"],'"':['"','"'],"'":["'","'"]};function OB(e,t,n,r){if(n<=t)return null;const s=DB[r];if(!s)return null;const[o,i]=s,a=e.slice(t,n);return{next:`${e.slice(0,t)}${o}${a}${i}${e.slice(n)}`,caretStart:t+o.length,caretEnd:n+o.length}}function HB(e,t,n,r){if(r!=="`"||t!==n)return null;const s=e.slice(0,t);if(/(^|\n)``$/.test(s)){const o=e.slice(n),i=`${s}\`
98
-
99
- \`\`\`${o}`,a=s.length+2;return{next:i,caret:a}}return null}function FB({inputMode:e,setInputMode:t,shellExcludeFromContext:n,setShellExcludeFromContext:r,message:s,setMessage:o,openAutocomplete:i,commandRef:a,snippetRef:l,mentionRef:d,composerRef:f,messageHistory:u,updateAutocompleteState:h,isMobile:m,hasContent:g,currentSessionId:x,sessionPhase:b,commandRunning:S=!1,followUpBehavior:y,handleSubmit:v,handleQueueMessage:C}){return p.useCallback(w=>{if(PB(w))return;if(e==="shell"&&w.key==="Escape"){w.preventDefault(),t("normal");return}if(e==="shell"&&w.key==="Backspace"&&s.length===0){w.preventDefault(),n&&r?r(!1):t("normal");return}if(i==="command"&&a.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),a.current.handleKeyDown(w.key);return}if(i==="snippet"&&l.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),l.current.handleKeyDown(w.key);return}if(i==="mention"&&d.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),d.current.handleKeyDown(w.key);return}const I=i!==null,E=f.current?.getSelection().start===0&&f.current?.getSelection().end===0,T=f.current?.getSelection().start===s.length&&f.current?.getSelection().end===s.length,A=!I&&(s.length===0||E),j=!I&&(s.length===0||T);if(e==="normal"&&!I&&!w.metaKey&&!w.ctrlKey&&!w.altKey){const k=f.current,_=k?.getSelection().start??-1,M=k?.getSelection().end??-1;if(k&&_>=0){const L=(D,W,z)=>{w.preventDefault(),o(D),f.current?.setSelection(W,z),h(D,z)},O=OB(s,_,M,w.key);if(O){L(O.next,O.caretStart,O.caretEnd);return}const N=HB(s,_,M,w.key);if(N){L(N.next,N.caret,N.caret);return}}}if(w.key==="ArrowUp"&&A){w.preventDefault();const k=u.older(s);k!==null&&(o(k),requestAnimationFrame(()=>f.current?.setSelection(0,0)));return}if(w.key==="ArrowDown"&&j){w.preventDefault();const k=u.newer();k!==null&&o(k);return}if(w.key==="Enter"&&!w.shiftKey&&(!m||w.ctrlKey||w.metaKey)){w.preventDefault();const k=w.ctrlKey||w.metaKey,_=e==="normal"&&g&&x&&b!=="idle";S&&_?C():y==="queue"?k||!_?v():C():k||!_?v():v({delivery:"steer"})}},[a,S,f,x,y,C,v,g,e,m,d,s,u,i,b,t,o,r,n,l,h])}const BB=e=>e.enabled&&e.draftOpen&&!!e.directory&&e.gitAvailable&&e.isGitRepository,VB=(e,t)=>{const n=(e??[]).filter(r=>r.length>0&&!r.startsWith("remotes/")).sort((r,s)=>r.localeCompare(s)).map(r=>({value:r,label:r}));return t&&!n.some(r=>r.value===t)&&n.push({value:t,label:t}),n};function $B(e){const t=lt(z=>z.projects),n=un(z=>z.projects),r=p.useMemo(()=>Zn(t,{projects:n}),[t,n]),s=nt(z=>z.homeDirectory),o=p.useMemo(()=>x3(t,r),[r,t]),i=lt(z=>z.activeProjectId),a=lt(z=>z.setActiveProjectIdOnly),l=he(z=>z.newSessionDraft),d=he(z=>z.currentSessionId),f=he(z=>z.currentSessionDirectory),u=he(z=>z.setNewSessionDraftTarget),h=!!l?.open,m=vt(z=>z.fetchBranches),{git:g}=qa(),x=p.useMemo(()=>{if(h){const X=Xt(l?.directoryOverride??null),F=l?.selectedProjectId?o.find(U=>U.ownerProjectId===l.selectedProjectId&&(!X||Xt(U.path)===X))??o.find(U=>U.id===l.selectedProjectId)??null:null;if(F)return F;if(X){const U=o.find(P=>Xt(P.path)===X)??null;if(U)return U}}else if(d){const X=Xt(f??null);if(X&&XI(X,s)){const U=o.find(P=>P.ownerProjectId===fr)??null;if(U)return U}const F=dr(t,r,f);if(F){const U=Xt(f??null);return o.find(P=>P.ownerProjectId===F.id&&Xt(P.path)===U)??o.find(P=>P.id===F.id)??null}}return(i?o.find(X=>X.id===i)??null:null)??o[0]??null},[i,r,f,d,s,h,l?.directoryOverride,l?.selectedProjectId,o,t]),b=p.useMemo(()=>Xt(x?.path??null),[x?.path]),S=p.useMemo(()=>h?Xt(l?.directoryOverride??null)??b:Xt(f??null)??b,[f,h,l?.directoryOverride,b]),y=x?t.find(z=>z.id===x.ownerProjectId)??null:null,v=Xt(y?.path??null),C=x?za(x):null;p.useEffect(()=>{if(!_L({enabled:e,isDraftOpen:h,activeProjectId:i,selectedProjectId:l?.selectedProjectId}))return;const z=o.find(X=>X.id===i);z&&u({projectId:z.id,directoryOverride:z.path,branchIntent:null,worktreeIntent:null})},[i,e,h,l?.selectedProjectId,o,u]);const w=ku(S),I=vt(z=>S&&z.directories.get(S)?.status?.current?.trim()||null),E=t4(h?S:null),[T,A]=p.useState(!1);p.useEffect(()=>{const z=S?vt.getState().directories.get(S)?.branches??null:null;if(!BB({enabled:e,draftOpen:h,directory:S,gitAvailable:!!g,isGitRepository:w===!0})){A(!1);return}if(!S||!g)return;let X=!1;return A(z===null),m(S,g).finally(()=>{X||A(!1)}),()=>{X=!0}},[e,m,h,g,w,S]);const j=E?.current?.trim()||I,k=h&&(l?.worktreeIntent?.startRef?.trim()||l?.branchIntent?.branch?.trim())||null,_=k??j,M=p.useMemo(()=>h?VB(E?.all,k):[],[k,h,E?.all]),L=_??(w===!0?"Detached HEAD":null),O=w===!0&&!!(L||M.length>0||T),N=p.useCallback(z=>{if(!h)return;const X=o.find(U=>U.id===z),F=Xt(X?.path??null);if(!(!X||!F)){if(X.ownerProjectId===fr){u({projectId:fr,directoryOverride:F,branchIntent:null,worktreeIntent:null});return}i!==X.ownerProjectId&&a(X.ownerProjectId),u({projectId:X.ownerProjectId,directoryOverride:F,branchIntent:null,worktreeIntent:null})}},[i,h,o,a,u]),D=p.useCallback(z=>{if(!h||!S)return;const X=z.trim();if(!(!X||X.startsWith("remotes/"))){if(l?.worktreeIntent&&v){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:X}});return}u({worktreeIntent:null,branchIntent:{runtimeKey:Y(),directory:S,branch:X}})}},[h,l?.worktreeIntent,S,v,u]),W=p.useCallback(z=>{if(!(!h||!S||!v||!_)){if(z){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:_}});return}u({worktreeIntent:null,branchIntent:_===j?null:{runtimeKey:Y(),directory:S,branch:_}})}},[j,h,_,S,v,u]);return{projects:o,selectedDraftProject:x,selectedDraftProjectPath:b,selectedDraftProjectRoot:v,draftProjectLabel:C,selectedDraftDirectory:S,selectedDraftBranchLabel:L,selectedBranchName:_,currentBranch:j,draftBranchItems:M,isDiscoveringDraftBranches:T,shouldShowDraftBranchSelector:O,worktreeMode:!!(h&&l?.worktreeIntent),handleDraftProjectChange:N,handleDraftBranchChange:D,handleWorktreeModeChange:W}}const zB=e=>{const t=de(e.targetDirectory)??e.targetDirectory,r=(e.projectId?e.projects.find(i=>i.id===e.projectId)??null:null)??e.projects.reduce((i,a)=>{const l=de(a.path);if(!l||t!==l&&!t.startsWith(`${l}/`))return i;const d=de(i?.path??null);return!d||l.length>d.length?a:i},null),s=de(r?.path??null),o=new Set([t]);if(!s)return o;o.add(s);for(const[i,a]of e.availableWorktreesByProject)if(de(i)===s)for(const l of a??[]){const d=de(l?.path??null);d&&o.add(d)}return o},UB=(e,t)=>{const n=new Set(e.map(r=>r.id));return t.some(r=>!n.has(r.id))},Mv=(e,t)=>{const n=lt.getState(),r=Zn(n.projects,un.getState()),s=zB({targetDirectory:e,projectId:t,projects:n.projects,availableWorktreesByProject:r});return kE().filter(o=>s.has(o.directory)).sort((o,i)=>(o.title??"").localeCompare(i.title??"")||o.id.localeCompare(i.id))};function qB(e){const{activeRuntimeKey:t,intent:n,onReady:r}=e,{git:s}=qa(),o=vt(I=>I.fetchStatus),i=vt(I=>I.fetchBranches),a=vt(I=>I.clearDiffCache),[l,d]=p.useState(null),f=p.useRef(!1),u=p.useRef(0),h=p.useRef(null),m=p.useRef(r);m.current=r;const g=n?.runtimeKey??"",x=n?.directory??"",b=n?.branch??"";p.useEffect(()=>{u.current+=1,h.current=null,d(null)},[t,b,x,g]);const S=p.useCallback(I=>{s&&(a(I),Cu.requestGitRefresh({directory:I}),Promise.all([o(I,s,{silent:!0}),i(I,s)]))},[a,i,o,s]),y=p.useCallback((I,E)=>{const T={runtimeKey:E.runtimeKey,directory:E.directory,branch:E.branch};h.current=T,m.current(I,T)},[]),v=p.useCallback(async I=>{const E=I.intent;if(!(f.current||l)){if(!s){Ce.error("Git is not available for the selected runtime.");return}if(E.runtimeKey!==Y()){Ce.error("The runtime changed. Select the branch again before sending.");return}f.current=!0;try{const[T,A]=await Promise.all([s.getGitBranches(E.directory),s.getGitStatus(E.directory,{mode:"light"})]),j=he.getState().newSessionDraft.branchIntent;if(!da(E,j))return;if(!T.all.includes(E.branch)||E.branch.startsWith("remotes/")){Ce.error(`Local branch ${E.branch} no longer exists.`),i(E.directory,s);return}if(A.mergeInProgress||A.rebaseInProgress||A.attentionReason){const L=A.attentionReason??(A.rebaseInProgress?"rebase":"merge");Ce.error(`Finish or abort the ${L} before switching branches.`);return}const k=A.current?.trim()||T.current?.trim()||null;if(k===E.branch){y(I.continuation,E);return}const _=I.projectId?lt.getState().projects.find(L=>L.id===I.projectId)?.label?.trim():null,M=E.directory.split(/[\\/]/).filter(Boolean).pop()||E.directory;d({runtimeKey:E.runtimeKey,projectId:I.projectId??null,directory:E.directory,branch:E.branch,currentBranch:k,projectLabel:_||M,changedFileCount:A.files.length,activeSessions:Mv(E.directory,I.projectId),phase:"ready",continuation:I.continuation})}catch(T){Ce.error(T instanceof Error?T.message:"Failed to inspect the selected branch.")}finally{f.current=!1}}},[i,s,l,y]),C=p.useCallback(()=>{u.current+=1,h.current=null,d(null)},[]),w=p.useCallback(async()=>{const I=l;if(!I||I.phase==="checking"||I.phase==="terminal-error"||!s)return;const E=u.current+1;u.current=E,d({...I,phase:"checking",activeSessionsChanged:!1,error:void 0});try{const T=he.getState().newSessionDraft;if(!T.open||!da(T.branchIntent,I))throw Object.assign(new Error("The draft target changed. Press Send again to review the branch."),{terminal:!0});if(I.runtimeKey!==Y())throw Object.assign(new Error("The runtime changed. Select the branch again before sending."),{terminal:!0});const A=Mv(I.directory,I.projectId);if(UB(I.activeSessions,A)){d({...I,activeSessions:A,phase:"ready",activeSessionsChanged:!0,error:void 0});return}const j=await s.getGitBranches(I.directory);if(u.current!==E)return;const k=j.current?.trim()||null;if(k!==I.currentBranch&&k!==I.branch)throw Object.assign(new Error(`The current branch changed to ${k??"detached HEAD"}. Press Send again to review it.`),{terminal:!0});if(!j.all.includes(I.branch)||I.branch.startsWith("remotes/"))throw Object.assign(new Error(`Local branch ${I.branch} no longer exists.`),{terminal:!0});if(k!==I.branch&&(await s.checkoutBranch(I.directory,I.branch,{expectedCurrent:k,localOnly:!0})).currentBranch!==I.branch)throw Object.assign(new Error(`Git did not confirm checkout of ${I.branch}.`),{terminal:!0});if(u.current!==E)return;if(I.runtimeKey!==Y()){Ce.warning("The branch may have changed on the previous runtime. The message was not sent.");return}S(I.directory),d(null),y(I.continuation,I)}catch(T){if(u.current!==E)return;const A=T instanceof Error?T.message:"Failed to check out the selected branch.";let j;try{j=(await s.getGitBranches(I.directory)).current?.trim()||null}catch{j=void 0}if(u.current!==E)return;S(I.directory);const k=!!(T&&typeof T=="object"&&"terminal"in T)||T&&typeof T=="object"&&"code"in T&&T.code==="BRANCH_CHANGED"||j===I.branch||j===void 0,_=j===I.branch?`Git switched to ${I.branch}, but reported an error: ${A} Review the repository, then press Send again.`:A;d({...I,phase:k?"terminal-error":"retryable-error",error:_})}},[s,l,S,y]);return{dialogState:l,request:v,confirm:w,cancel:C,getReceipt:I=>da(I,h.current)?h.current:null,clearReceipt:()=>{h.current=null}}}function WB(e){const{taskId:t,intent:n}=e,{git:r}=qa(),s=un(f=>f.refreshProject),o=t??a3(n),a=cn(p.useCallback(f=>o?f.entries.get(o)??null:null,[o]))?.state??null,l=p.useCallback(async f=>{try{const u=await cn.getState().request({taskId:t??void 0,intent:f.intent,prompt:f.prompt,...f.failedSend?{failedSend:f.failedSend}:{},git:r??void 0,refreshProject:s});return f.intent.runtimeKey!==Y()?null:u}catch(u){return u instanceof Error&&u.message===Pl,null}},[r,s,t]),d=p.useCallback(f=>{const u=o?cn.getState().getEntryByKey(o):cn.getState().getEntry(f);return!u?.receipt||!f?null:lN(f,u.receipt)?u.receipt:null},[o]);return{state:a,request:l,getReceipt:d}}function KB(e){const{isMobile:t,editorRef:n,formRef:r,controlsPanelOpen:s,attachMenuOpen:o}=e,[i,a]=p.useState(!1),[l,d]=p.useState(!1),f=p.useRef(0),u=p.useRef(!1),h=p.useRef(null);p.useEffect(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),p.useEffect(()=>{if(!t||typeof document>"u")return;let v=document.getElementById("mobile-overlay-root");v||(v=document.createElement("div"),v.id="mobile-overlay-root",document.body.appendChild(v));const C=v,w=()=>d(C.childElementCount>0);w();const I=new MutationObserver(w);return I.observe(C,{childList:!0}),()=>I.disconnect()},[t]);const m=l||s||o,g=p.useRef(0),x=p.useRef(0);p.useEffect(()=>{if(!t||cr()||typeof window>"u"||!window.matchMedia?.("(display-mode: standalone)")?.matches)return;const v=()=>{g.current+=1},C=()=>{if(g.current=Math.max(0,g.current-1),!u.current||g.current>0)return;u.current=!1,x.current=Date.now()+600,n.current?.focus(),n.current?.isFocused()&&a(!0);const w=()=>{const I=n.current;I?.isFocused()&&(r.current??I.getScrollDOM())?.scrollIntoView({block:"end"})};window.setTimeout(w,300),window.setTimeout(w,650)};return window.addEventListener("oc:mobile-overlay-opened",v),window.addEventListener("oc:mobile-overlay-closed",C),()=>{window.removeEventListener("oc:mobile-overlay-opened",v),window.removeEventListener("oc:mobile-overlay-closed",C)}},[n,r,t]),p.useEffect(()=>{if(!t)return;if(m){(i||Date.now()-f.current<800)&&(u.current=!0);return}if(!u.current)return;const v=window.setTimeout(()=>{u.current=!1,n.current?.focus({preventScroll:cr()})},180);return()=>window.clearTimeout(v)},[n,i,t,m]),p.useEffect(()=>{if(!t||cr()||typeof document>"u")return;const v=document.documentElement;return i?v.classList.add("oc-browser-keyboard-open"):(v.classList.remove("oc-browser-keyboard-open"),window.matchMedia?.("(display-mode: standalone)")?.matches&&window.setTimeout(()=>{v.classList.contains("oc-browser-keyboard-open")||(window.scrollTo(0,0),document.body.scrollTop=0,v.scrollTop=0)},350)),()=>v.classList.remove("oc-browser-keyboard-open")},[i,t]);const b=p.useCallback(()=>{t&&(cr()&&UE(),h.current!==null&&(window.clearTimeout(h.current),h.current=null),a(!0))},[t]),S=p.useCallback(()=>{if(t){if(Date.now()<x.current){const v=n.current;if(v){v.focus(),window.setTimeout(()=>{Date.now()<x.current&&!v.isFocused()&&v.focus()},50);return}}if(f.current=Date.now(),cr()){ba.flushSync(()=>a(!1));return}h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,a(!1)},120)}},[n,t]),y=p.useCallback(()=>{u.current=!1},[]);return{focused:i,onEditorFocus:b,onEditorBlur:S,cancelOverlayCloseRestore:y}}function Iv(e){e.style.position="",e.style.left="",e.style.right="",e.style.width="",e.style.top="",e.style.height="",e.style.zIndex="",e.style.background=""}function GB(e){const{isMobile:t,isFullscreen:n,isDraftScreen:r,isFocused:s,formRef:o,editorRef:i}=e;p.useLayoutEffect(()=>{if(!t||!n||cr())return;const a=window.visualViewport,l=o.current,d=i.current;if(!a||!l)return;document.documentElement.classList.add("oc-browser-kb-fullscreen");const f=()=>{const u=Math.max(0,Math.floor(a.offsetTop)),h=document.documentElement.clientHeight;l.style.position="fixed",l.style.left="0",l.style.right="0",l.style.top=`${u}px`,l.style.height=`${Math.floor(Math.min(a.height,h-u))}px`,l.style.zIndex="40",l.style.background="var(--background)"};return f(),a.addEventListener("resize",f),a.addEventListener("scroll",f),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{a.removeEventListener("resize",f),a.removeEventListener("scroll",f),window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0),document.documentElement.classList.remove("oc-browser-kb-fullscreen"),Iv(l),requestAnimationFrame(()=>{d?.isFocused()&&d.getScrollDOM()?.scrollIntoView({block:"nearest"})})}},[i,o,n,t]),p.useLayoutEffect(()=>{if(!t||cr()||!r||n||!s)return;const a=window.visualViewport,l=o.current;if(!a||!l)return;const d=l.getBoundingClientRect();l.style.position="fixed",l.style.left=`${Math.floor(d.left)}px`,l.style.width=`${Math.floor(d.width)}px`,l.style.zIndex="40",l.style.background="var(--background)";let f=Number.NaN,u=0;const h=()=>{const m=document.documentElement.clientHeight,g=a.offsetTop+a.height,x=Math.max(0,Math.floor(Math.min(g,m)-l.offsetHeight));x!==f&&(f=x,l.style.top=`${x}px`),u=requestAnimationFrame(h)};return h(),()=>{cancelAnimationFrame(u),Iv(l)}},[o,r,s,n,t])}const ZB=600*1e3,Ev=60*1e3,YB=[2e3,5e3,15e3],XB=200,Un=new Map,Td=new Set,D4=()=>{for(const e of Td)e()},JB=e=>(Td.add(e),()=>{Td.delete(e)});Zt(D4);const $1=e=>{const t=e?.trim();return t?t.length>1?t.replace(/[\\/]+$/,""):t:null},z1=e=>`${Y()}\0${e}`,mh=(e,t)=>{const n=Un.get(e);for(n?.url&&n.url!==t.url&&URL.revokeObjectURL(n.url),Un.delete(e),Un.set(e,t);Un.size>XB;){const[r,s]=Un.entries().next().value;s.url&&URL.revokeObjectURL(s.url),Un.delete(r)}D4()},QB=async e=>{const t=await Rt("/api/fs/project-icon",{query:{directory:e}});if(t.status===204)return null;if(!t.ok)throw new Error(`Project icon request failed (${t.status})`);const n=await t.blob();return n.size===0||!n.type.startsWith("image/")?null:URL.createObjectURL(n)},O4=(e,t,n=!1)=>{const r=Un.get(e);if(r&&(r.loading||!n&&r.expiresAt>Date.now()))return;const s=r?.failures??0;mh(e,{url:r?.url??null,expiresAt:0,loading:!0,failures:s}),QB(t).then(o=>{if(Un.get(e)?.loading!==!0){o&&URL.revokeObjectURL(o);return}mh(e,{url:o,expiresAt:Date.now()+(o?ZB:Ev),loading:!1,failures:0})},()=>{const o=Un.get(e);if(o?.loading!==!0)return;const i=YB[s];mh(e,{url:o.url,expiresAt:Date.now()+(i??Ev),loading:!1,failures:s+1}),i!==void 0&&setTimeout(()=>{Td.size>0&&O4(e,t,!0)},i)})},eV=e=>{const t=$1(e);return t?Un.get(z1(t))?.url??null:null},tV=e=>{const t=$1(e);t&&O4(z1(t),t)},nV=e=>{const t=p.useSyncExternalStore(JB,()=>eV(e),()=>null),n=$1(e),r=n?z1(n):null;return p.useEffect(()=>{r&&tV(e)},[r,e]),t},gh=["var(--syntax-keyword)","var(--syntax-string)","var(--syntax-number)","var(--syntax-function)","var(--syntax-type)","var(--syntax-variable)","var(--primary)"],rV=e=>{const t=e.normalize("NFKC").match(/[\p{L}\p{N}]/u)?.[0];return t?t.toLocaleUpperCase():"?"},sV=e=>{let t=0;for(const n of e.normalize("NFKC").trim().toLowerCase())t=t*31+(n.codePointAt(0)??0)>>>0;return gh[t%gh.length]??gh[0]},oV=e=>({text:rV(e),color:sV(e)}),to=16,iV=96,aV=.12,cV=.6,_v=.1;function lV(e){let t=0,n=0,r=0;for(let s=0;s+3<e.length;s+=4){if(e[s+3]<iV)continue;t+=1;const o=wp({r:e[s],g:e[s+1],b:e[s+2]});o>aV&&(n+=1),o<cV&&(r+=1)}return t===0?"mixed":n/t<=_v?"dark":r/t<=_v?"light":"mixed"}const dV=400,ho=new Map;function uV(e){return ho.get(e)}function fV(e,t){const n=ho.get(t);if(n)return n;let r="mixed";try{const s=document.createElement("canvas");s.width=to,s.height=to;const o=s.getContext("2d",{willReadFrequently:!0});o&&(o.drawImage(e,0,0,to,to),r=lV(o.getImageData(0,0,to,to).data))}catch{r="mixed"}if(ho.set(t,r),ho.size>dV){const s=ho.keys().next().value;s!==void 0&&ho.delete(s)}return r}function hV({directory:e,label:t,className:n}){const r=nV(e),[s,o]=p.useState(null),[i,a]=p.useState(null),l=r?i?.url===r?i.tone:uV(r):void 0;return r&&r!==s?c.jsx("img",{src:r,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(r),onLoad:d=>{l||a({url:r,tone:fV(d.currentTarget,r)})},"data-project-icon":"image","data-icon-tone":l&&l!=="mixed"?l:void 0,className:R("size-4 shrink-0 rounded-[25%] object-contain",n)}):c.jsx(pV,{label:t,className:n})}function pV({label:e,className:t}){const n=p.useMemo(()=>oV(e),[e]);return c.jsx("span",{"aria-hidden":"true","data-project-icon":"mark",className:R("inline-flex size-4 shrink-0 items-center justify-center overflow-hidden rounded-[25%]",t),style:{color:n.color,backgroundColor:`color-mix(in srgb, ${n.color} 20%, transparent)`},children:c.jsx("svg",{viewBox:"0 0 16 16",className:"size-full select-none",children:c.jsx("text",{x:"8",y:"11.7",textAnchor:"middle",fill:"currentColor",fontSize:"10.5",fontWeight:700,children:n.text})})})}const U1=(e,t)=>{const[n,r]=p.useState(e),s=p.useRef(null),o=p.useCallback(()=>{s.current!==null&&typeof window<"u"&&(window.clearTimeout(s.current),s.current=null)},[]);p.useEffect(()=>o,[o]);const i=p.useCallback(()=>{o(),r(e)},[o,e]),a=p.useCallback(l=>{o(),r(l),!(typeof window>"u")&&(s.current=window.setTimeout(()=>{r(e),s.current=null},t))},[o,t,e]);return{value:n,show:a,clear:i}},H4=20,mV=24,gV=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`;function Ad({project:e,maxCharacters:t}){const n=za(e),r=e.id==="__home__"||e.ownerProjectId==="__home__",s=e.kind==="worktree";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:n,children:[s||r?c.jsx($,{name:s?"git-branch":"home",className:"size-3.5 shrink-0 text-muted-foreground"}):c.jsx(hV,{directory:e.path,label:n,className:"size-3.5"}),s?c.jsx(d1,{value:n,showTitle:!1,className:"text-muted-foreground",style:t?{maxWidth:`${t}ch`}:void 0}):c.jsx("span",{className:"truncate text-muted-foreground",children:t?gV(n,t):n})]})}const jv="h-7 min-w-0 w-fit max-w-[48vw] gap-1 border-transparent bg-transparent px-1.5 text-muted-foreground typography-meta font-normal hover:bg-transparent hover:text-foreground data-[popup-open]:bg-transparent [&_svg]:size-3.5 [&_svg]:opacity-70 sm:max-w-none",F4=({checked:e,onChange:t,showCheck:n=!0,chromeLess:r=!1,keepWidth:s=!1})=>c.jsxs(wt,{delayDuration:300,children:[c.jsx(St,{asChild:!0,children:c.jsxs(be,{variant:r?"ghost":"chip",size:"xs",className:R(s?"shrink-0":"min-w-0 max-w-[48vw] shrink sm:max-w-none",r&&"aria-pressed:bg-interactive-hover aria-pressed:text-foreground"),"aria-pressed":e,onClick:()=>t?.(!e),children:[c.jsx($,{name:"git-branch",className:"size-3.5"}),c.jsx("span",{className:"truncate",children:"New worktree"}),e&&n?c.jsx($,{name:"check",className:"size-3.5"}):null]})}),c.jsx(Ct,{side:"top",sideOffset:6,className:"max-w-72",children:"Starts from the selected branch's latest commit. Uncommitted changes are not copied."})]}),yV=({label:e,startFrom:t=!1})=>{const n=e??"Branch";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:e??void 0,children:[c.jsx($,{name:"git-branch",className:"size-3.5 shrink-0 text-muted-foreground"}),t&&e?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,e?c.jsx(d1,{value:e,showTitle:!1}):c.jsx("span",{className:"truncate",children:n})]})};function vV({branchName:e}){const{value:t,show:n}=U1(!1,2e3),r=p.useCallback(async s=>{if(s.stopPropagation(),s.preventDefault(),!e)return;(await yr(e)).ok?n(!0):Ce.error("Failed to copy")},[e,n]);return e?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Copy branch name",onClick:s=>{r(s)},children:t?c.jsx($,{name:"check",className:"size-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"size-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:t?"Copied":"Copy branch name"})]}):null}function xV(e){const{projects:t,selectedProject:n,selectedBranchName:r,selectedBranchLabel:s,branchOptions:o,branchInteractive:i,branchLoading:a,showBranchSelector:l,showProjectSelector:d=!0,showWorktreeSelector:f=!1,worktreeMode:u=!1,endAccessory:h,onProjectChange:m,onBranchChange:g,onWorktreeModeChange:x,theme:b}=e;return c.jsxs("div",{className:"mb-3 flex min-w-0 w-full items-center justify-between gap-2 pl-2 pr-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[d?c.jsxs(by,{value:n.id,onValueChange:m,children:[c.jsx(Sy,{size:"sm",className:R(jv,"shrink-0"),children:c.jsx(wy,{children:c.jsx(Ad,{project:n,theme:b,maxCharacters:H4})})}),c.jsx(Cy,{className:"w-max min-w-48",children:t.map(S=>c.jsx(ky,{value:S.id,className:S.kind==="worktree"?"max-w-[24rem] truncate pl-7":"max-w-[24rem] truncate",children:c.jsx(Ad,{project:S,theme:b})},S.id))})]}):null,l&&i?c.jsxs(by,{value:r??void 0,onValueChange:g,disabled:!!(a&&o.length===0),children:[c.jsx(Sy,{size:"sm",className:jv,children:c.jsx(wy,{children:c.jsx(yV,{label:s,startFrom:u})})}),c.jsx(Cy,{className:"w-max min-w-56",children:c.jsxs(eP,{children:[c.jsx(tP,{children:a?"Loading branches...":"Local branches"}),o.map(S=>c.jsx(ky,{value:S.value,className:"max-w-[28rem] truncate",children:S.label},S.value))]})})]}):null,f?c.jsx(F4,{checked:u,onChange:x,keepWidth:!0}):null]}),h?c.jsx("div",{className:"min-w-0 shrink-0",children:h}):null]})}function bV(e){const{selectedProject:t,selectedBranchName:n,selectedBranchLabel:r,branchInteractive:s,showBranchSelector:o,showProjectSelector:i=!0,showWorktreeSelector:a=!1,worktreeMode:l=!1,onWorktreeModeChange:d,endAccessory:f,theme:u,onOpenPicker:h}=e,m=r?c.jsx(d1,{value:r,showTitle:!1,style:{maxWidth:`${mV}ch`}}):c.jsx("span",{className:"truncate",children:"Branch"});return c.jsxs("div",{className:"mb-1.5 flex min-w-0 w-full flex-col gap-0.5 pl-2 pr-1",children:[a?c.jsx("div",{className:"flex w-full justify-end",children:c.jsx(F4,{checked:l,onChange:d,showCheck:!1,chromeLess:!0})}):null,c.jsxs("div",{className:"flex min-w-0 w-full items-center gap-x-1",children:[i?c.jsxs("button",{type:"button",className:"inline-flex h-7 min-w-0 max-w-[44%] shrink cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-meta font-medium text-foreground/80 hover:bg-[var(--interactive-hover)]",onClick:()=>h("project"),children:[c.jsx(Ad,{project:t,theme:u,maxCharacters:H4}),c.jsx($,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):null,o&&s?c.jsxs("button",{type:"button",className:`inline-flex h-7 min-w-0 cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-meta font-medium text-foreground/80 hover:bg-[var(--interactive-hover)] ${i?"ml-auto max-w-[54%] shrink":"flex-1"}`,onClick:()=>h("branch"),title:r??void 0,children:[c.jsx($,{name:"git-branch",className:"h-3 w-3 shrink-0 text-muted-foreground"}),l&&r?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,m,c.jsx($,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):o?c.jsxs("div",{className:`inline-flex h-7 min-w-0 items-center gap-1 px-1.5 typography-meta text-muted-foreground ${i?"ml-auto max-w-[54%] shrink":"min-w-0 flex-1"}`,title:r??void 0,children:[c.jsx($,{name:"git-branch",className:"h-3 w-3 shrink-0"}),l&&r?c.jsx("span",{className:"shrink-0 text-subtle-foreground",children:"from"}):null,m,c.jsx(vV,{branchName:n})]}):null,!i&&f?c.jsx("div",{className:`min-w-0 shrink-0 ${o?"":"ml-auto"}`,children:f}):null]})]})}function wV(e){const{projects:t,selectedProject:n,selectedBranchName:r,branchOptions:s,branchInteractive:o,onProjectChange:i,onBranchChange:a,theme:l,openPicker:d,onOpenPickerChange:f,showProjectSelector:u=!0,showBranchSelector:h,query:m="",onQueryChange:g}=e,[x,b]=p.useState("");p.useEffect(()=>{d!=="project"&&b(""),d!=="branch"&&g?.("")},[g,d]);const S=p.useMemo(()=>{const v=x.trim().toLowerCase();return v?t.filter(C=>za(C).toLowerCase().includes(v)||C.path.toLowerCase().includes(v)):t},[x,t]),y=p.useMemo(()=>{const v=m.trim().toLowerCase();return v?s.filter(C=>C.label.toLowerCase().includes(v)):s},[s,m]);return c.jsxs(c.Fragment,{children:[c.jsx(Ta,{open:u&&d==="project",onClose:()=>f(null),title:"Project",children:c.jsxs("div",{className:"flex flex-col py-1",children:[t.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Uo,{value:x,onChange:v=>b(v.target.value),placeholder:"Search projects...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:S.map(v=>{const C=v.id===n.id;return c.jsxs("button",{type:"button",onClick:()=>{i(v.id),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${v.kind==="worktree"?"pl-7 ":""}${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx(Ad,{project:v,theme:l}),C?c.jsx($,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.id)})})]})}),c.jsx(Ta,{open:o&&h&&d==="branch",onClose:()=>f(null),title:"Branch",children:c.jsxs("div",{className:"flex flex-col py-1",children:[s.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Uo,{value:m,onChange:v=>g?.(v.target.value),placeholder:"Search branches...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:y.map(v=>{const C=v.value===r;return c.jsxs("button",{type:"button",onClick:()=>{a(v.value),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx("span",{className:"truncate",children:v.label}),C?c.jsx($,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.value)})})]})})]})}function SV(e){const{state:t,onCancel:n,onConfirm:r}=e,s=t?.phase==="checking",o=t?.phase==="terminal-error";return c.jsx(gu,{open:t!==null,onOpenChange:i=>{!i&&!s&&n()},children:c.jsxs(yu,{showCloseButton:!1,className:"max-w-md gap-5",children:[c.jsxs(vu,{children:[c.jsx(xu,{children:o?"Branch checkout needs attention":"Check out branch?"}),c.jsx(o1,{children:t?`PiChamber will check out "${t.branch}" in "${t.projectLabel}" before creating the session. This changes the files used by every session and terminal in this folder.`:""})]}),t?.activeSessions.length?c.jsxs("section",{"aria-live":"polite",className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[c.jsx("h3",{className:"typography-ui-label font-medium text-foreground",children:t.activeSessions.length===1?"Another session is active in this project":`${t.activeSessions.length} other sessions are active in this project`}),c.jsx("p",{className:"mt-1 typography-meta text-muted-foreground",children:"Switching branches may interrupt sessions using this folder or conflict with work in a related worktree."}),c.jsx("ul",{className:"mt-2 max-h-32 list-disc space-y-1 overflow-y-auto pl-5 typography-meta text-foreground",children:t.activeSessions.map(i=>c.jsx("li",{children:i.title??"Untitled session"},i.id))}),t.activeSessionsChanged?c.jsx("p",{className:"mt-2 typography-meta font-medium text-status-warning",children:"The active session list changed. Review it before continuing."}):null]}):null,t?.changedFileCount?c.jsx("p",{className:"typography-ui-label text-muted-foreground",children:t.changedFileCount===1?"This folder has 1 uncommitted file. Git may block the checkout if it conflicts.":`This folder has ${t.changedFileCount} uncommitted files. Git may block the checkout if they conflict.`}):null,t?.error?c.jsx("p",{role:"alert",className:"typography-ui-label text-status-error",children:t.error}):null,c.jsxs(Ej,{children:[c.jsx(be,{variant:"outline",onClick:n,disabled:s,children:o?"Close":"Cancel"}),o?null:c.jsx(be,{onClick:r,disabled:s,children:s?"Checking out...":t?.phase==="retryable-error"?"Try again":"Check out and send"})]})]})})}const q1=(e,t)=>{const[n,r]=p.useState(void 0);return p.useLayoutEffect(()=>{if(!t)return;const s=()=>{const o=e.current;if(!o)return;const i=o.closest("main");if(!i)return;const a=window.visualViewport?.offsetTop??0,l=Math.max(i.getBoundingClientRect().top,a),d=o.getBoundingClientRect().bottom-l-8,f=Math.max(120,Math.floor(d));r(u=>u===f?u:f)};return s(),window.addEventListener("resize",s),window.addEventListener("oc:keyboard-settled",s),window.visualViewport?.addEventListener("resize",s),window.visualViewport?.addEventListener("scroll",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("oc:keyboard-settled",s),window.visualViewport?.removeEventListener("resize",s),window.visualViewport?.removeEventListener("scroll",s)}}),t?n:void 0},Kr=e=>e.invocationName??e.name;function Tv(e,t){const n=Kr(e),r=Kr(t),s=e.searchAliases??[],o=[...s,...n===r&&e.name===t.name?[]:[t.name],...t.invocationName&&t.invocationName!==t.name&&t.invocationName!==n?[t.invocationName]:[],...t.description?[t.description]:[],...t.searchAliases??[]].filter((a,l,d)=>a!==e.description&&d.indexOf(a)===l);return o.length===s.length&&o.every((a,l)=>a===s[l])?e:{...e,searchAliases:o}}function CV(e,t,n,r=[]){const s=[],o=new Map,i=(a,l)=>{for(const d of a){const f=l(d),u=Kr(d),h=o.get(u);if(!h){o.set(u,{index:s.length,item:d,precedence:f}),s.push(d);continue}const m=f>h.precedence?Tv(d,h.item):Tv(h.item,d);s[h.index]=m,o.set(u,{index:h.index,item:m,precedence:Math.max(h.precedence,f)})}};return i(e,()=>4),i(t,a=>a.isBuiltIn?4:a.source==="extension"?3:a.isSkill?1:0),i(n,()=>2),i(r,()=>1),s}function Av(e,t){switch(t){case"all":return!0;case"system":return!!e.isBuiltIn||e.source==="pichamber"||e.source==="system";case"skills":return!!e.isSkill||e.source==="skill";case"extensions":return e.source==="extension";case"prompts":return e.source==="prompt"}}function kV(e,t){return yo(e.name,t)||yo(Kr(e),t)||!!(e.description&&yo(e.description,t))||!!e.searchAliases?.some(n=>yo(n,t))}function MV(e,t,n){const r=t.trim(),s=r.toLowerCase(),i=[...r?e.filter(a=>Av(a,n)&&kV(a,r)):e.filter(a=>Av(a,n))];return i.sort((a,l)=>{const d=Kr(a).toLowerCase(),f=Kr(l).toLowerCase(),u=s.length>0&&d.startsWith(s),h=s.length>0&&f.startsWith(s);return u&&!h?-1:!u&&h?1:d.localeCompare(f)}),i}function IV(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function EV(e){return`command-listbox-${e.length>0?e:"commands"}`}function Zp(e,t){return`${e}-option-${t}`}function _V(e){if(!e.loading&&e.hasSelectedCommand)return Zp(e.listboxId,e.selectedIndex)}const Nv=e=>{if(e.source==="skill"||e.isSkill)return"Skill";if(e.source==="extension")return"Extension";if(e.source==="prompt")return"Prompt";if(e.source==="system"||e.source==="pichamber"||e.isBuiltIn)return"System";const t=[e.scope,e.agent].filter(n=>!!n);return t.length>0?t.join(" · "):null},jV=[{value:"all",label:"All"},{value:"system",label:"System"},{value:"prompts",label:"Prompts"},{value:"skills",label:"Skills"},{value:"extensions",label:"Extensions"}],B4=p.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,style:r,onComboboxStateChange:s},o)=>{const i=he(N=>N.currentSessionId),l=Qm(i??"").length>0,d=!!i,f=re(N=>N.isMobile),[u,h]=p.useState("all"),m=Xn(),{commands:g,isLoading:x}=C4(m),[b,S]=p.useState([]),[y,v]=p.useState(!1),[C,w]=p.useState(0),I=p.useRef(0),E=p.useRef(!1),T=p.useRef([]),A=p.useRef(null),j=q1(A,f),k=p.useRef(!1),_=p.useRef(null),M=p.useRef(!1),L=p.useId(),O=p.useMemo(()=>EV(IV(L)),[L]);return p.useEffect(()=>{const N=D=>{const W=D.target;!W||!A.current||A.current.contains(W)||n()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n]),p.useEffect(()=>{v(x);const N=g.filter(X=>X.source==="system").filter(X=>X.invocationName==="compact"?!0:d).map(X=>({id:X.id,name:X.name,invocationName:X.invocationName,source:"system",description:X.description,isBuiltIn:!0,...X.scope?{scope:X.scope}:{}})),D=g.filter(X=>X.source!=="system").map(X=>({id:X.id,name:X.name,invocationName:X.invocationName,source:X.source,description:X.description,...X.source==="skill"?{isSkill:!0}:{},...X.scope?{scope:X.scope}:{}})),W=CV(N,D.filter(X=>X.source==="extension"),D.filter(X=>X.source==="skill"),D.filter(X=>X.source==="prompt"));S(MV(W,e,f?"all":u))},[e,d,l,g,x,u,f]),p.useEffect(()=>{w(0)},[b]),p.useEffect(()=>{I.current=C},[C]),p.useEffect(()=>{s?.({listboxId:O,activeOptionId:_V({loading:y,hasSelectedCommand:!!b[C],selectedIndex:C,listboxId:O})})},[b,O,y,s,C]),p.useEffect(()=>{T.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useImperativeHandle(o,()=>({handleKeyDown:N=>{const D=b.length;if(N==="Escape"){n();return}if(D!==0){if(N==="ArrowDown"){E.current=!0,w(W=>(W+1)%D);return}if(N==="ArrowUp"){E.current=!0,w(W=>(W-1+D)%D);return}if(N==="Enter"||N==="Tab"){const W=(I.current%D+D)%D,z=b[W];z&&t(z)}}}}),[b,n,t]),f?c.jsx("div",{ref:A,className:"absolute bottom-full left-0 z-[100] mb-2 flex max-h-60 min-w-0 w-full max-w-[450px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-none",style:j!==void 0?{...r,maxHeight:j}:r,children:c.jsx(Yn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx($,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((N,D)=>{const W=D===C,z=Nv(N),X=Kr(N);return c.jsx("div",{id:Zp(O,D),ref:F=>{T.current[D]=F},role:"option","aria-selected":W,className:R("flex cursor-pointer items-center gap-2 rounded-lg px-3 py-1.5 typography-ui-label",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:F=>F.preventDefault(),onPointerDown:F=>{F.pointerType==="touch"&&(_.current={x:F.clientX,y:F.clientY},M.current=!1)},onPointerMove:F=>{if(F.pointerType!=="touch"||!_.current)return;const U=F.clientX-_.current.x,P=F.clientY-_.current.y;Math.hypot(U,P)>6&&(M.current=!0)},onPointerUp:F=>{if(F.pointerType!=="touch")return;const U=M.current;_.current=null,M.current=!1,!U&&(F.preventDefault(),F.stopPropagation(),k.current=!0,t(N))},onPointerCancel:()=>{_.current=null,M.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(N)},onMouseMove:()=>{E.current=!1,w(D)},children:c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono font-semibold",children:["/",X]}),z&&c.jsx("span",{className:"shrink-0 rounded border border-[var(--interactive-border)]/60 bg-[var(--surface-muted)] px-1.5 py-1 text-[10px] font-bold uppercase leading-none tracking-tight text-muted-foreground",children:z})]})},N.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})})}):c.jsxs("div",{ref:A,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:j!==void 0?{...r,maxHeight:j}:r,children:[c.jsx("div",{role:"group","aria-label":"Filter commands",className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1.5",children:jV.map(N=>c.jsx(be,{variant:"chip",size:"xs","aria-pressed":u===N.value,onMouseDown:D=>D.preventDefault(),onClick:()=>h(N.value),children:N.label},N.value))}),c.jsx(Yn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx($,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((N,D)=>{const W=D===C,z=Nv(N),X=Kr(N);return c.jsx("div",{id:Zp(O,D),ref:F=>{T.current[D]=F},role:"option","aria-selected":W,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:F=>F.preventDefault(),onPointerDown:F=>{F.pointerType==="touch"&&(_.current={x:F.clientX,y:F.clientY},M.current=!1)},onPointerMove:F=>{if(F.pointerType!=="touch"||!_.current)return;const U=F.clientX-_.current.x,P=F.clientY-_.current.y;Math.hypot(U,P)>6&&(M.current=!0)},onPointerUp:F=>{if(F.pointerType!=="touch")return;const U=M.current;_.current=null,M.current=!1,!U&&(F.preventDefault(),F.stopPropagation(),k.current=!0,t(N))},onPointerCancel:()=>{_.current=null,M.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(N)},onMouseMove:()=>{E.current=!1,w(D)},children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["/",X]}),z&&c.jsx("span",{className:R("ml-auto max-w-[45%] shrink-0 truncate text-xs leading-4",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:z})]}),N.description&&c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:N.description}),N.source==="skill"&&N.name!==X&&c.jsx("div",{className:R("mt-0.5 truncate text-xs leading-4",W?"text-interactive-selection-foreground/60":"text-subtle-foreground"),children:N.name})]})},N.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),!f&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});B4.displayName="CommandAutocomplete";const TV=(e,t=200)=>{const[n,r]=H.useState(e);return H.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},AV=p.forwardRef(({searchQuery:e,onFileSelect:t,onClose:n,style:r},s)=>{const o=S4()??"",i=lt(G=>G.activeProjectId),a=lt(p.useCallback(G=>G.projects.find(K=>K.id===i)?.path??null,[i])),l=p.useMemo(()=>{const G=a||o;return G?G.replace(/\\/g,"/").replace(/\/+$/,""):null},[a,o]),d=yC(p.useCallback(G=>l?G.byRoot[l]:void 0,[l])),f=vC(G=>G.searchFiles),u=TV(e,180),h=xC(),[m,g]=p.useState([]),[x,b]=p.useState([]),[S,y]=p.useState(!1),v=p.useRef(0),[C,w]=p.useState(0),I=p.useRef(0),[E,T]=p.useState(360),[A,j]=p.useState({}),[k,_]=p.useState({}),M=p.useRef([]),L=p.useRef([]),O=p.useRef([]),N=p.useRef(null),D=re(G=>G.isMobile),W=q1(N,D),z=(e??"").trim(),X=p.useMemo(()=>{if(!l||!d)return[];const G=[d.selectedPath,...d.openPaths.slice().reverse()].filter(oe=>typeof oe=="string"&&oe.length>0),K=new Set,se=z.toLowerCase();return G.filter(oe=>{if(K.has(oe))return!1;K.add(oe);const ue=oe.startsWith(`${l}/`)?oe.slice(l.length+1):oe;return se?ue.toLowerCase().includes(se):!0}).slice(0,6).map(oe=>{const ue=oe.replace(/\\/g,"/"),ye=ue.split("/").filter(Boolean).pop()||ue,we=ue.startsWith(`${l}/`)?ue.slice(l.length+1):ue;return{name:ye,path:ue,relativePath:we,extension:ye.includes(".")?ye.split(".").pop()?.toLowerCase():void 0}})},[z,l,d]),F=x,U=X,P=m;p.useEffect(()=>{const G=K=>{const se=K.target;!se||!N.current||N.current.contains(se)||n()};return document.addEventListener("pointerdown",G,!0),()=>{document.removeEventListener("pointerdown",G,!0)}},[n]),p.useEffect(()=>{if(!o){g([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){g([]);return}let se=!1;return v.current++,y(!0),f(o,K,80,{includeHidden:!0,respectGitignore:!h,type:"file"}).then(le=>{if(se)return;const oe=new Set(X.map(ue=>ue.path));g(le.filter(ue=>!oe.has(ue.path)).slice(0,15))}).catch(()=>{se||g([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,X,f,h]),p.useEffect(()=>{if(!o){b([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){b([]);return}let se=!1;return v.current++,y(!0),f(o,K,20,{includeHidden:!0,respectGitignore:!h,type:"directory"}).then(le=>{se||b(le.slice(0,10))}).catch(()=>{se||b([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,f,h]),p.useEffect(()=>{w(0),j({}),_({})},[P,F,U.length]),p.useEffect(()=>{I.current=C},[C]),p.useEffect(()=>{M.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useEffect(()=>{let G=null;const K=()=>{G!==null&&cancelAnimationFrame(G),G=requestAnimationFrame(()=>{const se={},le={};L.current.forEach((oe,ue)=>{if(!oe)return;const we=O.current[ue]?.offsetWidth??oe.scrollWidth,Me=Math.max(0,we-oe.clientWidth),He=Me>8;if(se[ue]=He,He){const Ae=Math.max(.6,Me/110);le[ue]=Ae}}),j(se),_(le)})};return K(),window.addEventListener("resize",K),()=>{G!==null&&cancelAnimationFrame(G),window.removeEventListener("resize",K)}},[P,F]),p.useEffect(()=>{const G=L.current[C];if(!G)return;const K=()=>{const le=G.clientWidth;le>0&&T(le)};if(K(),typeof ResizeObserver>"u")return;const se=new ResizeObserver(K);return se.observe(G),()=>{se.disconnect()}},[C]);const q=p.useCallback(G=>{t(G)},[t]);p.useImperativeHandle(s,()=>({handleKeyDown:G=>{if(G==="Escape"){n();return}const K=F.length+U.length+P.length;if(K!==0){if(G==="ArrowDown"){w(se=>(se+1)%K);return}if(G==="ArrowUp"){w(se=>(se-1+K)%K);return}if(G==="Enter"||G==="Tab"){const le=(I.current%K+K)%K;if(le<F.length){const ye=F[le];ye&&q(ye);return}const oe=le-F.length,ue=oe<U.length?U[oe]:P[oe-U.length];ue&&q(ue)}}}}),[P,F,U,n,q]);const B=G=>{switch(G.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return c.jsx($,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return c.jsx($,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return c.jsx($,{name:"file",className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return c.jsx($,{name:"file-image",className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return c.jsx($,{name:"file-pdf",className:"h-3.5 w-3.5 text-muted-foreground"})}},ee=(G,K,se)=>{const le=G.relativePath||G.name,oe=t0(le,{maxLength:60}),ue=C===K,ye=A[K]??!1,we=k[K]??2.6;return c.jsxs("div",{ref:Me=>{M.current[K]=Me},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(K),children:[B(G),c.jsxs("span",{ref:Me=>{L.current[K]=Me},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:ue?{"--file-mention-marquee-width":`${E}px`,"--file-mention-marquee-duration":`${we}s`}:void 0,"aria-label":le,children:[c.jsx("span",{ref:Me=>{O.current[K]=Me},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:le}),ye&&ue?c.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:le}):c.jsx("span",{className:"block truncate",children:oe})]})]},se)};return c.jsxs("div",{ref:N,className:"absolute z-[100] min-w-0 w-full max-w-[640px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",style:W!==void 0?{...r,maxHeight:W}:r,children:[c.jsx(Yn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-0",children:S?c.jsx("div",{className:"flex items-center justify-center py-4",children:c.jsx($,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})}):c.jsxs("div",{className:"pb-2",children:[F.map((G,K)=>{const se=K,le=G.relativePath||G.name,oe=t0(le,{maxLength:60}),ue=C===se;return c.jsxs("div",{ref:ye=>{M.current[se]=ye},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(se),children:[c.jsx($,{name:"folder-3-fill",className:"h-3.5 w-3.5 text-primary/60"}),c.jsx("span",{className:"flex-1 min-w-0 truncate","aria-label":le,children:oe})]},`dir-${G.path}`)}),F.length>0&&(U.length>0||P.length>0)&&c.jsx("div",{className:"my-1 border-t border-border/60"}),U.map((G,K)=>ee(G,F.length+K,`recent-${G.path}`)),U.length>0&&P.length>0&&c.jsx("div",{className:"my-1 border-t border-border/60"}),P.map((G,K)=>ee(G,F.length+U.length+K,G.path)),P.length===0&&F.length===0&&U.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No matches found"})]})}),!D&&c.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});function NV(e){const t=(e.description||e.content).replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,140).trimEnd()}…`:t}const V4=p.forwardRef(({searchQuery:e,onSnippetSelect:t,onClose:n,style:r},s)=>{const o=p.useRef(null),i=re(E=>E.isMobile),a=q1(o,i),[l,d]=p.useState(0),f=p.useRef(0),[u,h]=p.useState([]),m=p.useRef([]),g=Or(E=>E.snippets),x=Or(E=>E.loadSnippets),b=Xn(),S=Or(E=>E.setSnippetDraft),y=Or(E=>E.setSelectedSnippet),v=re(E=>E.setSettingsDialogOpen),C=re(E=>E.setSettingsPage);p.useEffect(()=>{x(b)},[x,b]),p.useEffect(()=>{const E=e.trim(),A=[...E.length?g.filter(j=>yo(j.name,E)||j.aliases.some(k=>yo(k,E))):g].sort((j,k)=>j.source==="project"&&k.source!=="project"?-1:j.source!=="project"&&k.source==="project"?1:j.name.localeCompare(k.name));h(A),d(A.length?1:0)},[e,g]),p.useEffect(()=>{f.current=l,m.current[l]?.scrollIntoView({block:"nearest"})},[l]),p.useEffect(()=>{const E=T=>{const A=T.target;A&&o.current&&!o.current.contains(A)&&n()};return document.addEventListener("pointerdown",E,!0),()=>document.removeEventListener("pointerdown",E,!0)},[n]);const w=p.useCallback(E=>{const T=e.trim(),A=E.aliases.includes(T)?T:E.name;t(E,A)},[t,e]),I=p.useCallback(()=>{const E=new Set(g.map(j=>j.name));let T="new-snippet",A=1;for(;E.has(T);)T=`new-snippet-${A++}`;S({name:T,scope:"global"}),y(null),C("snippets"),v(!0),n()},[n,y,v,C,S,g]);return p.useImperativeHandle(s,()=>({handleKeyDown:E=>{if(E==="Escape"){n();return}const T=u.length+1;if(E==="ArrowDown"){d(A=>(A+1)%T);return}if(E==="ArrowUp"){d(A=>(A-1+T)%T);return}if(E==="Enter"||E==="Tab"){if(f.current===0){I();return}const A=u[f.current-1];A&&w(A)}}}),[w,u,n,I]),c.jsxs("div",{ref:o,role:"listbox","aria-label":"Snippets","aria-activedescendant":l===0?"snippet-option-new":`snippet-option-${l}`,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:a!==void 0?{...r,maxHeight:a}:r,children:[c.jsxs(Yn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:[c.jsx("div",{id:"snippet-option-new",ref:E=>{m.current[0]=E},role:"option","aria-selected":l===0,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",l===0?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:E=>E.preventDefault(),onClick:I,onMouseMove:()=>d(0),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"typography-ui-label font-medium",children:"Create a new snippet"}),c.jsx("div",{className:R("mt-1 text-xs leading-5",l===0?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:"Save reusable text for the # picker"})]})}),u.length?u.map((E,T)=>{const A=T+1,j=A===l,k=E.source==="project"?"Project":"Global",_=NV(E);return c.jsx("div",{id:`snippet-option-${A}`,ref:M=>{m.current[A]=M},role:"option","aria-selected":j,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",j?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:M=>M.preventDefault(),onClick:()=>w(E),onMouseMove:()=>d(A),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["#",E.name]}),c.jsx("span",{className:R("ml-auto shrink-0 text-xs leading-4",j?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:k})]}),_?c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",j?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:_}):null]})},`${E.source}:${E.id}`)}):c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No snippets found"})]}),!i&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});V4.displayName="SnippetAutocomplete";const LV={mention:520,command:520,snippet:520};function RV(e,t){if(t)return{left:`${t.left}px`,top:`${t.top}px`,bottom:"auto",width:`min(${LV[e]}px, calc(100% - ${t.left+8}px))`,maxHeight:`${t.maxHeight}px`,transform:t.place==="above"?"translateY(-100%)":void 0}}function PV(e){const{open:t,query:n,overlayPosition:r,onClose:s}=e;if(!t)return null;const o=RV(t,r);switch(t){case"command":return c.jsx(B4,{ref:e.commandRef,searchQuery:n,onCommandSelect:e.onCommandSelect,onClose:s,style:o,onComboboxStateChange:e.onCommandComboboxStateChange});case"snippet":return c.jsx(V4,{ref:e.snippetRef,searchQuery:n,onSnippetSelect:e.onSnippetSelect,onClose:s,style:o});case"mention":return c.jsx(AV,{ref:e.mentionRef,searchQuery:n,onFileSelect:e.onFileSelect,onClose:s,style:o})}}const Lv=Object.freeze({0:"var(--primary)",1:"var(--border)",2:"var(--primary)",3:"var(--border)",4:"var(--status-success)",5:"var(--status-error)",6:"var(--status-warning)",7:"var(--muted-foreground)",8:"var(--muted-foreground)",9:"var(--foreground)",10:"var(--muted-foreground)",11:"transparent",12:"var(--oc-scrollbar-thumb, var(--muted-foreground))",13:"var(--foreground)",14:"var(--foreground)",15:"var(--foreground)",16:"var(--muted-foreground)",17:"var(--tools-title)",18:"var(--tools-description)",19:"var(--markdown-heading1, var(--primary))",20:"var(--markdown-link, var(--primary))",21:"var(--muted-foreground)",22:"var(--markdown-inline-code, var(--syntax-string, var(--status-success)))",23:"var(--syntax-foreground, var(--foreground))",24:"var(--tools-border, var(--border))",25:"var(--markdown-blockquote, var(--muted-foreground))",26:"var(--markdown-blockquote-border, var(--border))",27:"var(--markdown-hr, var(--border))",28:"var(--markdown-list-marker, var(--primary))",29:"var(--tools-edit-added, var(--status-success))",30:"var(--tools-edit-removed, var(--status-error))",31:"var(--muted-foreground)",32:"var(--syntax-comment, var(--muted-foreground))",33:"var(--syntax-keyword, var(--primary))",34:"var(--syntax-function, var(--primary))",35:"var(--syntax-variable, var(--foreground))",36:"var(--syntax-string, var(--status-success))",37:"var(--syntax-number, var(--status-warning))",38:"var(--syntax-type, var(--status-info))",39:"var(--syntax-operator, var(--foreground))",40:"var(--syntax-punctuation, var(--muted-foreground))",41:"var(--muted-foreground)",42:"var(--muted-foreground)",43:"var(--muted-foreground)",44:"var(--muted-foreground)",45:"var(--muted-foreground)",46:"var(--muted-foreground)",47:"var(--muted-foreground)",48:"var(--primary)"}),Rv=Object.freeze({0:"var(--interactive-selection)",1:"var(--interactive-selection)",2:"var(--surface-elevated, var(--card))",3:"var(--surface-muted)",4:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",5:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",6:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))"}),Yp=Object.freeze({30:"var(--muted-foreground)",31:"var(--status-error)",32:"var(--status-success)",33:"var(--status-warning)",34:"var(--status-info)",35:"var(--primary)",36:"var(--status-info)",37:"var(--foreground)",90:"var(--muted-foreground)",91:"var(--status-error)",92:"var(--status-success)",93:"var(--status-warning)",94:"var(--status-info)",95:"var(--primary)",96:"var(--status-info)",97:"var(--foreground)"}),Pv=Object.freeze({40:"var(--muted)",41:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",42:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",43:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",44:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",45:"var(--surface-elevated)",46:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",47:"var(--surface-elevated)",100:"var(--muted)",101:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",102:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",103:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",104:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",105:"var(--surface-elevated)",106:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",107:"var(--surface-elevated)"});function Dv(e){if(e<0||e>255)return"var(--foreground)";if(e<16)return Yp[e<8?e+30:e-8+90]??"var(--foreground)";if(e>=232){const i=8+(e-232)*10;return`rgb(${i}, ${i}, ${i})`}const t=e-16,n=t%6,r=Math.floor(t/6)%6,s=Math.floor(t/36),o=[0,95,135,175,215,255];return`rgb(${o[s]}, ${o[r]}, ${o[n]})`}const DV=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;function $4(e){if(e)try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}function Nn(e){return e.replace(DV,"")}function z4(e){return e.includes("\x1B")}function U4(e){if(!e)return[];if(!z4(e))return[{text:e}];const t=[],n={bold:!1,dim:!1,italic:!1,underline:!1,strikethrough:!1,inverse:!1},r=/\u001b(?:\[([0-?]*)[ -/]*([@-~])|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;let s=0,o;const i=a=>{if(!a)return;if(t.length>0){const d=t[t.length-1];if((d.fg??void 0)===n.fg&&(d.bg??void 0)===n.bg&&!!d.bold===n.bold&&!!d.dim===n.dim&&!!d.italic===n.italic&&!!d.underline===n.underline&&!!d.strikethrough===n.strikethrough&&!!d.inverse===n.inverse&&d.href===n.href){d.text+=a;return}}const l={text:a};n.fg&&(l.fg=n.fg),n.bg&&(l.bg=n.bg),n.bold&&(l.bold=!0),n.dim&&(l.dim=!0),n.italic&&(l.italic=!0),n.underline&&(l.underline=!0),n.strikethrough&&(l.strikethrough=!0),n.inverse&&(l.inverse=!0),n.href&&(l.href=n.href),t.push(l)};for(;(o=r.exec(e))!==null;){o.index>s&&i(e.slice(s,o.index)),s=r.lastIndex;const a=o[1],l=o[2];if(o[0].startsWith("\x1B]8;")){const d=o[0].slice(4).replace(/(?:\u0007|\u001b\\)$/,""),f=d.slice(d.indexOf(";")+1);n.href=f||void 0;continue}if(l==="m"&&(!a||/^[0-9;]*$/.test(a))){const d=(a||"0").split(";").map(u=>u===""?0:parseInt(u,10));let f=0;for(;f<d.length;){const u=d[f];if(Number.isNaN(u)||u===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.strikethrough=!1,n.inverse=!1,f+=1;else if(u===1)n.bold=!0,f+=1;else if(u===2)n.dim=!0,f+=1;else if(u===3)n.italic=!0,f+=1;else if(u===4)n.underline=!0,f+=1;else if(u===7)n.inverse=!0,f+=1;else if(u===9)n.strikethrough=!0,f+=1;else if(u===22)n.bold=!1,n.dim=!1,f+=1;else if(u===23)n.italic=!1,f+=1;else if(u===24)n.underline=!1,f+=1;else if(u===27)n.inverse=!1,f+=1;else if(u===29)n.strikethrough=!1,f+=1;else if(u>=30&&u<=37)n.fg=Yp[u],f+=1;else if(u===39)n.fg=void 0,f+=1;else if(u>=40&&u<=47)n.bg=Pv[u],f+=1;else if(u===49)n.bg=void 0,f+=1;else if(u>=90&&u<=97)n.fg=Yp[u],f+=1;else if(u>=100&&u<=107)n.bg=Pv[u],f+=1;else if(u===38){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.fg=Dv(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in Lv?n.fg=Lv[x]:n.fg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else if(u===48){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.bg=Dv(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in Rv?n.bg=Rv[x]:n.bg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else f+=1}}}return s<e.length&&i(e.slice(s)),t}const Nd=e=>{const t={};let n=!1,r=e.fg,s=e.bg;if(e.inverse){const o=r;r=s??"var(--surface-background, var(--background))",s=o??"var(--foreground)",n=!0}return r&&(t.color=r,n=!0),s&&(t.backgroundColor=s,n=!0),e.bold&&(t.fontWeight=600,n=!0),e.dim&&(t.opacity=.65,n=!0),e.italic&&(t.fontStyle="italic",n=!0),e.underline&&e.strikethrough?(t.textDecoration="underline line-through",n=!0):e.underline?(t.textDecoration="underline",n=!0):e.strikethrough&&(t.textDecoration="line-through",n=!0),n?t:void 0},q4=e=>e.mode==="overlay"&&!e.hidden&&e.frame?.visible!==!1&&!!e.frame?.layout,OV=/[\u2500-\u259f]/g,Ov=(e,t)=>{for(const n of e.frame?.lines??[]){const r=Nn(n).replace(OV," ").trim().split(/\s+/)[0]??"";if(/[\p{L}\p{N}]/u.test(r))return r.length>16?`${r.slice(0,15)}…`:r}return`Panel ${t+1}`},HV=(e,t)=>{const n=new Map;for(const o of e){if(!o.parentId)continue;const i=n.get(o.parentId)??[];i.push(o),n.set(o.parentId,i)}const r=new Map(t.map((o,i)=>[o,i])),s=[];for(const[o,i]of n){const a=[...i].sort((d,f)=>f.z-d.z),l=i.find(d=>d.focused)??a.find(d=>d.capturing)??a[0];i.sort((d,f)=>(r.get(d.surfaceId)??0)-(r.get(f.surfaceId)??0)),s.push({parentId:o,members:i,front:l})}return s},FV=new Map,BV=(e,t)=>{let n=null;const r=new Set(t.map(s=>s.parentId));for(const s of t){if(s.members.length<2||e.has(s.parentId))continue;const o=s.members[0]?.frame?.layout;n??=new Map(e),n.set(s.parentId,{row:o?.row??0,col:o?.col??0})}for(const s of e.keys())r.has(s)||(n??=new Map(e),n.delete(s));return n??e},VV=(e,t,n)=>{if(!(t>0))return e.top<n?"below":"above";const r=Math.max(0,Math.min(e.top,t-e.layoutHeight));return r>=n?"above":r+e.height+n<=t?"below":"inside"},W4=e=>ze(t=>{const n=e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0;if(!n)return!1;for(const r of n.values())if(r.capturing&&q4(r))return!0;return!1},Object.is,e?`session:${e}`:"*",e??"");function $V(e){return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...e,children:[c.jsx("path",{d:"M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z",opacity:"0.2"}),c.jsx("path",{d:"M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z"})]})}const zV=p.memo(function(t){const{isMobile:n,footerIconButtonClass:r,sendIconSizeClass:s,stopIconSizeClass:o,canSend:i,disabledReason:a,canAbort:l,hasContent:d,currentSessionId:f,newSessionDraftOpen:u,isSending:h=!1,isShellMode:m=!1,onPrimaryAction:g,onQueueMessage:x,onAbort:b}=t,S=i&&!!(f||u)&&!h,y=c.jsx("button",{type:n?"button":"submit",disabled:!i||!f&&!u||h,onClick:v=>{n&&(v.preventDefault(),g())},className:R(r,S?"rounded-full bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)]":"opacity-30",m&&!h&&"w-auto gap-1 rounded-full px-2.5 typography-ui-label font-medium",h&&"animate-pulse"),"aria-label":h?"Creating session…":a||(m?"Run command":"Send message"),title:h?"Creating session…":a||(m?"Run command":void 0),children:h?c.jsx($,{name:"loader-4",className:R(s,"animate-spin")}):m?c.jsxs(c.Fragment,{children:[c.jsx($,{name:"play",className:"size-3.5"}),"Run"]}):c.jsx($,{name:"send-plane-2",className:R(s,S&&"size-3.5")})});return l?c.jsxs("div",{className:"relative",children:[d?c.jsx("button",{type:"button",disabled:!f||!i,onClick:v=>{n&&v.preventDefault(),x()},className:R(r,"absolute z-20 bottom-full left-1/2 -translate-x-1/2 mb-1",f&&i?"text-primary hover:text-primary":"opacity-30"),"aria-label":a||"Add follow-up",title:a||void 0,children:c.jsx($,{name:"send-plane-2",className:R(s,"-rotate-90")})}):null,c.jsx("button",{type:"button",onClick:b,className:R(r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:c.jsx($V,{className:R(o)})})]}):y},(e,t)=>e.isMobile===t.isMobile&&e.footerIconButtonClass===t.footerIconButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.disabledReason===t.disabledReason&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.isSending===t.isSending&&e.isShellMode===t.isShellMode&&e.onPrimaryAction===t.onPrimaryAction&&e.onQueueMessage===t.onQueueMessage&&e.onAbort===t.onAbort),UV=p.memo(function(t){const{footerIconButtonClass:n,iconSizeClass:r,handlePickLocalFiles:s,onOpenSettings:o,isAttachmentDisabled:i,disabled:a=!1,onLinkGitHub:l}=t;return c.jsxs("div",{className:"flex items-center gap-x-1.5",children:[c.jsx("div",{className:"relative inline-flex",children:t.onOpenMobileSheet?c.jsx("button",{type:"button",className:n,onClick:t.onOpenMobileSheet,disabled:i,onMouseDown:d=>d.preventDefault(),onPointerDownCapture:d=>{d.pointerType==="touch"&&d.preventDefault()},title:"Add attachment","aria-label":"Add attachment",children:c.jsx($,{name:"add-circle",className:R(r,"text-current")})}):c.jsxs(Fa,{onOpenChange:t.onMenuOpenChange,children:[c.jsx(Ba,{asChild:!0,children:c.jsx("button",{type:"button",className:n,title:"Add attachment","aria-label":"Add attachment",disabled:i,children:c.jsx($,{name:"add-circle",className:R(r,"text-current")})})}),c.jsxs(Va,{align:"start",children:[c.jsxs(ur,{onSelect:()=>{requestAnimationFrame(s)},children:[c.jsx($,{name:"attachment-2"}),"Attach files"]}),l?c.jsxs(ur,{onSelect:()=>{requestAnimationFrame(l)},children:[c.jsx($,{name:"github"}),"Link issue / pull request"]}):null]})]})}),o?c.jsx("button",{type:"button",onClick:o,className:n,title:"Model and agent settings","aria-label":"Model and agent settings",disabled:a,children:c.jsx($,{name:"ai-agent",className:R(r,"text-current")})}):null]})},(e,t)=>e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.handlePickLocalFiles===t.handlePickLocalFiles&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.isAttachmentDisabled===t.isAttachmentDisabled&&e.disabled===t.disabled&&e.onLinkGitHub===t.onLinkGitHub);function qV(e){const{isMobile:t,isInline:n,alignToolsEnd:r,sessionId:s,newSessionDraftOpen:o,children:i,leadingExtra:a,trailingExtra:l,actionsOverride:d,footerPaddingClass:f,footerGapClass:u,footerIconButtonClass:h,iconSizeClass:m,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C=!1,isShellMode:w=!1,isAttachmentDisabled:I,onOpenSettings:E,onPickLocalFiles:T,onLinkGitHub:A,onPrimaryAction:j,onQueueMessage:k,onAbort:_}=e,M=c.jsx(UV,{footerIconButtonClass:h,iconSizeClass:m,handlePickLocalFiles:T,onLinkGitHub:A,onOpenSettings:E,onOpenMobileSheet:t?T:void 0,disabled:C,isAttachmentDisabled:I}),L=d??c.jsx(zV,{isMobile:t,footerIconButtonClass:h,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C,isShellMode:w,currentSessionId:s,newSessionDraftOpen:o,onPrimaryAction:j,onQueueMessage:k,onAbort:_});if(t)return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsx("div",{className:R("flex-shrink-0",f,"flex items-center gap-x-1.5"),"data-chat-input-footer":"true",children:c.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[c.jsxs("div",{className:"composer-mobile-actions flex min-w-0 items-center gap-x-2 overflow-x-auto pl-1","data-no-drawer-swipe":"true",children:[M,a?c.jsx("div",{className:R("w-max shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:"flex min-w-0 shrink-0 items-center justify-end gap-x-1",children:[l,L]})]})})]});if(n){const O=r?"self-end":"self-center";return c.jsxs("div",{className:R("grid grid-cols-[auto_minmax(0,1fr)_auto] bg-transparent",f,u),"data-chat-input-footer":"true",children:[c.jsx("div",{className:R("flex min-w-0 items-center",u,O),children:M}),c.jsx("div",{className:"min-w-0",children:i}),c.jsxs("div",{className:R("flex min-w-0 items-center justify-end",u,O),children:[l,L]})]})}return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center justify-between",f,u),"data-chat-input-footer":"true",children:[c.jsxs("div",{className:R("flex min-w-0 items-center",u),children:[M,a?c.jsx("div",{className:R("w-max min-w-0 shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center",u),children:[l,L]})]})]})}const K4=p.memo(({sessionId:e})=>{const t=he(y=>y.restoreToMessage),n=he(y=>y.forkFromMessage),r=he(y=>y.handleSlashRedo),[s,o]=p.useState(null),[i,a]=p.useState(null),[l,d]=p.useState(!0),f=YI(e),u=f?.targetEntryId,h=p.useMemo(()=>f?f.abandoned.filter(y=>y.role==="user"):[],[f]),m="No text content",g=p.useMemo(()=>!f||h.length===0?[]:h.map(y=>({id:y.id,text:y.preview?.replace(/\s+/g," ").trim()||m})),[h,f,m]),x=g[0]?.id;p.useEffect(()=>{d(!0)},[u,x]);const b=p.useCallback(async y=>{if(!(!e||s)){o(y);try{const v=h.findIndex(w=>w.id===y),C=v>=0?h[v+1]:void 0;C?(await t(e,C.id),Ce.success("Restored messages through this point")):await r(e)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to restore messages")}finally{o(null)}}},[h,r,t,s,e]),S=p.useCallback(async y=>{if(!(!e||i)){a(y);try{await n(e,y)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to fork session")}finally{a(null)}}},[n,i,e]);return!e||g.length===0?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[c.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--interactive-hover)] transition-colors",onClick:()=>d(y=>!y),"aria-expanded":!l,children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Reverted"," messages ",g.length]}),c.jsx($,{name:"arrow-down-s",className:R("ml-auto h-4 w-4 text-muted-foreground transition-transform",!l&&"rotate-180"),"aria-hidden":"true"})]}),!l&&c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:g.map(y=>c.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-1",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:y.text}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{S(y.id)},children:[i===y.id?c.jsx($,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx($,{name:"git-branch",className:"h-3 w-3","aria-hidden":"true"}),"Fork"]}),c.jsxs(be,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{b(y.id)},children:[s===y.id?c.jsx($,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx($,{name:"arrow-go-forward",className:"h-3 w-3","aria-hidden":"true"}),"Restore"]})]},y.id))})]})})});K4.displayName="RevertedMessageDock";const WV=({isInternalDrag:e,iconButtonBaseClass:t,iconSizeClass:n,radius:r,isAttachmentDisabled:s,onPickLocalFiles:o})=>c.jsx("div",{className:"absolute -inset-px z-50 flex items-center justify-center border border-border/80 bg-[var(--surface-subtle)]/90",style:{borderRadius:r},children:c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:"inline-flex justify-center",children:c.jsx("button",{type:"button",className:t,onClick:o,disabled:s,title:"Attach files","aria-label":"Attach files",children:c.jsx($,{name:"attachment-2",className:R(n,"text-current")})})}),c.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:e?"Drop to insert as mention":"Drop files here to attach"})]})}),KV={type:"file",multiple:!0,accept:JM};function GV({inputRef:e,onChange:t}){return c.jsx("input",{ref:e,...KV,className:"hidden",onChange:t})}function ZV({available:e,disabled:t,className:n,iconClassName:r,onStart:s}){return e?c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:n,disabled:t,onClick:s,title:"Start dictation","aria-label":"Start dictation",children:c.jsx($,{name:"mic",className:R("size-4",r)})}):null}const YV=48,Ld=2,XV=1,Hv=Ld+XV,yh=.08,Ho=512,JV=2,QV=(e,t)=>{e.values[e.cursor]=t,e.cursor=(e.cursor+1)%Ho,e.count=Math.min(Ho,e.count+1)},e$=(e,t)=>{const n=Math.min(e.count,t),r=(e.cursor-n+Ho)%Ho;return Array.from({length:n},(s,o)=>e.values[(r+o)%Ho])},Fv=(e,t,n,r,s)=>{const o=Math.max(1,Math.round(Ld*n.pixelRatio)),i=Math.max(1,n.height-Math.round(8*n.pixelRatio)),a=Math.max(Math.round(2*n.pixelRatio),Math.round(i*r)),l=Math.round((n.height-a)/2);e.globalAlpha=.35+r*.65,e.fillStyle=s,e.beginPath(),e.roundRect(t,l,o,a,o/2),e.fill(),e.globalAlpha=1};function t$({subscribeLevel:e}){const t=p.useRef(null),n=p.useRef(null),r=p.useRef(null),s=p.useRef(0),o=p.useRef(""),i=p.useRef({width:0,height:0,pixelRatio:1}),a=p.useRef({values:Array.from({length:Ho},()=>yh),cursor:0,count:0}),l=p.useCallback(()=>{const d=n.current,f=i.current;if(!d||f.width<=0||f.height<=0||!o.current)return;d.clearRect(0,0,f.width,f.height);const u=Math.max(1,Math.round(Hv*f.pixelRatio)),h=Math.ceil(f.width/u),m=e$(a.current,h),g=h-m.length;for(let x=0;x<h;x+=1){const b=x>=g?m[x-g]:yh,S=f.width-Math.round(Ld*f.pixelRatio)-(h-1-x)*u;Fv(d,S,f,b,o.current)}},[]);return p.useEffect(()=>{const d=t.current;if(!d)return;const f=d.getContext("2d",{alpha:!0});if(!f)return;n.current=f;const u=g=>{const x=Math.min(JV,Math.max(1,window.devicePixelRatio||1)),b={width:Math.max(1,Math.round(g*x)),height:Math.round(YV*x),pixelRatio:x},S=i.current;S.width===b.width&&S.height===b.height&&S.pixelRatio===b.pixelRatio||(i.current=b,d.width=b.width,d.height=b.height,o.current=getComputedStyle(d).color,l())},h=new ResizeObserver(g=>{const x=g[0]?.contentRect.width;typeof x=="number"&&x>0&&u(x)});h.observe(d);const m=new MutationObserver(()=>{o.current=getComputedStyle(d).color,l()});return m.observe(document.documentElement,{attributes:!0,attributeFilter:["class","style"]}),()=>{h.disconnect(),m.disconnect(),n.current=null}},[l]),p.useEffect(()=>{const d=()=>{r.current=null;const u=t.current,h=n.current,m=i.current;if(!u||!h||m.width<=0||!o.current)return;const g=Math.max(yh,s.current),x=Math.max(1,Math.round(Hv*m.pixelRatio));m.width>x&&(h.globalCompositeOperation="copy",h.drawImage(u,x,0,m.width-x,m.height,0,0,m.width-x,m.height),h.globalCompositeOperation="source-over"),h.clearRect(Math.max(0,m.width-x),0,x,m.height),Fv(h,m.width-Math.round(Ld*m.pixelRatio),m,g,o.current),QV(a.current,g)},f=e(u=>{s.current=u,r.current===null&&(r.current=requestAnimationFrame(d))});return()=>{f(),r.current!==null&&cancelAnimationFrame(r.current)}},[e]),c.jsx("canvas",{ref:t,className:"h-12 w-full text-primary","aria-hidden":"true"})}const n$=e=>`${Math.floor(e/60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`;function r$({state:e,elapsedSeconds:t,buttonClassName:n,iconClassName:r,isMobile:s,onCancel:o,onDone:i}){const a=e==="recording"||e==="reconnecting";return c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?null:c.jsxs("div",{className:"mr-1 flex items-center gap-2 typography-ui-compact text-muted-foreground",children:[a?c.jsx("span",{className:"size-2 rounded-full bg-[var(--status-error)]","aria-hidden":"true"}):null,c.jsx("span",{className:"tabular-nums",children:n$(t)})]}),c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:n,onClick:o,title:"Cancel dictation","aria-label":"Cancel dictation",children:c.jsx($,{name:"close",className:R("size-4",r)})}),c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:R(n,"text-primary hover:text-primary"),onClick:i,disabled:!a,title:"Finish dictation","aria-label":"Finish dictation",children:c.jsx($,{name:"check",className:R("size-4",r)})})]})}function s$({state:e,subscribeLevel:t}){const n=e==="recording"||e==="reconnecting",r=e==="requesting-permission"?"Requesting microphone access...":e==="reconnecting"?"Recording. Reconnecting to the server...":e==="transcribing"?"Transcribing...":"Recording";return c.jsx("div",{className:"flex h-[7rem] w-full items-center px-3 py-3",role:"group","aria-label":"Dictation recorder",children:c.jsxs("div",{className:"min-w-0 flex-1",children:[n?c.jsx(t$,{subscribeLevel:t}):c.jsx("div",{className:"flex h-12 items-center justify-center typography-ui-label text-muted-foreground",children:r}),c.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:r})]})})}const o$=3e4;let Xp=null,Wi=null;const fQ=()=>{Xp=null,Wi=null},i$=async e=>{const t=Y();if(!e?.fresh){const r=Xp;if(r&&r.key===t&&Date.now()<r.expiresAt)return r.status;const s=Wi;if(s&&s.key===t)return s.promise}const n=(async()=>{const r=await Rt("/api/stt/status");if(!r.ok)throw new Error("Could not load dictation settings");const s=await r.json();return!e?.fresh&&Y()===t&&(Xp={key:t,status:s,expiresAt:Date.now()+o$}),s})();e?.fresh||(Wi={key:t,promise:n});try{return await n}finally{Wi?.promise===n&&(Wi=null)}},a$=`
100
- class PiChamberDictationProcessor extends AudioWorkletProcessor {
101
- constructor() {
102
- super();
103
- this.outputRate = 16000;
104
- this.step = sampleRate / this.outputRate;
105
- this.position = 0;
106
- this.source = [];
107
- this.pending = [];
108
- this.chunkSamples = 4000;
109
- this.port.onmessage = (event) => {
110
- if (event.data && event.data.type === 'flush') {
111
- if (this.pending.length > 0) {
112
- const samples = Int16Array.from(this.pending.splice(0));
113
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
114
- }
115
- this.port.postMessage({ type: 'flushed' });
116
- }
117
- };
118
- }
119
- process(inputs) {
120
- const input = inputs[0] && inputs[0][0];
121
- if (!input || input.length === 0) return true;
122
- let sum = 0;
123
- for (let i = 0; i < input.length; i += 1) { this.source.push(input[i]); sum += input[i] * input[i]; }
124
- this.port.postMessage({ type: 'level', value: Math.min(1, Math.sqrt(sum / input.length) * 3) });
125
- while (this.position + 1 < this.source.length) {
126
- const index = Math.floor(this.position);
127
- const fraction = this.position - index;
128
- const sample = this.source[index] + (this.source[index + 1] - this.source[index]) * fraction;
129
- const clamped = Math.max(-1, Math.min(1, sample));
130
- this.pending.push(clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767));
131
- this.position += this.step;
132
- }
133
- const consumed = Math.floor(this.position);
134
- if (consumed > 0) { this.source.splice(0, consumed); this.position -= consumed; }
135
- while (this.pending.length >= this.chunkSamples) {
136
- const samples = Int16Array.from(this.pending.splice(0, this.chunkSamples));
137
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
138
- }
139
- return true;
140
- }
141
- }
142
- registerProcessor('pichamber-dictation', PiChamberDictationProcessor);
143
- `,c$=16e3,Bv=4e3,G4=()=>typeof window>"u"?null:window.AudioContext??window.webkitAudioContext??null,vh=e=>{try{e?.disconnect()}catch{}};class l${constructor(t){this.options=t}options;stream=null;context=null;source=null;processor=null;gain=null;listeners=new Set;pendingFallback=[];fallbackPosition=0;fallbackCarry=[];flushed=null;cancelled=!1;subscribeLevel(t){return this.listeners.add(t),()=>this.listeners.delete(t)}level(t){for(const n of this.listeners)n(t)}chunk(t){t.length&&this.options.onChunk(new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice())}async start(){if(this.stream)return;const t=G4();if(!t||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone recording is not supported");const n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});if(this.cancelled)throw n.getTracks().forEach(o=>o.stop()),new Error("Dictation cancelled");this.stream=n,this.options.onPermissionGranted?.();const r=new t;this.context=r,r.state==="suspended"&&await r.resume(),this.source=r.createMediaStreamSource(n),this.gain=r.createGain(),this.gain.gain.value=0;let s=null;if(r.audioWorklet&&typeof AudioWorkletNode<"u"){const o=URL.createObjectURL(new Blob([a$],{type:"text/javascript"}));try{await r.audioWorklet.addModule(o),s=new AudioWorkletNode(r,"pichamber-dictation",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]})}catch{s=null}finally{URL.revokeObjectURL(o)}}if(s)s.port.onmessage=o=>{o.data.type==="level"?this.level(o.data.value??0):o.data.type==="chunk"&&o.data.buffer?this.chunk(new Int16Array(o.data.buffer)):o.data.type==="flushed"&&(this.flushed?.(),this.flushed=null)},this.processor=s;else{const o=r.createScriptProcessor(4096,1,1);o.onaudioprocess=i=>this.processFallback(i.inputBuffer.getChannelData(0),r.sampleRate),this.processor=o}this.source.connect(this.processor),this.processor.connect(this.gain),this.gain.connect(r.destination)}processFallback(t,n){let r=0;for(const a of t)r+=a*a;this.level(Math.min(1,Math.sqrt(r/Math.max(1,t.length))*3));const s=this.fallbackCarry.concat(Array.from(t)),o=n/c$;for(;this.fallbackPosition+1<s.length;){const a=Math.floor(this.fallbackPosition),l=this.fallbackPosition-a,d=s[a]+(s[a+1]-s[a])*l,f=Math.max(-1,Math.min(1,d));this.pendingFallback.push(f<0?Math.round(f*32768):Math.round(f*32767)),this.fallbackPosition+=o}const i=Math.floor(this.fallbackPosition);for(this.fallbackCarry=s.slice(i),this.fallbackPosition-=i;this.pendingFallback.length>=Bv;)this.chunk(Int16Array.from(this.pendingFallback.splice(0,Bv)))}async stop(){this.cancelled=!0;const t=this.processor;typeof AudioWorkletNode<"u"&&t instanceof AudioWorkletNode?await Promise.race([new Promise(n=>{this.flushed=n,t.port.postMessage({type:"flush"})}),new Promise(n=>window.setTimeout(n,100))]):this.pendingFallback.length&&this.chunk(Int16Array.from(this.pendingFallback.splice(0))),typeof ScriptProcessorNode<"u"&&t instanceof ScriptProcessorNode&&(t.onaudioprocess=null),vh(this.source),vh(t),vh(this.gain),this.stream?.getTracks().forEach(n=>n.stop()),await this.context?.close().catch(()=>{}),this.level(0),this.stream=null,this.context=null,this.source=null,this.processor=null,this.gain=null,this.pendingFallback=[],this.fallbackCarry=[],this.fallbackPosition=0,this.flushed=null}}const d$=()=>!!(G4()&&navigator.mediaDevices?.getUserMedia),xh=1,u$=300*16e3*2,Vv=(e,t)=>{const n=new Uint8Array(4+t.byteLength);return new DataView(n.buffer).setUint32(0,e,!0),n.set(t,4),n},f$=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${crypto.getRandomValues(new Uint32Array(4)).join("-")}`;class h${constructor(t,n,r){this.providerConfigId=t,this.onState=n,this.onError=r}providerConfigId;onState;onError;recordingId=f$();socket=null;socketStarted=!1;chunks=[];audioBytes=0;finishing=!1;cancelled=!1;failures=0;generation=0;reconnectTimer=null;finishPromise=null;resolveFinish=null;rejectFinish=null;begin(){this.connect()}append(t){if(this.cancelled||this.finishing||!t.byteLength)return;if(this.audioBytes+t.byteLength>u$){this.fail(new Error("Recording reached the five minute limit"));return}const n=t.slice(),r=this.chunks.length;this.chunks.push(n),this.audioBytes+=n.byteLength,this.socketStarted&&this.socket?.readyState===xh&&this.socket.send(Vv(r,n))}finish(){return this.finishPromise?this.finishPromise:(this.finishing=!0,this.onState("transcribing"),this.finishPromise=new Promise((t,n)=>{this.resolveFinish=t,this.rejectFinish=n}),this.socketStarted?this.sendFinish():this.connect(),this.finishPromise)}cancel(){this.cancelled||(this.cancelled=!0,this.generation+=1,this.socket?.readyState===xh&&this.socketStarted&&this.socket.send(JSON.stringify({version:1,type:"cancel",recordingId:this.recordingId})),this.closeSocket(),this.clearAudio(),this.rejectFinish?.(new Error("Dictation cancelled")),this.rejectFinish=null,this.resolveFinish=null)}async connect(){if(this.cancelled||this.socket||this.reconnectTimer)return;const t=++this.generation;this.failures>0&&this.onState(this.finishing?"transcribing":"reconnecting");try{const n=await bC();if(this.cancelled||t!==this.generation)return;const r=wC(SC().websocket("/api/stt/ws",void 0,n));r.binaryType="arraybuffer",this.socket=r;let s=!1;r.onopen=()=>{s=!0,!(this.socket!==r||this.cancelled)&&r.send(JSON.stringify({version:1,type:"start",recordingId:this.recordingId,providerConfigId:this.providerConfigId}))},r.onmessage=o=>{if(typeof o.data!="string"||this.socket!==r)return;let i;try{i=JSON.parse(o.data)}catch{return}if(!(i.recordingId&&i.recordingId!==this.recordingId))if(i.type==="started"){this.failures=0,this.socketStarted=!0;const a=Number.isInteger(i.ackSequence)?i.ackSequence:-1;for(let l=a+1;l<this.chunks.length;l+=1)r.send(Vv(l,this.chunks[l]));this.finishing?this.sendFinish():this.onState("recording")}else if(i.type==="transcribing")this.onState("transcribing");else if(i.type==="final"){const a=String(i.text??"").trim();this.resolveFinish?.(a),this.resolveFinish=null,this.rejectFinish=null,this.clearAudio(),this.cancelled=!0,this.closeSocket()}else i.type==="error"&&this.fail(Object.assign(new Error(i.message||"Transcription failed"),{code:i.code}))},r.onerror=()=>{},r.onclose=()=>{this.socket===r&&(this.socket=null,this.socketStarted=!1,s||CC(n),this.cancelled||this.scheduleReconnect())}}catch(n){!this.cancelled&&t===this.generation&&(this.socket=null,this.scheduleReconnect(n instanceof Error?n:new Error(String(n))))}}sendFinish(){!this.socketStarted||this.socket?.readyState!==xh||this.socket.send(JSON.stringify({version:1,type:"finish",recordingId:this.recordingId,finalSequence:this.chunks.length-1}))}scheduleReconnect(t){this.failures+=1,this.onState(this.finishing?"transcribing":"reconnecting");const r=typeof document<"u"&&(document.visibilityState==="hidden"||navigator.onLine===!1)?3e4:Math.min(1e4,300*2**Math.min(this.failures,5));if(this.failures>=8){this.fail(t??new Error("Could not reconnect to the transcription server"));return}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},r)}fail(t){this.cancelled||(this.cancelled=!0,this.onError(t),this.rejectFinish?.(t),this.resolveFinish=null,this.rejectFinish=null,this.closeSocket(),this.clearAudio())}closeSocket(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;if(this.socket=null,this.socketStarted=!1,t){t.onclose=null,t.onmessage=null;try{t.close()}catch{}}}clearAudio(){this.chunks=[],this.audioBytes=0}}function p$(){const[e,t]=p.useState("idle"),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(0),l=p.useRef(null),d=p.useRef(null),f=p.useRef("local"),u=p.useRef(0),h=p.useRef(0),m=p.useCallback(async()=>{const v=await i$();f.current=v.config?.providerConfigId||"local",o(v.config?.enabled===!0&&d$())},[]);p.useEffect(()=>(m().catch(()=>{}),Zt(()=>{h.current+=1,d.current?.cancel(),l.current?.stop(),d.current=null,l.current=null,t("idle"),r(null),o(!1),m().catch(()=>{})})),[m]),p.useEffect(()=>{if(!u.current||e!=="recording"&&e!=="reconnecting")return;const v=()=>a(Math.min(300,Math.floor((Date.now()-u.current)/1e3)));v();const C=window.setInterval(v,250);return()=>window.clearInterval(C)},[e]);const g=p.useCallback(v=>{r(v.message),t("error"),l.current?.stop(),l.current=null},[]),x=p.useCallback(async()=>{if(!s||e==="requesting-permission"||e==="recording"||e==="reconnecting"||e==="transcribing")return;r(null),a(0),t("requesting-permission");const v=++h.current,C=new h$(f.current,I=>{h.current===v&&t(I)},I=>{h.current===v&&g(I)}),w=new l$({onChunk:I=>C.append(I),onPermissionGranted:()=>{h.current===v&&(u.current=Date.now(),t("recording"))}});d.current=C,l.current=w;try{await w.start(),C.begin()}catch(I){if(C.cancel(),await w.stop().catch(()=>{}),h.current!==v)return;d.current=null,l.current=null,u.current=0;const E=I instanceof Error?I:new Error(String(I));throw r(E.name==="NotAllowedError"?"Microphone access was denied":E.message),t("error"),E}},[s,e,g]),b=p.useCallback(async()=>{const v=d.current,C=l.current;if(!v||!C)throw new Error("No dictation recording is active");const w=h.current;t("transcribing");try{if(await C.stop(),h.current!==w||d.current!==v)throw new Error("Dictation cancelled");l.current=null;const I=await v.finish();if(h.current!==w)throw new Error("Dictation cancelled");return d.current=null,u.current=0,t("idle"),r(null),I}catch(I){const E=I instanceof Error?I:new Error(String(I));throw h.current===w&&(r(E.message),t("error")),E}},[]),S=p.useCallback(()=>{h.current+=1,d.current?.cancel(),d.current=null,l.current?.stop(),l.current=null,u.current=0,a(0),r(null),t("idle")},[]);p.useEffect(()=>S,[S]);const y=p.useCallback(v=>l.current?.subscribeLevel(v)??(()=>{}),[]);return{state:e,error:n,available:s,elapsedSeconds:i,start:x,finish:b,cancel:S,subscribeLevel:y}}const m$=Fs(()=>mt(()=>import("./GitHubLinkPicker-BVYdg_e8.js"),__vite__mapDeps([58,5,1,6,59,17,11,8,18,19,20,60,23,61,43,42])).then(e=>({default:e.GitHubLinkPicker}))),g$=Fs(()=>mt(()=>import("./ToolOutputDialog-DdMIfrnK.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),y$=5,v$=16,x$=4,b$=560,$v=p.memo(QD),w$=p.memo(J3),S$=e=>{const t=he.getState(),n=t.newSessionDraft?.open?t.newSessionDraft.directoryOverride:null,r=e?t.getDirectoryForSession(e)??t.currentSessionDirectory:n??nt.getState().currentDirectory;return Jo(Y(),r,e)},Z4=({onOpenSettings:e,scrollToBottom:t})=>{const n=p.useRef(null),r=p.useRef(null),s=p.useRef({text:"",confirmedMentions:new Set}),[o,i]=p.useState(()=>{const V=he.getState().currentSessionId,ae=S$(V),Te=ru(ae);return r.current=ae,s.current=Te,Te.text&&(n.current=Te.text),Te.text}),a=p.useRef(s.current.confirmedMentions),[l,d]=p.useState("normal"),[f,u]=p.useState(!1);p.useEffect(()=>{l==="normal"&&u(!1)},[l]);const[h,m]=p.useState(null),[g,x]=p.useState(""),[b,S]=p.useState(null),y=p.useCallback(()=>m(null),[]);p.useEffect(()=>{h!=="command"&&S(V=>V===null?V:null)},[h]);const v=h==="command"?b?.listboxId:void 0,C=!!v,[w,I]=p.useState(null),[E,T]=p.useState(null),[A,j]=p.useState(""),k=p.useRef(null),_=p.useRef(cB()).current;p.useEffect(()=>()=>{_.view?.destroy(),_.view=null},[_]);const M=p.useRef(null),L=p.useRef(0),O=p.useRef(null),N=p.useRef(!1),D=p.useRef(null),W=p.useRef(!1),z=p.useRef(null),X=p.useRef(null),F=p.useRef(null),U=p.useRef(o),P=p.useRef(r.current),q=p.useRef((...V)=>Promise.resolve(he.getState().sendMessage(...V))).current,B=he(V=>V.currentSessionId),ee=W4(B);p.useEffect(()=>{ee&&y()},[ee,y]);const K=ze(V=>B?V.sessionLoadErrorById.get(B)?.code??null:null,void 0,B?`session:${B}`:"chrome")==="SESSION_IN_USE",se=ze(V=>{if(!B)return;const ae=V.reducer.bySession.get(B);if(!ae)return;const Te=ae.extensionEditorOps??(ae.extensionEditor?[ae.extensionEditor]:void 0);if(!(!Te||Te.length===0))return{sessionId:B,ops:Te}},(V,ae)=>V===ae?!0:!V||!ae||V.sessionId!==ae.sessionId||V.ops.length!==ae.ops.length?!1:V.ops.every((Te,Ve)=>Te.sequence===ae.ops[Ve]?.sequence&&Te.text===ae.ops[Ve]?.text&&Te.mode===ae.ops[Ve]?.mode),B?`session:${B}`:"chrome"),le=p.useRef(new Map);p.useEffect(()=>{if(!B||!se||se.sessionId!==B)return;const{ops:V}=se;if(!V||V.length===0)return;const ae=le.current.get(B)??-1,Te=V.filter(Le=>Le.sequence>ae);if(Te.length===0)return;let Ve=ae;for(const Le of Te)Le.sequence>Ve&&(Ve=Le.sequence);let $e=-1;for(let Le=Te.length-1;Le>=0;Le--)if(Te[Le]?.mode!=="paste"){$e=Le;break}if($e!==-1){const Le=Te[$e],Je=Te.slice($e+1).map(hn=>hn.text).join(""),gt=Le.text+Je;a.current.clear(),i(gt),y()}else for(const Le of Te){const Je=k.current;Je?(Je.insertText(Le.text),Je.focus({preventScroll:!0})):i(gt=>gt+Le.text)}le.current.set(B,Ve),qe().consumeExtensionEditor(B,Ve)},[y,B,se]);const oe=nt(V=>V.currentDirectory),ue=Xn()??oe,ye=he(p.useCallback(V=>B?V.getDirectoryForSession(B):null,[B])),we=Y();OP({sessionId:B,directory:ye??ue,text:o}),p.useEffect(()=>(id(),Hr.getState().loadSkills(),Zt(()=>{id(),Hr.getState().loadSkills()})),[ue]);const Me=p.useMemo(()=>Jo(we,ye??ue,B),[we,ue,ye,B]),He=he(V=>V.newSessionDraft),Ae=!!He?.open,Ge=he(V=>V.sendingNewSessionDraftId),et=Nw(He,B,Ge);he(V=>V.openNewSessionDraft);const Xe=he(V=>V.abortPromptSessionId),te=he(V=>V.clearAbortPrompt),Q=Ye(V=>V.attachedFiles),me=Ye(V=>V.addAttachedFile),Se=Ye(V=>V.detachAttachedFiles),_e=Ye(V=>V.consumePendingInputText),Fe=Ye(V=>V.pendingStarterInsert),ht=Ye(V=>V.pendingInputText),ge=Ye(V=>V.pendingRevertText),Ze=Ye(V=>V.consumePendingRevertText),Be=Ye(V=>V.consumePendingSyntheticParts),ie=he(V=>V.acknowledgeSessionAbort),ke=p.useCallback(V=>e1(V??B??""),[B]),ve=We(V=>V.currentProviderId),xe=We(V=>V.currentModelId),je=We(V=>V.getModelMetadata);We(V=>V.modelsMetadata),We(V=>V.providers);const ce=ve&&xe?je(ve,xe):void 0,J=We(V=>V.currentVariant),ne=re(V=>V.isMobile),fe=p$(),De=p.useRef({start:0,end:0}),Ue=p.useRef(null),st=fe.state==="requesting-permission"||fe.state==="recording"||fe.state==="reconnecting"||fe.state==="transcribing",Ke=Iu()==="mini-chat",_t=GE(),{enabled:fn}=mu(),Sn=ne&&!fn,Vs=re(V=>V.setImagePreviewOpen),$s=re(V=>V.inputBarOffset),On=re(V=>V.isExpandedInput),Ja=re(V=>V.setExpandedInput),Ot=re(V=>V.setTimelineDialogOpen),{git:en}=qa(),{currentTheme:Xr}=vr(),ti=S4(),ni=ku(ue),xr=vt(V=>ue?V.directories.get(ue)?.status??null:null),Qa=vt(V=>V.ensureStatus),ec=vt(V=>V.fetchStatus),tc=vt(V=>V.clearDiffCache),[Hn,Jr]=p.useState(!1),Fn=p.useRef(async()=>{}),Pt=qB({activeRuntimeKey:we,intent:He?.branchIntent,onReady:V=>{Fn.current(V)}}),br=WB({taskId:He?.id,intent:He?.worktreeIntent}),[Vt,Qr]=p.useState(!1),[ri,es]=p.useState({open:!1,title:"",content:""}),[nc,Lu]=p.useState(!1);p.useEffect(()=>{ri.open&&Lu(!0)},[ri.open]);const zs=p.useRef({modelKey:`${ve??""}/${xe??""}`,modalitySignature:ce?.modalities?.input?.slice().sort().join(",")??null,attachmentIds:new Set});p.useEffect(()=>{const V=`${ve??""}/${xe??""}`,ae=ce?.modalities?.input,Te=ae?.slice().sort().join(",")??null,Ve=zs.current,$e=Ve.modelKey!==V,Le=Ve.modalitySignature===null&&Te!==null,Je=$e||Le?Q:Q.filter(ut=>!Ve.attachmentIds.has(ut.id));if(zs.current={modelKey:V,modalitySignature:Te,attachmentIds:new Set(Q.map(ut=>ut.id))},!ae||Je.length===0)return;const gt=eI(Je,ae);if(gt.length===0)return;const hn=Array.from(new Set(gt.map(({modality:ut})=>ut))),pn={text:"Text",image:"Image",pdf:"PDF",audio:"Audio",video:"Video"},Gs=gt.map(({attachment:ut})=>ut.filename),qu=Gs.length>3?`${Gs.slice(0,3).join(", ")} (+${Gs.length-3})`:Gs.join(", ");Ce.warning(`${ce.name??xe??""} does not support ${hn.map(ut=>pn[ut]).join(", ")} input required by ${qu}. You can still send the message, but these attachments may be ignored.`,{id:`attachment-modalities:${V}`})},[Q,xe,ce,ve]);const Ru=p.useCallback(V=>{V.image&&(es(V),Vs(!0))},[Vs]),Pu=p.useCallback(V=>{es(ae=>({...ae,open:V})),Vs(V)},[Vs]);p.useEffect(()=>{!ue||!en||Qa(ue,en)},[ue,en,Qa]),p.useEffect(()=>{if(!(!ue||!en))return Cu.onGitRefreshHint(V=>{Xt(V.directory)===Xt(ue)&&(V.paths?.length&&tc(ue,V.paths),ec(ue,en,{silent:!0}))})},[tc,ue,en,ec]);const Jn=!1,ts=On&&ne,tn=ts,[yg,si]=p.useState(1),Bn=!ne&&!Ke,rc=!!(Ae&&Bn&&!tn),wr=!ne&&!tn&&!Bn,Us=ne||Bn?"1.5rem":"9999px",sc=ne||Vt;p.useEffect(()=>{const V=O.current;if(!V)return;const ae=Ve=>{const $e=Ve>0&&Ve<b$;Qr(Le=>Le===$e?Le:$e)};if(ae(V.clientWidth),typeof ResizeObserver>"u"){const Ve=()=>ae(V.clientWidth);return window.addEventListener("resize",Ve),()=>window.removeEventListener("resize",Ve)}const Te=new ResizeObserver(Ve=>{ae(Ve[0]?.contentRect.width??V.clientWidth)});return Te.observe(V),()=>Te.disconnect()},[]);const oc=p.useMemo(()=>new Set,[]),{commands:ic}=C4(ue),ac=p.useMemo(()=>{const V=new Set;for(const ae of ic)V.add(ae.invocationName.toLowerCase());return V},[ic]),cc=Or(V=>V.snippets),lc=Or(V=>V.loadSnippets);p.useEffect(()=>{lc(ue)},[ue,lc]);const dc=p.useMemo(()=>{const V=new Set;for(const ae of cc){V.add(ae.name.toLowerCase());for(const Te of ae.aliases??[])V.add(Te.toLowerCase())}return V},[cc]),uc=p.useMemo(()=>Q.map(V=>V.filename),[Q]),Z=p.useMemo(()=>({inputMode:l,knownAgentNames:oc,confirmedMentions:a.current,knownSlashNames:ac,knownSnippetTriggers:dc,attachmentFilenames:uc}),[uc,l,oc,ac,dc]),pe=p.useCallback(V=>[...V??[]].map(ae=>({...ae,dataUrl:ae.source==="server"&&ae.serverPath?wL(ae.serverPath):ae.dataUrl})),[]),Re=p.useCallback(V=>({sanitizedText:V,attachments:[]}),[]),Ne=p.useRef(null),ct=p.useRef(!1),ot=B?ym(B,ye??ue):null,dt=ft(V=>V.followUpBehavior),Oe=ft(V=>V.addToQueue),Qe=TB(d_(B??""));p.useEffect(()=>{U.current=o},[o]),p.useEffect(()=>{P.current=Me},[Me]);const{persistNow:kt}=NB({message:o,messageRef:U,setMessage:i,confirmedMentionsRef:a,identity:Me,persistEnabled:!0,initialDraft:{text:n.current??"",identity:r.current},onIdentityChange:()=>d("normal"),onDraftRestored:()=>k.current?.selectAll()});p.useEffect(()=>{const V=Me?Qt(Me):"";Ye.getState().activateAttachmentsDraft(V)},[Me]);const jt=Ye(V=>V.sentDraftClear);p.useEffect(()=>{if(!jt)return;const V=Me?Qt(Me):"";if(!V||jt.draftKey!==V)return;Ye.getState().consumeSentDraftClear(jt.nonce);const ae=k.current?.getValue()??U.current;_I(jt,V,ae)&&(a.current.clear(),Qe.reset(),i(""))},[jt,Me,Qe]);const Cn=p.useRef(Ae);p.useEffect(()=>{!Cn.current&&Ae&&requestAnimationFrame(()=>{ne?k.current?.focus({preventScroll:!0}):k.current?.focus()}),Cn.current=Ae},[Ae,ne]);const{phase:nn}=h1();p.useEffect(()=>{if(ht!==null){const V=_e();V?.text&&(V.mode==="append"?i(ae=>{const Te=V.text;return Te.trim()?lB(ae,Te):ae}):V.mode==="append-inline"?i(ae=>L4(ae,V.text)):i(V.text),setTimeout(()=>{k.current?.focus()},0))}},[ht,_e]),p.useEffect(()=>{if(ge!==null){const V=Ze();V&&o.trim().length===0&&(i(V),setTimeout(()=>{k.current?.focus()},0))}},[ge,Ze,o]);const qs=Ye(V=>V.pendingWorktreeRestore),Ws=Ye(V=>V.consumePendingWorktreeRestore);p.useEffect(()=>{if(qs===null)return;const V=Ws();if(!V)return;const ae=hN(V,U.current??"");if(ae.ok)a.current=new Set(V.confirmedMentions),U.current=V.prompt,i(V.prompt),y(),setTimeout(()=>{k.current?.focus()},0);else{const Te=fN(ae,"pending-composer");Te&&Ce.error(Te.title,{description:Te.description})}},[qs,Ws,y]);const Qn=o.trim().length>0||Q.length>0,oi=!!(ve&&xe),Sr=nh(Q),Cr=l4(),V9=(Cr?"Connection lost. Waiting to reconnect — your draft is kept.":null)??(My(Q)?"Uploading attachments…":nP(Q)||Q.length>0&&!Sr?"Retry or remove failed attachments":null),vg=l==="shell"&&!!B&&!Ae,$9=Qn&&(oi||vg)&&Sr&&!Cr,Vn=!!(br.state&&br.state.phase!=="failed")||et||K,Ks=!B&&!Ae||Vn,fc=uu(B??""),z9=nn!=="idle"&&!fc,ii=p.useCallback(()=>{const V=k.current?.getValue()??o;return{message:V,hasContent:V.trim().length>0||Q.length>0}},[Q.length,o]),ai=p.useRef(!1),hc=p.useCallback(async()=>{if(jd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const V=ii();if(ai.current||!V.hasContent||!B||!ot||!nh(Q))return;ai.current=!0;let ae;try{ae=await sw(pe(Q))}catch{Ce.error("Attachment data could not be saved for the follow-up."),ai.current=!1;return}const Te=V.message.replace(/^\n+|\n+$/g,""),Ve=B?Lt.getState().getSessionAgentSelection(B)??void 0:void 0;if(!Oe(ot,{content:Te,attachments:ae.length>0?ae:void 0,sendConfig:ve&&xe?{providerID:ve,modelID:xe,agent:Ve,variant:J??void 0}:void 0})){ai.current=!1,Ce.error("Follow-up limit reached. Remove a pending message before adding another.");return}(k.current?.getValue()??U.current)===V.message&&i(""),ae.length>0&&Se(ae.map(Le=>Le.id)),ai.current=!1,ne||k.current?.focus()},[ii,B,ot,Q,pe,Oe,Se,ne,ve,xe,J]),U9=p.useCallback(V=>{i(V),setTimeout(()=>{k.current?.focus()},0)},[]),q9=p.useCallback(V=>{Fn.current({queuedOnly:!0,queuedMessageId:V,delivery:"steer"})},[]),W9=(V,ae)=>{const Te=V instanceof Error?V.message:"";return Te.toLowerCase().includes("runtime changed")?"Message failed to send. Attachments restored.":Te||ae},xg=async V=>{if(jd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const ae=V?.queuedOnly??!1,Te=V?.queuedMessageId,Ve=V?.delivery==="steer"?"steer":void 0,$e=ot;let Le=null;if(!(ae&&(!$e||!Te||(Le=ft.getState().claimQueuedMessage($e,Te),!Le)))){try{if(!ae&&!nh(Q)){My(Q)?Ce.info("Uploading attachments…"):Ce.error("Retry or remove failed attachments");return}const Je=V?.presetText!=null&&!ae?{message:V.presetText,hasContent:V.presetText.trim().length>0||Q.length>0}:ae?{message:"",hasContent:!1}:ii();if(!ae&&l==="shell"&&Q.length>0){Ce.error("Remove attachments to run a shell command.");return}if(ae){if(!B)return}else if(!Je.hasContent||!B&&!Ae)return;const gt=ae?Le?.sendConfig:void 0,hn=gt?.providerID??ve,pn=gt?.modelID??xe,Gs=gt?.agent,qu=ae?gt?.variant:J;if((!hn||!pn)&&!(vg&&!ae)){console.warn("Cannot send message: provider or model not selected"),Ce.error("Select a provider and model before sending a message.");return}const ut=he.getState().newSessionDraft,vc=!$e&&!ae&&!Te&&ut?.open===!0,xc=()=>he.getState().newSessionDraft.id===ut.id&&he.getState().currentSessionId===null,Wu=(l==="normal"?Sv(Je.message):null)?.name==="compact",Hg=!!(vc&&ut.worktreeIntent&&!Wu),rs=Hg?new Set(a.current):null;let mn=null;if(vc){if(ut.id&&he.getState().sendingNewSessionDraftId===ut.id)return;if(he.getState().setSendingNewSessionDraftId(ut.id),Hg){try{mn=await dN(Q)}catch{he.getState().sendingNewSessionDraftId===ut.id&&he.getState().setSendingNewSessionDraftId(null),Ce.error("Attachment data could not be saved for the worktree send.");return}U.current="",i(""),a.current.clear(),kt(Me,"")}await new Promise(ss=>{let Yt=!1;const sn=()=>{Yt||(Yt=!0,ss())};typeof window<"u"&&typeof window.requestAnimationFrame=="function"&&window.requestAnimationFrame(()=>sn()),setTimeout(()=>sn(),50)})}try{const ss=!$e&&!V?.queuedOnly&&!V?.queuedMessageId&&ut?.open&&!Wu?ut.worktreeIntent:null;let Yt=br.getReceipt(ss);if(ss&&!Yt){const rt=br.request({intent:ss,prompt:Je.message,failedSend:{prompt:Je.message,confirmedMentions:rs?[...rs]:[],attachments:mn??[]}});if(mn&&mn.length>0&&Se(mn.map(It=>It.id)),Ce.info("Worktree queued",ut.id?{id:`worktree-queued:${ut.id}`}:void 0),he.getState().openNewSessionDraft(),re.getState().setActiveMainTab("chat"),Yt=await rt,!Yt){if((ut.id?cn.getState().getEntryByKey(ut.id):cn.getState().getEntry(ss))?.failedSend){Ce.error("Worktree creation failed",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}if(xc()){if(U.current=Je.message,a.current=rs??new Set,i(Je.message),As(Me,Je.message,rs??[]),mn){const bt=Ye.getState().restoreAttachmentsForRetry(mn);if(!bt.ok){const kn=jp({limit:bt.limit,currentCount:bt.currentCount,missingCount:bt.missingCount});Ce.error(kn.title,{description:kn.description})}}}else Ce.error("Worktree creation failed",{description:"Your prompt was not sent."});return}}const sn=Yt?ut.id??a3(ss):null,kr=sn?cn.getState().getEntryByKey(sn)?.failedSend??null:null,bc=!$e&&!V?.queuedOnly&&!V?.queuedMessageId&&ut?.open&&!Wu?ut.branchIntent:null;if(bc&&!Pt.getReceipt(bc)){if(Pt.dialogState)return;await Pt.request({intent:bc,projectId:ut.selectedProjectId,continuation:V});return}const Ku=Pt.getReceipt(bc),Fg=ae&&$e&&Le?{target:$e,delivery:"steer",operationId:Le.id}:$e?{target:$e,...Ve?{delivery:Ve}:{}}:Ve||Ku||Yt?{...Ve?{delivery:Ve}:{},...Ku?{branchCheckoutReceipt:Ku}:{},...Yt?{worktreeCreationReceipt:Yt,draftSnapshot:ut}:{}}:void 0,Bg=Be(),vS=new Set(Hr.getState().skills.map(rt=>rt.name)),Gu=kB(ae&&Le?{queued:[{content:Le.content,attachments:Le.attachments}],composerText:null,composerAttachments:[],syntheticTexts:Bg?.map(rt=>rt.text)??[]}:{queued:[],composerText:Je.hasContent?Je.message:null,composerAttachments:uN(mn,Q),syntheticTexts:Bg?.map(rt=>rt.text)??[]},{parseAgentMention:rt=>({text:rt}),extractFileMentions:rt=>{const{sanitizedText:It,attachments:bt}=Re(rt);return{text:It,attachments:bt}},sanitizeAttachments:pe,collectSkillNames:rt=>SB(rt,vS),buildSkillInstruction:CB});let wc=Gu.primaryText;const{primaryAttachments:Vg,additionalParts:li}=Gu;if(Gu.isEmpty){!ae&&sn&&kr&&Yt&&mN(sn,kr,"Prompt was empty and was not sent.")&&Ce.error("Prompt was empty and was not sent.",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const Sc=()=>!Yt||xc();!ae&&Sc()&&(Qe.reset(),Ja(!1)),ne&&Sc()&&k.current?.blur();const Cc=l==="normal"?Sv(wc):null;if(Cc&&await IB({command:Cc,currentSessionId:B,scrollToBottom:t,setTimelineDialogOpen:Ot,onUndoSession:async It=>{await he.getState().handleSlashUndo(It)},onRedoSession:async It=>{await he.getState().handleSlashRedo(It)},onCompactSession:async(It,bt)=>{try{await A_(),await N_(It,bt)}catch(kn){Ce.error(W9(kn,"Failed to compact session"))}}})){!ae&&sn&&kr&&Yt&&gN(sn,kr,mn,Q),Sc()&&(kt(Me,""),i(""),a.current.clear());return}let di=!!(vc&&Cc&&!P4(Cc.name))?{...Fg,initialInputKind:"extension-command"}:Fg;const $g=$e?.directory??ue,zg=await qH({newSessionDraftOpen:Ae,sessionId:$e?.sessionId??B,getStoreState:()=>qe().getState()});if(zg&&li.push({text:WH(zg),synthetic:!0}),l!=="shell")try{const rt=Or.getState().expandText;wc=rt(wc,$g);for(const It of li)It.synthetic||(It.text=rt(It.text,$g))}catch(rt){console.warn("[ChatInput] Failed to expand snippets, sending original text:",rt)}const xS=[...Vg,...li.flatMap(rt=>rt.attachments??[])],Ug=c3(mn,Q);if(ae&&$e&&Le){const rt=ft.getState().markDeliveryAttempt($e,Le.id,"steer");if(!rt?.streamEpoch){ft.getState().markSendUnconfirmed($e,Le.id,"steer"),Ce.error("Follow-up status uncertain. Check status before retrying.");return}di={...di,streamEpoch:rt.streamEpoch}}!ae&&l==="shell"&&(di={...di,...f?{shellExcludeFromContext:!0}:{}});const bS=q(wc,hn??"",pn??"",Gs,Vg,void 0,li.length>0?li:void 0,qu,l,di);Pt.clearReceipt(),typeof window>"u"?t?.():window.requestAnimationFrame(()=>{t?.()}),await bS.then(()=>{if(ae&&$e&&Le&&ft.getState().completeQueuedSend($e,Le.id),!ae&&sn&&kr&&cn.getState().markWorktreePromptSucceeded(sn,kr),!ae&&Ug.length>0&&Se(Ug),!ae&&Sc()){const rt=Me?Qt(Me):"",It=P.current,bt=It?Qt(It):"",kn=k.current?.getValue()??U.current,kc=!kn||kn===Je.message;rt===bt?(kt(Me,kc?"":kn),kc&&(i(""),a.current.clear(),Qe.reset()),Ye.getState().publishSentDraftClear(rt,Je.message)):kt(Me,"")}}).catch(rt=>{if(ae&&$e&&Le){if(S3(rt)){ft.getState().markSendUnconfirmed($e,Le.id,"steer"),console.warn("Follow-up send unconfirmed:",rt),Ce.error("Follow-up status uncertain. Check status before retrying.");return}ft.getState().markSendFailed($e,Le.id)}const It=rt instanceof Error?rt.message:typeof rt=="string"?rt:String(rt??""),bt=It.toLowerCase();if(console.error("Message send failed:",It||rt),!ae&&sn&&kr&&Yt){const Zs=It||"Prompt failed to send.";cn.getState().markWorktreePromptFailed(sn,kr,Zs),Ce.error("Prompt failed to send",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const kn=k.current?.getValue()??U.current;if(xc()&&Je.message&&(!kn||kn===Je.message)&&(rs&&(a.current=rs),i(Je.message),As(Me,Je.message,rs??a.current)),xc()&&mn){const Zs=Ye.getState().restoreAttachmentsForRetry(mn);if(!Zs.ok){const qg=jp({limit:Zs.limit,currentCount:Zs.currentCount,missingCount:Zs.missingCount});Ce.error(qg.title,{description:qg.description})}}const kc=bt.includes("timeout")||bt.includes("timed out")||bt.includes("may still be processing")||bt.includes("being processed")||bt.includes("failed to fetch")||bt.includes("networkerror")||bt.includes("network error")||bt.includes("gateway timeout")||bt==="failed to send message";if(bt.includes("payload too large")||bt.includes("413")||bt.includes("entity too large")){Ce.error("Attachments are too large to send. Please try reducing the number or size of images.");return}if(kc){xS.length>0&&Ce.error("Failed to send attachments. Try fewer files or smaller images.");return}if(bt.includes("runtime changed")){Ce.error("Message failed to send. Attachments remain available.");return}Ce.error(It||"Message failed to send. Attachments remain available.")})}finally{vc&&he.getState().sendingNewSessionDraftId===ut.id&&he.getState().setSendingNewSessionDraftId(null)}}finally{ae&&$e&&Le&&ft.getState().clearSending($e,Le.id)}ne||k.current?.focus()}};Fn.current=xg;const bg=p.useCallback(()=>{const V=ii(),ae=l==="normal"&&V.hasContent&&B&&nn!=="idle";(dt==="queue"||fc)&&ae?hc():dt==="steer"&&ae?Fn.current({delivery:"steer"}):Fn.current()},[l,ii,B,nn,fc,dt,hc]),rn=p.useCallback((V,ae,Te="manual",Ve)=>{const $e=oF(V,ae,{inputMode:l,inputSource:Te,insertedText:Ve});m($e?.kind??null),x($e?.query??"")},[l]),pc=p.useCallback(V=>{const ae=()=>{try{k.current?.focus({preventScroll:!0})}catch{k.current?.focus()}k.current?.setSelection(V)};requestAnimationFrame(()=>{ae(),requestAnimationFrame(ae)}),setTimeout(ae,60)},[]),Du=p.useCallback(V=>{const ae=V.trim();if(!ae)return;const Te=`/${ae} `,Ve=k.current,$e=Ve?.getValue()??U.current??"",Le=$e.trim().length>0?`${Te}${$e.replace(/^\s+/,"")}`:Te,Je=Te.length;if(Ve)try{Ve.replaceRange(0,$e.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>Ve.setSelection(Je))}else i(Le);rn(Le,Je,"manual",Te),y(),pc(Je)},[y,pc,i,rn]),Ou=p.useCallback(V=>{const ae=V.trim();if(!ae)return;const Te=k.current,Ve=Te?.getValue()??U.current??"",$e=Ve.trim().length>0,Le=$e?`${ae} ${Ve.replace(/^\s+/,"")}`:ae,Je=$e?ae.length+1:ae.length;if(Te)try{Te.replaceRange(0,Ve.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>Te.setSelection(Je))}else i(Le);rn(Le,Je,"manual"),y(),pc(Je)},[y,pc,i,rn]);p.useEffect(()=>{if(Fe==null)return;const V=Ye.getState().consumePendingStarterInsert();V&&("text"in V?Ou(V.text):Du(V.name))},[Fe,Du,Ou]);const K9=FB({inputMode:l,setInputMode:d,shellExcludeFromContext:f,setShellExcludeFromContext:u,message:o,setMessage:i,openAutocomplete:h,commandRef:X,snippetRef:F,mentionRef:z,composerRef:k,messageHistory:Qe,updateAutocompleteState:rn,isMobile:ne,hasContent:Qn,currentSessionId:B,sessionPhase:nn,commandRunning:!!fc,followUpBehavior:dt,handleSubmit:xg,handleQueueMessage:hc}),{update:G9}=EB({enabled:Jn,openAutocomplete:h,message:o,editorRef:k,containerRef:O}),mc=p.useCallback(()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null),Jr(!0),Ne.current=setTimeout(()=>{Jr(!1),Ne.current=null},1800)},[]),Z9=p.useCallback(()=>{te(),mc(),ke(B||void 0)},[ke,te,B,mc]),Y9=p.useCallback((V,ae="manual")=>{if(!V)return;const Te=k.current;if(!Te){const gt=o+V;i(gt),rn(gt,gt.length,ae,V);return}const{start:Ve,end:$e}=Te.getSelection(),Le=`${o.substring(0,Ve)}${V}${o.substring($e)}`,Je=Ve+V.length;Te.insertText(V),rn(Le,Je,ae,V)},[o,rn]),X9=p.useCallback(()=>{const V=U.current.length;De.current=k.current?.getSelection()??{start:V,end:V},y(),fe.start().catch(()=>{})},[y,fe]),J9=p.useCallback(()=>{fe.finish().then(V=>{const ae=U.current,Te=De.current,Ve=Math.min(Math.max(0,Te.start),ae.length),$e=Math.min(Math.max(Ve,Te.end),ae.length),Le=R4(V.trim(),ae.slice(0,Ve),ae.slice($e));if(!Le)return;const Je=k.current;if(Je)Je.replaceRange(Ve,$e,Le,Ve+Le.length),Je.focus({preventScroll:!0});else{const gt=`${ae.slice(0,Ve)}${Le}${ae.slice($e)}`;i(gt),rn(gt,Ve+Le.length,"manual",Le)}}).catch(()=>{})},[fe,rn]);p.useEffect(()=>{fe.state!=="error"||!fe.error||Ue.current===fe.error||(Ue.current=fe.error,Ce.error(fe.error))},[fe.error,fe.state]);const Hu=p.useCallback(()=>{N.current=!1,D.current&&(clearTimeout(D.current),D.current=null)},[]),Q9=p.useCallback(()=>{N.current=!0,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{N.current=!1,D.current=null},700)},[]),eS=({value:V,selection:ae,fromPaste:Te,insertedText:Ve})=>{const $e=Te?Ve:"",Le=$e.includes("@")||N.current;N.current&&Hu();const Je=Le?"paste":"manual";if(l==="shell"&&!f&&V.startsWith("!")){const gt=V.slice(1),hn=Math.max(0,ae.start-1);u(!0),i(gt);const pn=k.current;pn&&pn.getValue()!==gt?pn.replaceRange(0,1,"",hn):requestAnimationFrame(()=>k.current?.setSelection(hn));return}if(l==="normal"&&V.startsWith("!")){const gt=V.slice(1),hn=Math.max(0,ae.start-1);d("shell"),i(gt),y();const pn=k.current;pn&&pn.getValue()!==gt?(pn.replaceRange(0,1,"",hn),y()):requestAnimationFrame(()=>k.current?.setSelection(hn));return}i(V),rn(V,ae.start,Je,$e)};p.useEffect(()=>()=>{Hu()},[Hu]);const tS=wB({inputMode:l,enabled:!!(B||Ae),composerRef:k,message:o,setMessage:i,insertTextAtSelection:Y9,updateAutocompleteState:rn,markFileMentionPasteSuppression:Q9,attachedFiles:Q,addAttachedFile:me}),nS=p.useCallback(V=>kL(V,ti||""),[ti]),{handleFileSelect:rS,handleSnippetSelect:sS,handleCommandSelect:oS}=RB({composerRef:k,message:o,setMessage:i,updateAutocompleteState:rn,closeAutocomplete:y,confirmedMentionsRef:a,toMentionPath:nS});p.useEffect(()=>{B&&k.current&&!ne&&k.current.focus()},[B,ne]),p.useEffect(()=>{ne||I(null)},[ne]),p.useEffect(()=>{Xe&&Xe!==B&&te()},[Xe,B,te]),p.useEffect(()=>{W.current=!!(B||Ae)},[B,Ae]);const{isDragging:iS,isInternalDrag:aS,handleDragEnter:wg,handleDragOver:Sg,handleDragLeave:cS,handleDragEnd:Cg,handleDrop:kg,handleDropCapture:Mg}=yB({enabled:!!(B||Ae),composerRef:k,messageRef:U,cursorPosRef:L,confirmedMentionsRef:a,setMessage:i,addAttachedFile:me}),Ig=p.useRef(null),Eg=p.useCallback(async V=>{const ae=Array.isArray(V)?V:Array.from(V),Te=await Promise.all(ae.map(async Ve=>{try{return await me(Ve)}catch($e){return console.error("File attach failed",$e),!1}}));ae.length>0&&!Te.some(Boolean)&&Ce.error("Failed to attach file")},[me]),_g=p.useCallback(()=>{Ks||Ig.current?.click()},[Ks]),[jg,Tg]=p.useState(!1),lS=p.useCallback(()=>{Ks||Tg(!0)},[Ks]),dS=p.useCallback(async V=>{const ae=V.target.files;ae&&(await Eg(ae),V.target.value="")},[Eg]),uS="gap-x-1.5 gap-y-0",fS=!0,ci=(Ae||!!B)&&!Ke,{projects:Ag,selectedDraftProject:ns,selectedDraftBranchLabel:Fu,selectedBranchName:Bu,draftBranchItems:Ng,isDiscoveringDraftBranches:Lg,shouldShowDraftBranchSelector:er,worktreeMode:Vu,handleDraftProjectChange:Rg,handleDraftBranchChange:Pg,handleWorktreeModeChange:$u}=$B(ci),Dg=!!(ci&&ns&&(Ae||er)),gc=p.useMemo(()=>Ke||ni!==!0||!xr||xr.isClean?!1:o4(xr.files,xr.diffStats,ue).length>0,[ue,xr,ni,Ke])?c.jsx(c4,{align:Dg?"end":"start"}):null,zu=KB({isMobile:ne,editorRef:k,formRef:M,controlsPanelOpen:!!w,attachMenuOpen:!1}),hS=zu.focused;p.useEffect(()=>{j("")},[E]),GB({isMobile:ne,isFullscreen:ts,isDraftScreen:Ae,isFocused:hS,formRef:M,editorRef:k});const pS=ne?"pl-1.5 pr-3 pt-1.5 pb-3":wr?"px-1.5 py-1":"px-3 py-2",mS=ne?"h-8 w-8":"h-6 w-6",gS="h-4 w-4",yS=ne?"h-6 w-6":"h-5 w-5",yc="h-[18px] w-[18px]",Og="flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed",Uu=R(Og,mS);return p.useEffect(()=>{const V=!!Xe&&Xe===B;!ct.current&&V&&!Hn&&(mc(),B&&ie(B)),ct.current=V},[Xe,ie,B,Hn,mc]),p.useEffect(()=>()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null)},[]),c.jsxs(c.Fragment,{children:[c.jsxs("form",{ref:M,onSubmit:V=>{V.preventDefault(),bg()},className:R("relative w-full pt-0 pb-4",Jn,ts&&"flex h-full min-h-0 flex-col pt-2",ne&&"bottom-safe-area oc-mobile-composer"),style:ne&&$s>0?{marginBottom:`${$s}px`}:void 0,children:[c.jsxs("div",{className:R("chat-input-column relative overflow-visible",tn&&"flex flex-1 min-h-0 flex-col"),children:[c.jsx(U3,{onEditMessage:U9,onSendMessage:q9}),c.jsx(K4,{sessionId:B,directory:ye??ue}),c.jsx(w$,{showAbortStatus:Hn,showAssistantStatus:!1,showTodos:fS,leftAccessory:Dg||Ae||!gc?null:gc}),!Sn&&ci&&ns&&(Ae||er)?c.jsx("div",{inert:Vn||void 0,className:R(Vn&&"pointer-events-none opacity-60"),children:c.jsx(xV,{projects:Ag,selectedProject:ns,selectedBranchName:Bu,selectedBranchLabel:Fu,branchOptions:Ng,branchInteractive:Ae,branchLoading:Lg,showBranchSelector:er&&Ae,showProjectSelector:Ae,showWorktreeSelector:Ae&&er,worktreeMode:Vu,endAccessory:gc,onProjectChange:Rg,onBranchChange:Pg,onWorktreeModeChange:$u,theme:Xr})}):null,Sn&&ci&&ns&&(Ae||er)?c.jsx("div",{inert:Vn||void 0,className:R(Vn&&"pointer-events-none opacity-60"),children:c.jsx(bV,{selectedProject:ns,selectedBranchName:Bu,selectedBranchLabel:Fu,branchInteractive:Ae,showBranchSelector:er,showProjectSelector:Ae,showWorktreeSelector:Ae&&er,worktreeMode:Vu,onWorktreeModeChange:$u,endAccessory:gc,theme:Xr,onOpenPicker:T})}):null,c.jsx("div",{className:R(!ne&&"contents",ne&&"relative",ts&&"flex min-h-0 flex-1 flex-col"),children:c.jsx(c.Fragment,{children:c.jsxs("div",{className:R("flex flex-col relative overflow-visible",tn&&"flex-1 min-h-0",Bn&&!tn&&"min-h-[7rem]","border border-border/80","shadow-[0_4px_16px_-4px_rgb(0_0_0_/_0.12)]","focus-within:ring-1",l==="shell"?"focus-within:ring-[color:color-mix(in_srgb,var(--status-info)_45%,transparent)]":"focus-within:ring-primary/30"),style:{borderRadius:Us,backgroundColor:Xr?.colors?.surface?.subtle},ref:O,"data-composer-card":"true",onDropCapture:Mg,onDragEnter:wg,onDragOver:Sg,onDragLeave:cS,onDrop:kg,onDragEnd:Cg,children:[iS&&c.jsx(WV,{isInternalDrag:aS,iconButtonBaseClass:Og,iconSizeClass:yc,radius:Us,isAttachmentDisabled:Ks,onPickLocalFiles:_g}),et&&c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",style:{borderRadius:Us},children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}),c.jsx(PV,{open:h,query:g,overlayPosition:null,commandRef:X,snippetRef:F,mentionRef:z,onCommandSelect:oS,onSnippetSelect:sS,onFileSelect:rS,onClose:y,onCommandComboboxStateChange:S}),c.jsx(qV,{isMobile:ne,isInline:wr,alignToolsEnd:yg>1,sessionId:B,directory:ye??ue,newSessionDraftOpen:Ae,messageLength:o.length,leadingExtra:l!=="shell"&&(Bn||ne)?c.jsx($v,{keepLabels:!0,className:"w-max shrink-0",mobilePanel:ne?w:void 0,onMobilePanelChange:ne?I:void 0}):null,trailingExtra:st?null:c.jsx(ZV,{available:fe.available,disabled:!B&&!Ae||Vn,className:Uu,iconClassName:yc,onStart:X9}),actionsOverride:st?c.jsx(r$,{state:fe.state,elapsedSeconds:fe.elapsedSeconds,buttonClassName:Uu,iconClassName:yc,isMobile:ne,onCancel:fe.cancel,onDone:J9}):void 0,radius:Us,footerPaddingClass:pS,footerGapClass:uS,footerIconButtonClass:Uu,iconSizeClass:yc,sendIconSizeClass:gS,stopIconSizeClass:yS,canSend:$9&&!Vn,isSending:et,isShellMode:l==="shell",isAttachmentDisabled:Ks,disabledReason:V9,canAbort:z9,hasContent:!!Qn,onOpenSettings:e,onPickLocalFiles:_g,onLinkGitHub:lS,onPrimaryAction:bg,onQueueMessage:hc,onAbort:Z9,children:st?c.jsx(s$,{state:fe.state,subscribeLevel:fe.subscribeLevel}):c.jsxs("div",{className:R("overflow-hidden",tn&&"flex flex-1 min-h-0 flex-col"),children:[l==="shell"?c.jsxs("div",{className:R("flex items-center gap-1.5 typography-micro text-muted-foreground",wr?"px-1.5 pt-1":"px-3 pt-2"),"data-testid":"chat-input-shell-mode",children:[c.jsx($,{name:"terminal-box",className:"size-3.5 shrink-0 text-foreground"}),c.jsx("span",{className:"font-medium text-foreground",children:"Shell"}),c.jsx("span",{className:"min-w-0 truncate",children:f?"Output not sent to the model":"Output sent to the model"}),!ne||_t?c.jsx("span",{className:"ml-auto shrink-0",children:"Esc to exit"}):c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>{d("normal"),k.current?.focus()},className:"ml-auto h-6 shrink-0 px-2 typography-micro font-medium text-muted-foreground hover:text-foreground",children:"Exit shell"})]}):null,c.jsx("div",{className:"relative z-10",children:c.jsx($3,{onShowPopup:Ru,isInline:wr,isMobile:ne})}),c.jsx("div",{className:R("relative overflow-hidden",tn&&"flex flex-1 min-h-0 flex-col"),onDragEnter:wg,onDragOver:Sg,onDropCapture:Mg,onDrop:kg,onDragEnd:Cg,children:c.jsx(aB,{ref:k,viewStore:_,"data-testid":"chat-input",value:o,languageContext:Z,onChange:eS,onKeyDown:V=>(K9(V),V.defaultPrevented),onPaste:tS,onSelectionChange:V=>{L.current=V.start,G9()},onVisualLineCount:V=>{si(ae=>ae===V?ae:V)},onFocus:zu.onEditorFocus,onBlur:zu.onEditorBlur,placeholder:K?"Session is open elsewhere":B||Ae?l==="shell"?f?"Enter shell command...":"Enter shell command... (!! keeps it from the model)":rc?"Plan, build, / for skills, @ for context":sc?"Ask anything. @ files, / commands":"Ask anything. @ files, / commands, ! shell, # snippets":"Select or create a session to start chatting",editable:!!(B||Ae)&&!Vn,autoCorrect:!1,autoCapitalize:"none",spellCheck:ne,fillContainer:tn,maxLines:ne?v$:y$,boundSelector:ne?"[data-composer-bound]":void 0,boundGapPx:x$,commandComboboxExpanded:C,commandComboboxListboxId:v,commandComboboxActiveOptionId:C?b?.activeOptionId:void 0,className:R("relative z-10",wr?"min-h-0 px-1.5 py-1.5":"min-h-[52px] px-3",tn?R("h-full min-h-0",ne?"py-2.5":"py-4"):ne?Q.length>0?"pt-1 pb-2.5":"py-2.5":wr?void 0:Q.length>0?"pt-1.5 pb-2":"pt-3 pb-2","typography-markdown md:typography-ui-label",l==="shell"&&"font-mono")})})]})})]})})}),Bn||ne||l==="shell"?null:c.jsx("div",{className:R("mt-1.5 flex w-full shrink-0 items-center pl-2",Vn&&"pointer-events-none opacity-60"),inert:Vn||void 0,children:c.jsx($v,{className:"w-full min-w-0"})})]}),Ae&&!Jn&&!ne&&!Ke?c.jsx(w4,{onInsert:V=>V.ref.type==="text"?Ou(V.insertText):Du(V.promptName),className:"chat-input-column mt-3"}):null]}),nc?c.jsx(p.Suspense,{fallback:null,children:c.jsx(g$,{popup:ri,onOpenChange:Pu,isMobile:ne})}):null,c.jsx(GV,{inputRef:Ig,onChange:dS}),c.jsx(SV,{state:Pt.dialogState,onCancel:Pt.cancel,onConfirm:()=>{Pt.confirm()}}),jg&&(ye??ue)?c.jsx(p.Suspense,{fallback:null,children:c.jsx(m$,{directory:ye??ue,open:jg,onClose:()=>Tg(!1)})}):null,Sn&&ci&&ns?c.jsx(wV,{projects:Ag,selectedProject:ns,selectedBranchName:Bu,selectedBranchLabel:Fu,branchOptions:Ng,branchInteractive:Ae,branchLoading:Lg,showBranchSelector:er,showProjectSelector:Ae,showWorktreeSelector:Ae&&er,worktreeMode:Vu,onProjectChange:Rg,onBranchChange:Pg,onWorktreeModeChange:$u,theme:Xr,openPicker:E,onOpenPickerChange:T,query:A,onQueryChange:j}):null]})};Z4.displayName="ChatInput";const _i=p.memo(Z4);function C$({label:e,className:t}){return c.jsx("span",{className:R("size-1.5 shrink-0 rounded-full bg-status-warning",t),"aria-label":e,title:e})}const k$=e=>e!=null&&e.count>0,hQ=e=>k$(e.pendingInput)?"needs-input":e.isStreaming?"working":!e.isStreaming&&!e.isActive&&e.unseenCount>0?"unread":null,M$=(e,t)=>{const n=e==="approval"?"Needs approval":"Needs input";return t>1?`${n} (${t} requests)`:n},pQ=e=>e===1?"A session needs input":`${e} sessions need input`,I$="underline decoration-dotted underline-offset-2 hover:decoration-solid",Y4=({segment:e,href:t,children:n})=>c.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:I$,style:Nd(e),children:n}),qt=H.memo(({text:e,className:t,style:n,links:r=!1})=>{if(e==null||e==="")return null;if(!z4(e))return t||n?c.jsx("span",{className:t,style:n,children:e}):c.jsx(c.Fragment,{children:e});const s=U4(e);return s.length===0?null:s.length===1&&!Nd(s[0])&&!(r&&s[0].href)?t||n?c.jsx("span",{className:t,style:n,children:s[0].text}):c.jsx(c.Fragment,{children:s[0].text}):c.jsx("span",{className:t,style:n,children:s.map((o,i)=>{const a=r?$4(o.href):void 0;if(a)return c.jsx(Y4,{segment:o,href:a,children:o.text},i);const l=Nd(o);return l?c.jsx("span",{style:l,children:o.text},i):c.jsx(H.Fragment,{children:o.text},i)})})});qt.displayName="AnsiText";const E$=(e,t,n)=>{if(n<=0)return null;switch(e){case"ArrowDown":return{kind:"highlight",index:(t+1)%n};case"ArrowUp":return{kind:"highlight",index:(t-1+n)%n};case"Home":return{kind:"highlight",index:0};case"End":return{kind:"highlight",index:n-1};case"Enter":case" ":return{kind:"submit",index:t};default:{if(e.length!==1||e<"1"||e>"9")return null;const r=Number(e)-1;return r<n?{kind:"submit",index:r}:null}}},_$=async(e,t,n)=>{try{await Ie.respondToExtensionDialog({requestId:t.requestId,...n},{runtimeKey:Y()}),qe().dismissExtensionDialog(e,t.requestId)}catch(r){if(r instanceof at&&r.code==="EXTENSION_DIALOG_NOT_PENDING"){qe().dismissExtensionDialog(e,t.requestId);return}throw r}},j$=()=>{requestAnimationFrame(()=>{document.querySelector('[data-slot="composer-editor"], .chat-input-column textarea, textarea')?.focus()})},T$=(e,t)=>{const[n,r]=H.useState(()=>typeof e!="number"||e<=0?null:Math.max(0,Math.ceil(e/1e3)));return H.useEffect(()=>{if(typeof e!="number"||e<=0){r(null);return}const s=Date.now();let o=null;const i=()=>{const a=Date.now()-s,l=Math.max(0,Math.ceil((e-a)/1e3));r(l),l<=0&&o!==null&&(clearInterval(o),o=null)};return i(),o=setInterval(i,1e3),()=>{o!==null&&clearInterval(o)}},[e,t]),n},A$=e=>e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.value.trim().length>0:e.isContentEditable?(e.textContent??"").trim().length>0:!1:!1,N$=({request:e,onRespond:t,messageId:n,highlightedIndex:r,setHighlightedIndex:s})=>{const o=e.options??[];return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex flex-col gap-1 max-h-60 overflow-y-auto",role:"listbox","aria-label":Nn(e.title),children:o.map((i,a)=>{const l=a===r,d=a<9?a+1:void 0;return c.jsxs("button",{type:"button",role:"option","aria-selected":l,tabIndex:l?0:-1,onMouseEnter:()=>s(a),onFocus:()=>s(a),onClick:()=>t({value:i}),className:R("flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors outline-none",l?"bg-interactive-selection text-interactive-selection-foreground font-medium":"text-foreground hover:bg-interactive-hover"),children:[c.jsx("span",{className:"truncate",children:c.jsx(qt,{text:i})}),d!==void 0&&c.jsx("span",{className:R("ml-2 shrink-0 font-mono text-xs opacity-70",l?"text-interactive-selection-foreground":"text-muted-foreground"),children:d})]},i)})})]})},L$=({request:e,onRespond:t,messageId:n})=>c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-3 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsxs("div",{className:"flex items-center justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"outline",size:"sm",onClick:()=>t({confirmed:!1,cancelled:!0}),children:"No (N)"}),c.jsx(be,{type:"button",variant:"default",size:"sm",onClick:()=>t({confirmed:!0}),children:"Yes (Y)"})]})]}),R$=({request:e,onRespond:t,messageId:n})=>{const r=e.method==="editor",[s,o]=H.useState(r?e.prefill??"":""),i=()=>{t({value:s})};return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),r?c.jsx("textarea",{autoFocus:!0,value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),rows:4,className:"w-full resize-y rounded-md border bg-transparent p-2 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),i())}}):c.jsx("input",{autoFocus:!0,type:"text",value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),className:"w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),i())}}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(be,{type:"button",variant:"default",size:"sm",onClick:i,disabled:!r&&s.trim().length===0,children:"Submit"})]})]})},P$=({request:e,onRespond:t,messageId:n})=>{const r={};for(const u of e.fields??[])u.type==="checkbox"?r[u.id]=u.initial==="true"?"true":"false":u.initial!==void 0?r[u.id]=u.initial:u.type==="select"&&u.options?.[0]!==void 0?r[u.id]=u.options[0]:r[u.id]="";const[s,o]=H.useState(r),[i,a]=H.useState(!1),l=(e.fields??[]).filter(u=>u.required&&(s[u.id]??"").length===0),d=(e.fields??[]).filter(u=>{if(u.type!=="number")return!1;const h=s[u.id]??"";if(h.length===0)return!1;const m=Number(h);return!Number.isFinite(m)||"min"in u&&typeof u.min=="number"&&m<u.min||"max"in u&&typeof u.max=="number"&&m>u.max}),f=i&&(l.length>0||d.length>0);return c.jsxs("form",{onSubmit:u=>{u.preventDefault(),a(!0),!(l.length>0||d.length>0)&&t({values:{...s}})},children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex max-h-60 flex-col gap-2.5 overflow-y-auto",children:(e.fields??[]).map(u=>{const h=f&&u.required&&(s[u.id]??"").length===0,m=f&&d.some(y=>y.id===u.id),g=h||m,x=s[u.id]??"",b=y=>o(v=>({...v,[u.id]:y})),S="w-full rounded-md border bg-transparent p-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing";return u.type==="checkbox"?c.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[c.jsx("input",{type:"checkbox",checked:x==="true",onChange:y=>b(y.target.checked?"true":"false"),className:"size-4"}),c.jsx("span",{children:c.jsx(qt,{text:u.label})})]},u.id):c.jsxs("label",{className:"flex flex-col gap-1 text-sm",children:[c.jsxs("span",{className:"text-xs font-medium text-foreground",children:[c.jsx(qt,{text:u.label}),u.required&&c.jsx("span",{"aria-hidden":"true",className:"text-status-error",children:" *"})]}),u.type==="textarea"?c.jsx("textarea",{value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",rows:2,"aria-invalid":g||void 0,className:S}):u.type==="number"?c.jsx("input",{type:"number",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",min:"min"in u&&typeof u.min=="number"?u.min:void 0,max:"max"in u&&typeof u.max=="number"?u.max:void 0,"aria-invalid":g||void 0,className:S}):u.type==="select"?c.jsx("select",{value:x,onChange:y=>b(y.target.value),"aria-invalid":g||void 0,className:S,children:(u.options??[]).map(y=>c.jsx("option",{value:y,children:y},y))}):c.jsx("input",{type:"text",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"","aria-invalid":g||void 0,className:S})]},u.id)})}),f&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:l.length>0&&d.length>0?"Fill in all required fields and enter valid numbers within the allowed range before submitting.":d.length>0?"Enter valid numbers within the allowed range before submitting.":"Fill in all required fields before submitting."}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(be,{type:"submit",variant:"default",size:"sm",children:"Submit"})]})]})},D$=3,O$=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.sessionId!==s.sessionId||r.directory!==s.directory||r.title!==s.title||r.pending.count!==s.pending.count||r.pending.kind!==s.pending.kind||r.pending.since!==s.pending.since)return!1}return!0},H$=e=>ze(t=>{const n=[];for(const r of Wm(t.catalog)){if(e&&r.sessionId===e)continue;const s=t.catalog.byId.get(r.sessionId),o=s?n3(Ls(s),"Untitled session"):"Untitled session";n.push({sessionId:r.sessionId,directory:r.directory,pending:r.pending,title:o})}return n},O$,"catalog",e??""),F$=({sessions:e})=>{const t=he(s=>s.setCurrentSession),n=e.slice(0,D$),r=e.length-n.length;return c.jsxs("div",{role:"region","aria-label":"Other sessions need input",className:"overflow-hidden rounded-xl border border-border/80 bg-card p-1.5 shadow-md",children:[c.jsx("ul",{className:"flex flex-col",children:n.map(s=>{const o=M$(s.pending.kind,s.pending.count);return c.jsxs("li",{className:"flex min-h-[44px] items-center gap-2 px-2 py-1",children:[c.jsx(C$,{label:o}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",title:`${s.title} — ${o}`,children:s.title}),s.pending.count>1?c.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:`${s.pending.count} requests`}):null,c.jsx(be,{type:"button",variant:"outline",size:"sm",onClick:()=>{t(s.sessionId,s.directory)},"aria-label":`Open ${s.title}`,children:"Open"})]},s.sessionId)})}),r>0?c.jsx("p",{className:"px-2 pb-1 text-xs text-muted-foreground",children:`+${r} more`}):null]})},zv=({sessionId:e})=>{const t=ze(y=>{const v=e??y.selectedSessionId,w=(v?y.reducer.bySession.get(v):void 0)?.extensionDialogs??[],I=w[0];if(I&&v)return{sessionId:v,request:I,queueLength:w.length};if(e!==void 0)return null;for(const[E,T]of y.reducer.bySession){const A=T.extensionDialogs,j=A[0];if(j)return{sessionId:E,request:j,queueLength:A.length}}return null},(y,v)=>y?.sessionId===v?.sessionId&&y?.request.requestId===v?.request.requestId&&y?.queueLength===v?.queueLength,"dialogs",e??""),n=he(y=>y.currentSessionId),s=H$(e??n??null),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(0),u=H.useRef(!1),h=H.useRef(null),m=H.useId(),g=t?`${t.sessionId}\0${t.request.requestId}`:null;H.useEffect(()=>{u.current=!1,i(!1),l(!1),f(0),g!==null&&h.current&&!h.current.contains(document.activeElement)&&!A$(document.activeElement)&&h.current.focus()},[g]);const x=T$(t?.request.timeoutMs,t?.request.requestId),b=H.useCallback(y=>{!t||o||u.current||(u.current=!0,i(!0),l(!1),_$(t.sessionId,t.request,y).then(()=>{j$()}).catch(()=>{l(!0)}).finally(()=>{u.current=!1,i(!1)}))},[o,t]),S=y=>{if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),b({cancelled:!0});return}if(t){if(t.request.method==="confirm"){if(y.key==="y"||y.key==="Y"){y.preventDefault(),b({confirmed:!0});return}if(y.key==="n"||y.key==="N"){y.preventDefault(),b({confirmed:!1,cancelled:!0});return}}if(t.request.method==="select"){const v=t.request.options??[],C=E$(y.key,d,v.length);if(!C)return;const I=(y.target instanceof HTMLElement?y.target:null)?.getAttribute("role")==="option";if(C.kind==="highlight"){y.preventDefault(),f(C.index),I&&h.current?.querySelectorAll('[role="option"]')[C.index]?.focus();return}if((y.key==="Enter"||y.key===" ")&&!I&&y.target!==y.currentTarget)return;const T=v[C.index];if(T===void 0)return;y.preventDefault(),b({value:T})}}};return!t&&s.length===0?null:c.jsxs("div",{"data-extension-prompt-dock":!0,className:"chat-input-column relative mb-2 flex flex-col gap-2",children:[s.length>0?c.jsx(F$,{sessions:s}):null,t?c.jsxs("div",{ref:h,role:"dialog","aria-label":Nn(t.request.title),"aria-describedby":t.request.message?m:void 0,tabIndex:-1,onKeyDown:S,className:"relative z-40 overflow-hidden rounded-xl border border-border/80 bg-card p-3 shadow-md transition-[opacity,transform] duration-150 outline-none",children:[c.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-2 border-b border-border/40 pb-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx($,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate text-xs font-semibold uppercase tracking-wider text-foreground",children:c.jsx(qt,{text:t.request.title})})]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.queueLength>1&&c.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:["1 of ",t.queueLength]}),x!==null&&c.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",title:`${x}s remaining`,children:[x,"s"]}),c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>b({cancelled:!0}),className:"h-6 px-1.5 typography-micro text-muted-foreground hover:text-foreground","aria-label":"Dismiss extension dialog",children:"Dismiss (Esc)"})]})]}),c.jsxs("div",{className:o?"pointer-events-none opacity-60":void 0,"aria-busy":o||void 0,children:[t.request.method==="select"&&c.jsx(N$,{request:t.request,onRespond:b,messageId:m,highlightedIndex:d,setHighlightedIndex:f}),t.request.method==="confirm"&&c.jsx(L$,{request:t.request,onRespond:b,messageId:m}),(t.request.method==="input"||t.request.method==="editor")&&c.jsx(R$,{request:t.request,onRespond:b,messageId:m}),t.request.method==="form"&&c.jsx(P$,{request:t.request,onRespond:b,messageId:m})]}),a&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:"Could not send the response. Check your connection and try again."})]}):null]})},B$=e=>{const t=e.replace(/[-_]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e},V$=({sessionId:e,className:t})=>{const n=ze(d=>d.selectedSessionId),r=e??n,s=ze(d=>r?d.reducer.bySession.get(r)?.extensionWidgets:void 0,(d,f)=>d===f,r?`session:${r}`:"chrome"),o=H.useMemo(()=>[...s?.entries()??[]],[s]),[i,a]=H.useState({}),l=H.useCallback(d=>{a(f=>({...f,[d]:!f[d]}))},[]);return o.length===0?c.jsxs("div",{className:R("flex h-full flex-col items-center justify-center gap-1.5 p-6 text-center",t),"data-testid":"extensions-surface-empty",children:[c.jsx($,{name:"plug-2","aria-hidden":"true",className:"size-6 text-subtle-foreground"}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"No extension widgets yet"}),c.jsx("p",{className:"max-w-60 typography-micro text-muted-foreground",children:"Widgets that extensions set with ctx.ui.setWidget show up here."})]}):c.jsx("div",{className:R("flex h-full min-h-0 flex-col overflow-y-auto",t),"data-testid":"extensions-surface",children:c.jsx($$,{title:"Widgets",count:o.length,children:o.map(([d,f])=>c.jsx(z$,{title:B$(d),meta:f.placement==="belowEditor"?"below editor":"above editor",collapsed:!!i[d],onToggle:()=>l(d),testId:`extension-widget-${d}`,children:c.jsx("div",{className:"max-h-64 overflow-auto rounded-md bg-muted/40 px-2 py-1.5 font-mono typography-micro leading-relaxed text-foreground",children:f.lines.map((u,h)=>c.jsx("span",{className:"block whitespace-pre-wrap",children:c.jsx(qt,{text:u})},h))})},d))})})},$$=({title:e,count:t,children:n})=>c.jsxs("section",{"aria-label":e,className:"border-t border-border/60 first:border-t-0",children:[c.jsxs("p",{className:"flex items-center gap-1.5 px-3 pb-0.5 pt-1.5 typography-micro font-medium text-muted-foreground",children:[e,c.jsx("span",{className:"tabular-nums text-subtle-foreground",children:t})]}),c.jsx("div",{className:"flex flex-col p-1 pt-0.5",children:n})]}),z$=({title:e,meta:t,collapsed:n,onToggle:r,testId:s,children:o})=>c.jsxs("div",{"data-testid":s,children:[c.jsxs("button",{type:"button",onClick:r,"aria-expanded":!n,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-left hover:bg-interactive-hover",children:[c.jsx("span",{className:"inline-flex w-4 shrink-0 items-center justify-center",children:c.jsx($,{name:n?"arrow-right-s":"arrow-down-s","aria-hidden":"true",className:"size-3.5 text-muted-foreground"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:e,children:e}),t?c.jsx("span",{className:"shrink-0 whitespace-nowrap typography-micro text-muted-foreground",children:t}):null]}),!n&&c.jsx("div",{className:"pb-2 pl-8 pr-2 pt-0.5",children:o})]}),U$=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Uv=({sessionId:e})=>{const t=ze(u=>u.selectedSessionId),n=e??t,{isMobile:r}=Dn(),[s,o]=H.useState(!1),i=ze(u=>[...(n?u.reducer.bySession.get(n):void 0)?.extensionStatuses.entries()??[]],(u,h)=>U$(u.flat(),h.flat()),`session:${n??""}`),{widgetsCount:a,sessionDirectory:l}=ze(u=>{const h=n?u.reducer.bySession.get(n):void 0;return{widgetsCount:h?.extensionWidgets.size??0,sessionDirectory:h?.directory}},(u,h)=>u.widgetsCount===h.widgetsCount&&u.sessionDirectory===h.sessionDirectory,`session:${n??""}`);H.useEffect(()=>{a===0&&o(!1)},[a]);const d=a===0?"":a===1?"1 widget":`${a} widgets`,f=H.useCallback(()=>{if(r){o(h=>!h);return}const u=l||nt.getState().currentDirectory||"";re.getState().openContextSurface(u,"extensions")},[r,l]);return i.length===0&&!d?null:c.jsxs("div",{className:"chat-input-column flex flex-col gap-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 overflow-hidden rounded-full border border-border/40 bg-card px-3 py-1.5 shadow-sm transition-[opacity,transform] duration-150",children:[c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[c.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-full bg-interactive-hover text-muted-foreground",children:c.jsx($,{name:"plug-2",className:"size-3"})}),i.length>0&&c.jsx("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hidden touch-pan-x","data-no-drawer-swipe":"true",children:i.map(([u,h])=>c.jsx("span",{className:"inline-flex shrink-0 items-center whitespace-nowrap rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-foreground",children:c.jsx(qt,{text:h})},u))})]}),d&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:f,"aria-label":"Open extensions panel","aria-expanded":r?s:void 0,className:"shrink-0 gap-1 rounded-full border border-border/50 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground active:bg-interactive-active",children:[c.jsx($,{name:"layout-right",className:"size-3"}),c.jsx("span",{children:d})]})]}),r&&s&&c.jsx("div",{className:"max-h-60 overflow-y-auto rounded-xl border border-border/80 bg-card p-2 shadow-md",children:c.jsx(V$,{sessionId:n,className:"h-auto"})})]})},q$=({sessionId:e})=>{const t=re(r=>r.commandTriggers),n=p.useCallback((r,s)=>{e&&qe().prompt(e,P5(r,s),"prompt").catch(()=>{})},[e]);return!e||t.length===0?null:c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-1.5 px-1",role:"toolbar","aria-label":"Command triggers",children:t.map(r=>c.jsx(be,{size:"xs",variant:"outline",disabled:!e,onClick:()=>n(r.command,r.args),title:r.combo?`${r.label} (${kC(r.combo)})`:r.label,children:r.label},r.id))})},W$=e=>[...e.key].length!==1?!1:e.getModifierState?.("AltGraph")===!0?!0:e.ctrlKey&&e.altKey&&!/^[a-z]$/i.test(e.key),K$={ArrowUp:"\x1B[A",ArrowDown:"\x1B[B",ArrowRight:"\x1B[C",ArrowLeft:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",Insert:"\x1B[2~",Delete:"\x1B[3~",PageUp:"\x1B[5~",PageDown:"\x1B[6~"},X4=e=>{const{key:t,ctrlKey:n,altKey:r,metaKey:s,shiftKey:o}=e;if(s)return null;if(W$(e))return t;if(t==="Enter")return!n&&!o?r?"\x1B\r":"\r":`\x1B[13;${1+(o?1:0)+(r?2:0)+(n?4:0)}u`;if(t==="Escape")return"\x1B";if(t==="Tab")return o?"\x1B[Z":" ";if(t==="Backspace")return r?"\x1B":"";const i=K$[t];if(i){if(!n&&!r&&!o)return i;const a=1+(o?1:0)+(r?2:0)+(n?4:0),l=i.at(-1);return l==="~"?i.replace("~",`;${a}~`):`\x1B[1;${a}${l}`}if([...t].length!==1)return null;if(n){const a=t.toLowerCase().charCodeAt(0);return a>=97&&a<=122?(r?"\x1B":"")+String.fromCharCode(a-96):t===" "||t==="@"?"\0":t==="["?"\x1B":t==="\\"?"":t==="]"?"":t==="_"||t==="-"?"":null}return r?`\x1B${t}`:t},qv="\x1B[200~",Wv="\x1B[201~",G$=e=>{const t=e.split(qv).join("").split(Wv).join("");return`${qv}${t}${Wv}`},Z$=e=>{let n=e.action==="wheel-up"||e.action==="wheel-down"?e.action==="wheel-up"?64:65:Math.min(Math.max(e.button,0),2);e.action==="drag"&&(n+=32),e.shiftKey&&(n+=4),e.altKey&&(n+=8),e.ctrlKey&&(n+=16);const r=Math.max(0,Math.floor(e.col))+1,s=Math.max(0,Math.floor(e.row))+1;return`\x1B[<${n};${r};${s}${e.action==="release"?"m":"M"}`},Kv=(e,t)=>{const n=[...e],r=[...t];let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return"".repeat(n.length-s)+r.slice(s).join("").replace(/\r?\n/g,"\r")},Y$=256,W1=64*1024,ju=xb,Pn=new Map,K1=new Set,X$=(e,t)=>e!==void 0&&e.columns===t.columns&&e.screenColumns===t.screenColumns&&e.rows===t.rows,J4=e=>e instanceof at&&e.code==="EXTENSION_SURFACE_NOT_OPEN",Ya=()=>({runtimeKey:Y()}),Q4=(e,t,n)=>{Ie.sendExtensionSurface("viewport",{sessionId:e,clientId:ju(),viewport:t,...n?{claim:!0}:{}},Ya()).catch(()=>{Pn.delete(e)})},J$=(e,t)=>{const n=K1.delete(e);!n&&X$(Pn.get(e),t)||(Pn.set(e,t),Q4(e,t,n))},e7=e=>{const t=Pn.get(e);t?Q4(e,t,!0):K1.add(e)},Q$=e=>{Pn.delete(e),K1.delete(e)},G1=Symbol("esc-press"),Jp=new Map,ez=e=>{const t=[];let n=0;for(;e.length>0&&t.length<Y$;){const r=e[0];if(r===G1||t.length>0&&n+r.length>W1)break;e.shift(),t.push(r),n+=r.length}return t},tz=(e,t)=>Ie.sendExtensionSurface("close",{sessionId:e,surfaceId:t,clientId:ju(),...Pn.has(e)?{viewport:Pn.get(e)}:{}},Ya()),nz=async(e,t,n)=>{n.inFlight=!0;try{for(;n.pending.length>0;){const r=n.pending[0]===G1;r&&n.pending.shift();const s=r?[]:ez(n.pending);try{r?await tz(e,t):await Ie.sendExtensionSurface("input",{sessionId:e,surfaceId:t,clientId:ju(),...Pn.has(e)?{viewport:Pn.get(e)}:{},items:s},Ya())}catch(o){n.pending.length=0,J4(o)?qe().dropExtensionSurface(e,t):r?Ce.error("Esc may not have reached the extension. Check it before you press Esc again."):Ce.error("Keys did not reach the extension. Try again.")}}}finally{n.inFlight=!1,Jp.delete(`${e}\0${t}`)}},t7=(e,t,n)=>{const r=`${e}\0${t}`;let s=Jp.get(r);s||(s={pending:[],inFlight:!1},Jp.set(r,s)),s.pending.push(...n),s.inFlight||nz(e,t,s)},Ul=(e,t,n)=>{const r=n.filter(s=>s.length>0&&s.length<=W1);r.length!==0&&t7(e,t,r)},Ki=new Set,rz=256,sz=e=>e.reason==="cancelled"&&!e.surface.parentId&&!Ki.has(`${e.sessionId}\0${e.surface.surfaceId}`),oz=(e,t)=>{Ki.add(`${e}\0${t}`),Ki.size>rz&&Ki.delete(Ki.values().next().value),t7(e,t,[G1])},Gv=async(e,t)=>{try{await Ie.sendExtensionSurface("focus",{sessionId:e,surfaceId:t,clientId:ju(),...Pn.has(e)?{viewport:Pn.get(e)}:{}},Ya())}catch(n){if(J4(n))return;Ce.error("Could not switch to that panel. Try again.")}},bh=new Set,iz=(e,t)=>{const n=`${e}\0${t}`;bh.has(n)||(bh.add(n),Ie.sendExtensionSurface("refresh",{sessionId:e,surfaceId:t},Ya()).catch(()=>{}).finally(()=>bh.delete(n)))},az=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Left",data:"\x1B[D",icon:"arrow-left"},{label:"Up",data:"\x1B[A",icon:"arrow-up"},{label:"Down",data:"\x1B[B",icon:"arrow-down"},{label:"Right",data:"\x1B[C",icon:"arrow-right"},{label:"Enter",data:"\r"}],no=" ",n7=({sessionId:e,surfaceId:t,className:n})=>{const r=H.useRef(null),s=H.useRef(""),[o,i]=H.useState(!1),a=u=>{u&&Ul(e,t,[u])},l=()=>{s.current="";const u=r.current;u&&(u.value=no,u.setSelectionRange(no.length,no.length))},d=u=>{const h=u.currentTarget,m=u.nativeEvent.isComposing;if(!h.value.startsWith(no)){a(Kv(s.current,"")+(h.value===""?"":h.value)),l();return}const g=h.value.slice(no.length);a(Kv(s.current,g)),s.current=g,m||l()},f=u=>{if(u.nativeEvent.isComposing||u.key==="Unidentified"||[...u.key].length===1)return;const h=X4(u);h!==null&&(u.preventDefault(),a(h))};return c.jsxs("div",{role:"toolbar","aria-label":"Extension keys",className:R("relative flex items-center gap-0.5 overflow-x-auto",n),children:[az.map(u=>c.jsx(be,{type:"button",variant:"outline",size:"xs",className:R("shrink-0 font-sans",u.icon?"h-7 w-6 px-0 has-[>svg]:px-0":"h-7 px-1.5"),"aria-label":u.icon?u.label:void 0,onPointerDown:h=>h.preventDefault(),onClick:()=>a(u.data),children:u.icon?c.jsx($,{name:u.icon,className:"size-3.5"}):u.label},u.label)),c.jsx(be,{type:"button",variant:"chip",size:"xs",className:"ml-auto h-7 shrink-0 px-1.5 font-sans","aria-pressed":o,onPointerDown:u=>u.preventDefault(),onClick:()=>{o?r.current?.blur():r.current?.focus({preventScroll:!0})},children:"Keyboard"}),c.jsx("input",{ref:r,"aria-label":"Type to the extension",className:"pointer-events-none absolute left-0 top-0 size-px opacity-0",defaultValue:no,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"enter",onFocus:()=>{l(),i(!0)},onBlur:()=>i(!1),onInput:d,onCompositionEnd:l,onKeyDown:f})]})},cz=.5,r7=(e,t)=>{const n=[1];return e.width>0&&t.width>0&&n.push(t.width/e.width),e.height&&t.height&&e.height>0&&t.height>0&&n.push(t.height/e.height),Math.max(cz,Math.min(...n))},s7=(e,t,n=!0)=>{const[r,s]=H.useState({width:0,height:0,cell:0});return H.useEffect(()=>{const o=e.current;if(!o)return;const i=()=>{const l=o.clientWidth,d=o.clientHeight,f=(t.current?.getBoundingClientRect().width??0)/10;s(u=>u.width===l&&u.height===d&&u.cell===f?u:{width:l,height:d,cell:f})};i();const a=new ResizeObserver(i);return a.observe(o),()=>a.disconnect()},[e,t,n]),r},ji=(e,t,n,r)=>({col:Math.min(Math.max(Math.floor((n-t.left)/Math.max(e.cellWidth,1)),0),Math.max(e.columns-1,0)),row:Math.min(Math.max(Math.floor((r-t.top)/e.lineHeight),0),Math.max(e.rows-1,0))}),Rd=5,lz=10,dz=(e,t,n,r)=>{const s=e.deltaMode===1?e.deltaY:e.deltaMode===2?e.deltaY*r:e.deltaY/n,o=t+s,i=Math.trunc(o);return{steps:Math.max(-Rd,Math.min(Rd,i)),rest:i===0?o:0}},wh={shiftKey:!1,altKey:!1,ctrlKey:!1},uz=e=>{const t=H.useRef(e);t.current=e;const n=H.useRef(null),r=H.useRef(0),s=(x,b,S,y)=>{t.current.send(Z$({action:x,button:b,...S,shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.ctrlKey}))},o=(x,b,S)=>{for(let y=0;y<Math.abs(x);y+=1)s(x<0?"wheel-up":"wheel-down",0,b,S)},i=()=>({columns:t.current.columns,rows:t.current.rows,cellWidth:t.current.measureCell(),lineHeight:t.current.lineHeight}),a=()=>t.current.rows===0||t.current.columns===0,l=x=>x.target instanceof Element&&x.target.closest("a[href]")!==null,d=x=>!x.shiftKey&&x.button<=2&&!a()&&!l(x),f=x=>{const b=t.current.ref.current;if(!b||n.current)return;if(x.pointerType==="touch"){if(a()||l(x))return;const w=b.getBoundingClientRect();n.current={kind:"touch",pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,lastY:x.clientY,swiping:!1,rest:0,cell:ji(i(),{left:w.left,top:w.top},x.clientX,x.clientY)};return}if(!d(x))return;const S=b.getBoundingClientRect(),y={left:S.left,top:S.top},v=i(),C=ji(v,y,x.clientX,x.clientY);n.current={kind:"mouse",pointerId:x.pointerId,button:x.button,...C,grid:v,origin:y},b.setPointerCapture?.(x.pointerId),t.current.onPress?.(),s("press",x.button,C,x)},u=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(b.kind==="touch"){if(!b.swiping){if(Math.hypot(x.clientX-b.startX,x.clientY-b.startY)<lz)return;if(t.current.nativeTouchScroll){n.current=null;return}b.swiping=!0}const y=b.rest+b.lastY-x.clientY;b.lastY=x.clientY;const v=Math.trunc(y/t.current.lineHeight);b.rest=y-v*t.current.lineHeight,o(Math.max(-Rd,Math.min(Rd,v)),b.cell,wh);return}const S=ji(b.grid,b.origin,x.clientX,x.clientY);S.col===b.col&&S.row===b.row||(b.col=S.col,b.row=S.row,s("drag",b.button,S,x))},h=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(n.current=null,b.kind==="touch"){if(x.type!=="pointerup"||b.swiping)return;t.current.onPress?.(),s("press",0,b.cell,wh),s("release",0,b.cell,wh);return}const S=x.type==="pointercancel"?b:ji(b.grid,b.origin,x.clientX,x.clientY);s("release",b.button,{col:S.col,row:S.row},x)},m=x=>{d(x)&&x.preventDefault()},g=H.useRef({wheel:o,grid:i,empty:a});return g.current={wheel:o,grid:i,empty:a},H.useEffect(()=>{const x=e.ref.current;if(!x)return;const b=S=>{const{wheel:y,grid:v,empty:C}=g.current;if(S.shiftKey||S.deltaY===0||C())return;S.preventDefault();const{steps:w,rest:I}=dz(S,r.current,t.current.lineHeight,t.current.rows);if(r.current=I,w===0)return;const E=x.getBoundingClientRect();y(w,ji(v(),{left:E.left,top:E.top},S.clientX,S.clientY),S)};return x.addEventListener("wheel",b,{passive:!1}),()=>x.removeEventListener("wheel",b)},[e.ref]),{onPointerDown:f,onPointerMove:u,onPointerUp:h,onPointerCancel:h,onMouseDown:m,touchAction:e.nativeTouchScroll?"pan-y":"none"}},fz="▀",hz="▄",pz="█",mz=/[▀▄█]/,gz=/^([▀▄█])\1*$/,yz=/([▀▄█])\1*|[^▀▄█]+/g,vz=e=>mz.test(e),o7=e=>gz.test(e),xz=e=>(e.match(yz)??[]).map(t=>({text:t,block:o7(t)})),Zv=(e,t,n)=>{const{color:r,backgroundColor:s,...o}=t??{},i=String(r??"var(--foreground)"),a=String(s??"transparent"),l=e[0];return{...o,display:"inline-block",width:`${e.length}ch`,height:n,verticalAlign:"top",color:"transparent",backgroundColor:l===pz?i:a,backgroundImage:l===fz?`linear-gradient(${i} 50%, ${a} 50%)`:l===hz?`linear-gradient(${a} 50%, ${i} 50%)`:"none"}},Ft=18,Ko=12,bz=24,i7=3,Go="font-mono text-[13px] leading-[18px] [font-variant-ligatures:none]",a7=[],c7=e=>ze(t=>e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0,Object.is,e?`session:${e}`:"*",e??""),l7=e=>{const t=c7(e);return H.useMemo(()=>t?[...t.values()].sort((n,r)=>n.z-r.z):a7,[t])},wz=e=>ze(t=>{const n=t.reducer.bySession.get(e);return n?.lifecycle==="busy"&&!n.runningCommand||n?.lifecycle==="retry"},Object.is,`session:${e}`,e),Gi=e=>{document.querySelector(`[data-extension-surface="${CSS.escape(e)}"]`)?.focus({preventScroll:!0})},Qp=()=>{requestAnimationFrame(()=>{const e=document.activeElement;e&&e!==document.body&&!e.closest('[aria-hidden="true"]')||document.querySelector('[data-chat-input="true"] [contenteditable="true"], .chat-input-column textarea')?.focus()})},Sh=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null,d7=H.memo(({line:e,cells:t})=>{if(e==="")return" ";const n=t&&Sh?t:void 0;if(!n&&!vz(e))return c.jsx(qt,{text:e,links:!0});let r=0;return c.jsx(c.Fragment,{children:U4(e).map((s,o)=>{const i=Nd(s),a=$4(s.href);if(!a&&o7(s.text))return r+=s.text.length,c.jsx("span",{style:Zv(s.text,i,Ft),children:s.text},o);const l=[],d=f=>{for(const u of xz(f))l.push(u.block?c.jsx("span",{style:Zv(u.text,i,Ft),children:u.text},`block-${l.length}`):u.text)};if(!n||!Sh)d(s.text);else{let f="";for(const{segment:u}of Sh.segment(s.text)){const h=n[r++]??1;if(h===1){f+=u;continue}f&&d(f),f="",l.push(c.jsx("span",{className:"inline-block overflow-hidden text-center align-top",style:{width:`${h}ch`,height:Ft},children:h===0?null:u},r))}f&&d(f)}return a?c.jsx(Y4,{segment:s,href:a,children:l},o):c.jsx("span",{style:i,children:l},o)})})});d7.displayName="CellLine";const u7=({sessionId:e,surface:t,nativeTouchScroll:n=!1,scale:r=1,zoomSelf:s=!1})=>{const o=H.useRef(null),i=H.useRef(null),a=t.frame,l=t.capturing||t.focused,d=uz({ref:o,measureCell:()=>(i.current?.getBoundingClientRect().width??0)/10,columns:a?.columns??0,rows:a?.lines.length??0,lineHeight:Ft*r,nativeTouchScroll:n,send:h=>Ul(e,t.surfaceId,[h]),onPress:()=>{l&&o.current?.focus({preventScroll:!0})}});H.useEffect(()=>{!t.focused||!l||!o.current||o.current.contains(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||o.current.focus({preventScroll:!0})},[t.focused,l]);const f=h=>{if(h.nativeEvent.isComposing)return;const m=h.metaKey||h.ctrlKey;if(m&&h.key.toLowerCase()==="c"&&(window.getSelection()?.toString()??"")!==""||m&&h.key.toLowerCase()==="v")return;const g=X4(h);g!==null&&(h.preventDefault(),h.stopPropagation(),Ul(e,t.surfaceId,[g]))},u=h=>{const m=h.clipboardData.getData("text/plain");if(!m)return;h.preventDefault();const g=G$(m);if(g.length>W1){Ce.error("That paste is too long for the extension (64 KB at most).");return}Ul(e,t.surfaceId,[g])};return c.jsxs("div",{ref:o,"data-extension-surface":t.surfaceId,role:"application","aria-label":`Extension: ${t.title}`,tabIndex:l?0:-1,onKeyDown:l?f:void 0,onPaste:l?u:void 0,onPointerDown:h=>{e7(e),d.onPointerDown(h)},onPointerMove:d.onPointerMove,onPointerUp:d.onPointerUp,onPointerCancel:d.onPointerCancel,onMouseDown:d.onMouseDown,style:{touchAction:d.touchAction,...s&&r!==1?{zoom:r}:{}},className:R("relative whitespace-pre text-foreground outline-none",Go),children:[c.jsx("span",{ref:i,"aria-hidden":!0,className:"invisible absolute left-0 top-0",children:"0000000000"}),(a?.lines??[]).map((h,m)=>c.jsx("div",{style:{height:Ft},children:c.jsx(d7,{line:h,cells:a?.cells[m]})},m)),a?.cursor&&t.focused?c.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute bg-foreground/70",style:{left:`${a.cursor.col}ch`,top:a.cursor.row*Ft+1,width:"1ch",height:Ft-2}}):null]})},Z1=({sessionId:e,surface:t})=>{const n=r=>{if(oz(e,t.surfaceId),document.activeElement!==r)return;const s=document.querySelector(`[data-extension-surface="${CSS.escape(t.surfaceId)}"]`);s&&s.tabIndex>=0&&Gi(t.surfaceId)};return c.jsx(be,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 px-1.5 font-sans text-muted-foreground hover:text-foreground","aria-label":`Press Esc in ${t.title}`,title:"Press Esc",onPointerDown:r=>r.preventDefault(),onClick:r=>n(r.currentTarget),children:"Esc"})},Sz=(e,t)=>{const n=t.filter(r=>r.stale).map(r=>r.surfaceId).join("\0");H.useEffect(()=>{if(n)for(const r of n.split("\0"))iz(e,r)},[e,n])},Cz=({sessionId:e})=>{const t=H.useRef(null),n=H.useRef(null),r=Dn().hasTouchOnlyPointer?i7:0;return H.useEffect(()=>{const s=t.current;if(!s)return;const o=s.closest("[data-composer-bound]"),i=()=>{const l=(n.current?.getBoundingClientRect().width??0)/10;!(l>0)||!o||J$(e,{columns:Math.floor(s.clientWidth/l),screenColumns:Math.floor((o.clientWidth-2*Ko)/l),rows:Math.max(1,Math.floor((o.clientHeight-2*Ko)/Ft)-r)})};Q$(e),i();const a=new ResizeObserver(i);return a.observe(s),o&&a.observe(o),()=>a.disconnect()},[e,r]),c.jsx("div",{"aria-hidden":!0,className:"chat-input-column pointer-events-none absolute inset-x-0 top-0 h-0 overflow-hidden",children:c.jsx("div",{className:"mx-px px-3",children:c.jsx("div",{ref:t,className:"relative w-full",children:c.jsx("span",{ref:n,className:R("invisible absolute",Go),children:"0000000000"})})})})},kz=e=>{const[t,n]=H.useState(!1);return H.useEffect(()=>{const r=e.current;if(!r)return;const s=()=>n(r.scrollHeight>r.clientHeight+1);s();const o=new ResizeObserver(s);return o.observe(r),r.firstElementChild&&o.observe(r.firstElementChild),()=>o.disconnect()},[e]),t},Mz=(e,t)=>{const[n,r]=H.useState(void 0);return H.useLayoutEffect(()=>{const s=e.current,o=t.current,i=s?.closest("[data-composer-bound]");if(!s||!o||!i)return;const a=()=>{const d=s.offsetHeight-o.offsetHeight,f=s.parentElement,u=f&&Number.parseFloat(getComputedStyle(f).paddingBottom)||0;r(Math.max(4*Ft,Math.floor(i.clientHeight-d-u-Ko)))};a();const l=new ResizeObserver(a);return l.observe(i),l.observe(s),()=>l.disconnect()},[e,t]),n},Iz=({sessionId:e,surface:t,below:n})=>{const r=wz(e),{hasTouchOnlyPointer:s}=Dn(),o=H.useRef(null),i=H.useRef(null),a=H.useRef(null),l=Mz(o,i),d=kz(i),f=s7(i,a),u=f.cell>0&&t.frame?r7({width:t.frame.columns*f.cell},{width:f.width-bz}):1;return c.jsx("div",{className:"chat-input-column pb-3",children:c.jsxs("div",{ref:o,role:"dialog","aria-label":`Extension: ${t.title}`,className:"pi-surface-rise overflow-hidden rounded-xl border border-border/80 bg-card shadow-md",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/40 px-3 py-1.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx($,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"shrink-0 typography-ui-label font-medium text-foreground",children:t.title}),t.blocked?.message?c.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:t.blocked.message}):null,n>0?c.jsx("span",{className:"shrink-0 rounded-full bg-muted px-2 py-0.5 typography-micro text-muted-foreground",children:n===1?"1 more below":`${n} more below`}):null]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[r?c.jsxs(be,{type:"button",variant:"ghost",size:"xs",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>e1(e),children:[c.jsx($,{name:"stop",className:"size-3.5"}),"Stop"]}):null,c.jsx(Z1,{sessionId:e,surface:t})]})]}),c.jsxs("div",{ref:i,className:"relative overflow-auto px-3 py-2",style:{maxHeight:l??"60vh"},children:[c.jsx(u7,{sessionId:e,surface:t,nativeTouchScroll:d,scale:u,zoomSelf:!0}),c.jsx("span",{ref:a,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",Go),children:"0000000000"})]}),s&&t.capturing?c.jsx(n7,{sessionId:e,surfaceId:t.surfaceId,className:"border-t border-border/40 px-3 py-1.5"}):c.jsx("div",{className:"border-t border-border/40 px-3 py-1.5 typography-micro text-muted-foreground",children:"Keys go to the extension. Your draft is kept when it closes."})]})})},Ez=({sessionId:e,surfaces:t})=>{const n=uu(e)!==null;return t.length===0?null:c.jsx("div",{className:"chat-input-column mb-2 flex flex-col gap-1",children:t.map(r=>c.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg bg-[var(--surface-muted)] px-3 py-1",children:[c.jsxs("span",{className:"min-w-0 typography-meta text-muted-foreground [text-wrap:pretty]",children:[r.hidden?`${r.title} is hidden by the extension.`:`${r.title} is hidden because the screen is too narrow.`,n?" New messages wait until it closes.":null]}),c.jsx(Z1,{sessionId:e,surface:r})]},r.surfaceId))})},_z=e=>{H.useEffect(()=>{if(e)return qe().subscribeExtensionSurfaceDismissals(t=>{t.sessionId!==e||!sz(t)||Ce.info(`${t.surface.title} was closed on another device.`,{id:`extension-surface-closed:${t.surface.surfaceId}`})})},[e])},Yv=({sessionId:e,children:t})=>{_z(e);const n=l7(e),r=n.filter(f=>f.mode==="inline"&&!f.hidden),s=r.at(-1)??null,o=n.filter(f=>f.mode==="overlay"&&!f.parentId&&(f.hidden||f.frame?.visible===!1)),[i,a]=H.useState(!1),[l,d]=H.useState({sessionId:e,hasTop:!!s});return(l.sessionId!==e||l.hasTop!==!!s)&&(d({sessionId:e,hasTop:!!s}),l.sessionId===e&&!s&&a(!0)),H.useEffect(()=>{i&&Qp()},[i]),Sz(e??"",e?n:a7),c.jsxs(c.Fragment,{children:[e&&n.length>0?c.jsx(Cz,{sessionId:e}):null,e?c.jsx(Ez,{sessionId:e,surfaces:o}):null,e&&s?c.jsx(Iz,{sessionId:e,surface:s,below:r.length-1},s.surfaceId):null,c.jsx("div",{hidden:!!s,className:i&&!s?"pi-surface-fade":void 0,onAnimationEnd:f=>{f.target===f.currentTarget&&a(!1)},children:t})]})},Xv=8,jz=2,xo=5,Tz=28-Ko,Y1="rounded-lg border border-border/80 bg-card shadow-md",f7=({sessionId:e,surface:t,scale:n})=>{const r=t.frame?.layout??{width:40,height:1};return c.jsx("div",{className:R(Y1,"max-w-full p-1"),style:n!==1?{zoom:n}:void 0,children:c.jsx("div",{className:"relative overflow-hidden",style:{width:`${r.width}ch`,maxWidth:"100%",height:r.height*Ft},children:c.jsx(u7,{sessionId:e,surface:t,scale:n})})})},h7=e=>({left:`max(0px, min(${e.col}ch, 100% - ${e.width}ch - ${2*xo}px))`,top:`max(0px, min(${e.row*Ft}px, 100% - ${e.height*Ft+2*xo}px))`,maxWidth:"100%"}),Az=({sessionId:e,title:t,members:n,front:r,anchor:s,onPicked:o,scaleFor:i})=>{const a=r.frame?.layout??{width:40,height:1},l={row:s.row,col:s.col,width:a.width,height:a.height},d=n.length>1,f=Math.min(jz,n.length-1),u=l.row<3;return c.jsxs("div",{role:"group","aria-label":`${t} panels`,className:R("absolute isolate pointer-events-auto",Go),style:h7(l),children:[d?c.jsx("div",{role:"tablist","aria-label":`${t} panels`,"data-extension-tabs":!0,onKeyDown:h=>{const m=n.findIndex(x=>x.surfaceId===r.surfaceId),g=h.key==="ArrowRight"?(m+1)%n.length:h.key==="ArrowLeft"?(m-1+n.length)%n.length:h.key==="Home"?0:h.key==="End"?n.length-1:null;g!==null&&(h.preventDefault(),h.currentTarget.querySelectorAll('[role="tab"]')[g]?.focus(),g!==m&&Gv(e,n[g].surfaceId))},className:"absolute left-0 flex max-w-[calc(100vw-2rem)] items-center gap-1 overflow-x-auto rounded-md bg-card p-0.5 font-sans",style:u?{top:"calc(100% + 4px)"}:{bottom:`calc(100% + ${f*Xv+4}px)`},children:n.map((h,m)=>{const g=h.surfaceId===r.surfaceId;return c.jsx(be,{type:"button",variant:"chip",size:"xs",role:"tab","aria-selected":g,tabIndex:g?0:-1,className:R("shrink-0",g&&"bg-interactive-selection text-interactive-selection-foreground"),onMouseDown:x=>x.preventDefault(),onClick:()=>{o(),(!g||!h.focused)&&Gv(e,h.surfaceId)},children:Ov(h,m)},h.surfaceId)})}):null,Array.from({length:f},(h,m)=>{const g=m+1;return c.jsx("div",{"aria-hidden":!0,className:R("absolute inset-0",Y1),style:{zIndex:-g,transform:`translateY(-${g*Xv}px) scale(${1-g*.04})`,transformOrigin:"top center"}},g)}),c.jsx("div",{role:d?"tabpanel":"dialog","aria-label":`Extension: ${t}, ${Ov(r,n.indexOf(r))}`,className:"pi-surface-pop",children:c.jsx(f7,{sessionId:e,surface:r,scale:i(r)})},r.surfaceId)]})},Nz=e=>{const[t,n]=H.useState(FV),r=BV(t,e);return r!==t&&n(r),r},Lz=e=>{const[t,n]=H.useState(e),[r,s]=H.useState([]);if(t!==e){const i=new Set(e.map(l=>l.surfaceId)),a=t.filter(l=>!i.has(l.surfaceId));n(e),(a.length>0||r.some(l=>i.has(l.surfaceId)))&&s([...r.filter(l=>!i.has(l.surfaceId)),...a])}const o=H.useCallback(i=>{s(a=>a.filter(l=>l.surfaceId!==i))},[]);return{leaving:r,finish:o}},Jv=({sessionId:e})=>{const t=c7(e),n=l7(e),r=H.useMemo(()=>n.filter(q4),[n]),s=H.useMemo(()=>HV(r,t?[...t.keys()]:[]),[r,t]),o=Nz(s),i=H.useMemo(()=>s.flatMap(M=>{const L=o.get(M.parentId);return L?[{...M,anchor:L}]:[]}),[s,o]),a=H.useMemo(()=>new Set(i.flatMap(M=>M.members.map(L=>L.surfaceId))),[i]),{leaving:l,finish:d}=Lz(r),f=H.useRef(new Set),u=l.filter(M=>!f.current.has(M.surfaceId)),h=l.filter(M=>f.current.has(M.surfaceId)).map(M=>M.surfaceId).join("\0");H.useEffect(()=>{f.current=a},[a]),H.useEffect(()=>{if(h)for(const M of h.split("\0"))d(M)},[h,d]);const m=r.filter(M=>M.capturing).at(-1)?.surfaceId??null,g=H.useRef(!1);H.useEffect(()=>{m?g.current=!0:g.current&&(g.current=!1,Qp())},[m]);const x=(r.find(M=>M.capturing&&M.focused)??r.filter(M=>M.capturing).at(-1))?.surfaceId??null,b=H.useRef(null),{hasTouchOnlyPointer:S}=Dn(),y=H.useRef(null),v=H.useRef(null),C=s7(y,v,r.length>0||u.length>0),w=M=>{const L=M.frame?.layout;return!L||!(C.cell>0)?1:r7({width:L.width*C.cell+2*xo,height:L.height*Ft+2*xo},{width:C.width,height:C.height})};H.useEffect(()=>{const M=b.current,L=M?.closest("[data-composer-bound]");if(!x||!M||!L)return;const O=U=>U instanceof Element&&U.closest("[data-extension-prompt-dock]")!==null,N=()=>{O(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||Gi(x)},D=requestAnimationFrame(N);let W=null;const z=()=>{W?.disconnect(),W=null},X=()=>{W||(W=new MutationObserver(()=>{const U=document.activeElement;U&&U!==document.body&&U.isConnected||(z(),N())}),W.observe(L,{childList:!0,subtree:!0}))},F=U=>{const P=U.target;if(!(P instanceof Node)||!L.contains(P)||M.contains(P)){z();return}if(O(P)){X();return}z(),N()};return O(document.activeElement)&&X(),document.addEventListener("focusin",F,!0),()=>{cancelAnimationFrame(D),z(),document.removeEventListener("focusin",F,!0)}},[x]);const I=x?null:r.find(M=>!M.capturing&&M.focused)?.surfaceId??null,E=H.useRef(null);if(H.useEffect(()=>{const M=E.current;E.current=I,!(I||!M)&&(document.activeElement?.getAttribute("data-extension-surface")===M&&document.activeElement.blur(),Qp())},[I]),H.useEffect(()=>{const M=b.current,L=M?.closest("[data-composer-bound]");if(!I||!M||!L)return;let O=!1;const N=W=>{W.target instanceof Node&&!M.contains(W.target)&&(O=!0)},D=W=>{const z=W.target;O||!(z instanceof Node)||!L.contains(z)||M.contains(z)||z instanceof Element&&z.closest("[data-extension-prompt-dock]")||Gi(I)};return document.addEventListener("pointerdown",N,!0),document.addEventListener("focusin",D,!0),()=>{document.removeEventListener("pointerdown",N,!0),document.removeEventListener("focusin",D,!0)}},[I]),!e||r.length===0&&u.length===0)return null;const T=r.filter(M=>M.capturing).at(-1)??null,A=x??I,j=S&&A!==null,k=C.height-(j?i7*Ft:0),_=[...r.map(M=>({surface:M,isLeaving:!1})),...u.map(M=>({surface:{...M,focused:!1,capturing:!1},isLeaving:!0}))];return c.jsxs("div",{ref:b,className:"pointer-events-none absolute inset-0 z-30",children:[T?c.jsx("div",{"aria-hidden":!0,className:"pi-surface-fade pointer-events-auto absolute inset-0 bg-background/60",onMouseDown:M=>{M.preventDefault(),e7(e),x&&Gi(x)}}):null,c.jsx("div",{className:"absolute inset-0",style:{padding:Ko},children:c.jsxs("div",{ref:y,className:"relative h-full",children:[c.jsx("span",{ref:v,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",Go),children:"0000000000"}),_.map(({surface:M,isLeaving:L})=>{const O=M.frame?.layout??{row:0,col:0,width:40,height:1};if(!L&&a.has(M.surfaceId)){const N=i.find(W=>W.members.includes(M));if(!N||N.members.some(W=>W.z>M.z))return null;const D=t?.get(N.parentId)?.title??M.title;return c.jsx(Az,{sessionId:e,title:D,members:N.members,front:N.front,anchor:N.anchor,onPicked:()=>{x&&Gi(x)},scaleFor:w},`stack-${N.parentId}`)}return c.jsxs("div",{role:"dialog","aria-label":`Extension: ${M.title}`,"aria-hidden":L||void 0,className:R("absolute",Go,L?"pi-surface-out pointer-events-none":"pi-surface-pop pointer-events-auto"),style:h7(O),onAnimationEnd:L?N=>{N.target===N.currentTarget&&d(M.surfaceId)}:void 0,children:[M.parentId?null:c.jsxs("div",{className:R("absolute flex items-center gap-0.5 rounded-md bg-card pl-2 font-sans",{above:"right-0 -top-7",below:"right-0 -bottom-7",inside:"right-1 top-1 z-10 shadow-sm"}[VV({top:O.row*Ft,layoutHeight:O.height*Ft+2*xo,height:(O.height*Ft+2*xo)*w(M)},k,Tz)]),children:[c.jsx("span",{className:"typography-micro text-muted-foreground",children:M.title}),c.jsx(Z1,{sessionId:e,surface:M})]}),c.jsx(f7,{sessionId:e,surface:M,scale:w(M)})]},M.surfaceId)})]})}),j&&A?c.jsx("div",{className:"pointer-events-auto absolute inset-x-0 bottom-0 flex justify-center",style:{padding:Ko},children:c.jsx(n7,{sessionId:e,surfaceId:A,className:R(Y1,"max-w-full p-1")})}):null]})},Rz=({isNewSession:e=!1})=>{const{currentTheme:t}=vr(),n=t?.colors?.surface?.mutedForeground||"var(--muted-foreground)";return c.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[c.jsx(c1,{width:120,height:120,isAnimated:!e,className:e?"opacity-20":void 0}),e?c.jsx("span",{className:"text-body-md",style:{color:n},children:"Start a new chat"}):null]})},Pz=p.memo(Rz),X1=2,p7=2,Dz=72,Oz=(e,t=X1)=>t+Math.max(0,e),Hz=(e,t,n,r=X1)=>{const s=Oz(n,r);return t<=s?!1:e<t-s},Fz=(e,t,n=X1)=>Math.max(0,t-n-e),Bz=(e,t,n=p7)=>e+Math.max(0,Math.min(n,t)),Vz=({foldedCount:e,onLoadOlder:t,onLoadAll:n})=>{const r=Math.min(p7,e),s=e>r;return c.jsx("div",{className:"chat-message-column flex flex-col items-center py-4",children:c.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[c.jsxs(be,{type:"button",variant:"secondary",size:"sm",onClick:t,"aria-label":"Load older history",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx($,{name:"history",className:"size-3.5"}),"Load older history"]}),s?c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:n,"aria-label":"Load all history",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load all history"}):null]})})},$z=p.memo(Vz),m7="The following tool was executed by the user",J1=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},zz=e=>{const t=e.info;return typeof t.parentID=="string"&&t.parentID.length>0?t.parentID:null},g7=e=>!e||J1(e)!=="user"?!1:e.parts.some(t=>{if(t?.type!=="text")return!1;const n=t.text;return t.synthetic===!0&&typeof n=="string"&&n.trim().startsWith(m7)}),y7=(e,t)=>{if(J1(e)!=="assistant")return{hide:!1,details:null};if(t&&zz(e)!==t)return{hide:!1,details:null};if(e.parts.length!==1)return{hide:!1,details:null};const n=e.parts[0];if(n?.type!=="tool")return{hide:!1,details:null};if((typeof n.tool=="string"?n.tool.toLowerCase():"")!=="bash")return{hide:!1,details:null};const s=typeof n.state?.input?.command=="string"?n.state.input.command:void 0,o=(typeof n.state?.output=="string"?n.state.output:void 0)??(typeof n.state?.metadata?.output=="string"?n.state.metadata.output:void 0),i=typeof n.state?.status=="string"?n.state.status:void 0;return{hide:!0,details:{command:s,output:o,status:i}}},Uz=(e,t)=>{const n=e[t];if(!n)return null;const r=n.info.id;for(let s=t+1;s<e.length;s+=1){const o=e[s];if(J1(o)==="user")break;const{hide:i,details:a}=y7(o,r);if(i){const l=typeof a?.command=="string"?a.command.trim():"";return l.length>0?l:null}}return null},Ds=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},qz=e=>e.info.error?.name==="SessionRetry",Wz=e=>{const t=e.text;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""},Kz=e=>{if(!e)return null;const t=e.info.id;return typeof t=="string"&&t.trim().length>0?t:null},Gz=e=>{const t=e.info.parentID;return typeof t=="string"&&t.trim().length>0?t:null},Zz=(e,t)=>{if(Ds(e)!=="system")return e;const r=Gz(e);return!r||!t.has(r)||e.info.clientRole==="assistant"?e:{...e,info:{...e.info,clientRole:"assistant"}}},Yz=e=>!e||Ds(e)!=="user"?!1:e.parts.some(t=>t?.type==="subtask"),Xz=e=>{const t=e,n=t.state?.metadata,r=(typeof n?.sessionID=="string"&&n.sessionID.trim().length>0?n.sessionID.trim():null)??(typeof n?.sessionId=="string"&&n.sessionId.trim().length>0?n.sessionId.trim():null);if(r)return r;const s=t.state?.output;if(typeof s=="string"){const o=s.match(/task_id\s*:\s*([^\s<"']+)/i);if(o?.[1])return o[1]}return null},Jz=e=>{if(Ds(e)!=="assistant")return{hide:!1,taskSessionId:null};if(e.parts.length!==1)return{hide:!1,taskSessionId:null};const t=e.parts[0];return t?.type!=="tool"?{hide:!1,taskSessionId:null}:(typeof t.tool=="string"?t.tool.toLowerCase():"")!=="task"?{hide:!1,taskSessionId:null}:{hide:!0,taskSessionId:Xz(e.parts[0])}},Qz=(e,t)=>{if(!t)return e;const n=e.parts.map(r=>{if(r?.type!=="subtask")return r;const s=r.taskSessionID;return typeof s=="string"&&s.trim().length>0?r:{...r,taskSessionID:t}});return{...e,parts:n}},eU=(e,t)=>{const n=typeof t?.command=="string"?t.command.trim():"",r=typeof t?.output=="string"?t.output:"",s=typeof t?.status=="string"?t.status.trim():"",o=[];let i=!1;for(const a of e.parts){if(!i&&a?.type==="text"){const l=a.text;if(a.synthetic===!0&&typeof l=="string"&&l.trim().startsWith(m7)){o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),i=!0;continue}}o.push(a)}return i||o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),{...e,parts:o}},Ch=(e,t)=>t?e.userMessage.info.id===t?!0:e.assistantMessages.some(n=>n.info.id===t):!1,tU=40,nU=40,rU=(e,t)=>{const n=e.reduce((a,l)=>a+(l.kind==="tool"?1:0),0),r=Math.max(0,t),s=Math.max(0,n-r);if(s===0)return{activities:e,hiddenToolCount:0};let o=s,i=0;for(let a=0;a<e.length&&!(e[a]?.kind==="tool"&&(o-=1,i=a+1,o===0));a+=1);return{activities:e.slice(i),hiddenToolCount:s}},sU=(e,t,n,r)=>n&&!r&&e.length>t.length?e:t,Q1=({text:e,isStreaming:t,identityKey:n,allowTextReplacement:r=!1})=>{const s=p.useRef(n),o=p.useRef(e);if(s.current!==n)return s.current=n,o.current=e,e;if(!t)return o.current=e,e;const i=sU(o.current,e,!0,r);return o.current=i,i},oU=e=>e.isStreaming?e.throttledTextContent:e.textContent,iU=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,aU=({part:e,messageId:t,streamPhase:n,onShowPopup:r,withinActivityRail:s=!1})=>{const o=e,i=typeof o.text=="string"?o.text:"",a=typeof o.content=="string"?o.content:"",l=typeof o.value=="string"?o.value:"",d=[i,a,l].reduce((y,v)=>v.length>y.length?v:y,""),h=n==="streaming"||n==="cooldown";js("ui.assistant_text_part.render"),h&&js("ui.assistant_text_part.render.streaming");const m=Q1({text:d,isStreaming:h,identityKey:`${t}:${e.id??"text"}`}),g=oU({textContent:d,throttledTextContent:m,isStreaming:h});MC("ui.assistant_text_part.display_len",g.length);const x=o.time,b=!!(x&&typeof x.end<"u");return!(e.type==="text"||e.type==="reasoning")||!iU({displayTextContent:g,isFinalized:b})?null:c.jsx("div",{className:R("group/assistant-text relative w-full min-w-0 break-words",s?"py-1":"pt-3 pb-1"),"data-chat-activity-text":s?"true":void 0,"data-chat-assistant-text":"true",children:c.jsx(qo,{content:g,part:e,messageId:t,isAnimated:!1,isStreaming:h,variant:e.type==="reasoning"?"reasoning":"assistant",enableFileReferences:b,onShowPopup:r})},e.id||`${t}-text`)},v7=p.memo(aU),Qv=300*1e3,Pd=({active:e,minDurationMs:t=300,className:n,children:r,style:s,title:o})=>{const i=p.useRef(e?Date.now():null),[a,l]=p.useState(e),d=p.useRef(null);e&&i.current===null&&(i.current=Date.now()),p.useEffect(()=>{if(e){if(d.current!==null&&(clearTimeout(d.current),d.current=null),i.current===null&&(i.current=Date.now()),Date.now()-i.current>=Qv){l(!1),i.current=null;return}l(!0);return}if(!a){i.current=null;return}const u=i.current??Date.now(),h=Date.now()-u;if(h>=Qv){l(!1),i.current=null;return}const m=Math.max(0,t-h);return d.current=setTimeout(()=>{l(!1),i.current=null,d.current=null},m),()=>{d.current!==null&&(clearTimeout(d.current),d.current=null)}},[e,t,a]);const f=p.useMemo(()=>{if(!a)return s;if(!s)return;const u={...s};return delete u.color,u},[a,s]);return c.jsxs("span",{className:R("transition-opacity duration-200",a&&"oc-shimmer-verb",n),style:f,title:o,children:[r,a&&typeof r=="string"?c.jsx(j3,{text:r}):null]})},cU="!text-[length:var(--text-markdown)] !leading-5 tracking-normal",Gr=R("typography-markdown font-medium",cU),Mt=R("typography-code font-mono","!text-[length:var(--text-code)] !leading-5 tracking-normal"),em={...IC.getCollapsedStyles(),padding:0,overflow:"visible"},ex={style:{background:"transparent",backgroundColor:"transparent"}},x7={color:"var(--status-error)"},b7={color:"var(--tools-icon)"},w7={color:"var(--status-error)"},ei={color:"color-mix(in srgb, var(--tools-title) 72%, var(--tools-description))"},mQ=`
144
- [data-diff-header],
145
- [data-diff] {
146
- [data-separator] {
147
- height: 24px !important;
148
- }
149
- }
150
- `,gQ={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},lU=e=>typeof e!="string"||e.trim().length===0?"":e.split(`
151
- `).map(t=>t.replace(/^>\s?/,"").trimEnd()).filter(t=>t.trim().length>0).join(`
152
- `).trim(),kh=80,dU=40,tx=4e3,uU=200,fU={duration:.2,ease:"easeOut"},S7=e=>e.replace(/<!--\s*-->/g,"").replace(/```[\w]*\n?([\s\S]*?)```/g,(t,n)=>n.trim()).replace(/`([^`]+)`/g,"$1").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^>\s?/gm,"").replace(/^[-*_]{3,}\s*$/gm,"").trim(),C7=e=>{if(e.length<=kh)return e;const t=e.lastIndexOf(" ",kh),n=t>0?t:kh;return`${e.substring(0,n).trimEnd()}…`},hU=e=>{if(!e)return"";const t=S7(e).replace(/\s+/g," ").trim();return C7(t)},pU=e=>{const t=e.trimEnd();if(!t)return"";const n=t.lastIndexOf(`
153
- `),r=n===-1?t:t.slice(n+1);return C7(S7(r).replace(/\s+/g," ").trim())},mU=e=>{let t=1,n=0;for(let s=e.length-1;s>=0;s-=1)if(e.charCodeAt(s)===10&&(t+=1,t>dU)){n=s+1;break}const r=n>0?e.slice(n):e;return r.length<=tx?r:r.slice(-tx)},gU=({text:e,variant:t,onContentChange:n,blockId:r,isStreaming:s=!1,actions:o,withinActivityRail:i=!1})=>{const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(null),h=p.useRef(!0),m=p.useId(),g=p.useRef(s),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(n);y.current=n;const v=p.useMemo(()=>s?pU(e):hU(e),[s,e]),C=a?"Collapse reasoning trace":"Expand reasoning trace",w=p.useCallback(()=>{f(!0),l(j=>!j),n?.("structural")},[n]),I=p.useCallback(j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),w())},[w]),E=p.useCallback(j=>{j.deltaY<0&&(h.current=!1)},[]),T=p.useCallback(j=>{const k=j.currentTarget;h.current=k.scrollHeight-k.scrollTop-k.clientHeight<=2},[]);if(p.useLayoutEffect(()=>{if(!s||!a){h.current=!0;return}const j=u.current;!j||!h.current||(j.scrollTop=j.scrollHeight)},[a,s,e]),p.useEffect(()=>{if(a){f(!0);return}if(!d)return;if(typeof window>"u"){f(!1);return}const j=window.setTimeout(()=>{f(!1)},uU);return()=>{window.clearTimeout(j)}},[a,d]),p.useLayoutEffect(()=>{const j=x.current;if(!j)return;if(b.current?.stop(),!S.current){S.current=!0,j.style.height=a?"auto":"0px",j.style.overflow=a?"visible":"hidden";return}j.style.overflow="hidden",a?j.style.height="0px":(j.style.height=`${j.scrollHeight}px`,y.current?.("animation"));const k=H8(j,{height:a?"auto":"0px"},fU);return b.current=k,k.finished.then(()=>{b.current===k&&(b.current=null,a?(j.style.overflow="visible",j.style.height="auto"):j.style.overflow="hidden")}).catch(()=>{}),()=>{k.stop(),b.current===k&&(b.current=null)}},[a]),p.useEffect(()=>()=>{b.current?.stop(),b.current=null},[]),!e||e.trim().length===0)return null;const A=c.jsxs(c.Fragment,{children:[c.jsx("div",{"data-message-text-export-source":"true",children:s?c.jsx("div",{className:"markdown-content markdown-reasoning w-full min-w-0 whitespace-pre-wrap break-words",children:mU(e)}):c.jsx(qo,{content:e,messageId:r,isAnimated:!1,isStreaming:!1,variant:"reasoning"})}),o?c.jsx("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5","data-message-actions":"true",children:c.jsx("div",{className:"flex items-center gap-1.5","data-message-action-group":"true",children:o})}):null]});return c.jsxs("div",{"data-reasoning-block-id":r,"data-message-text-export-root":"true",className:g.current?"oc-step-in":void 0,children:[c.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":a,"aria-controls":m,"aria-label":C,className:R("group/tool flex items-center gap-1.5 py-1 pr-2 pl-px cursor-pointer"),"data-chat-activity-row":"true",onClick:w,onKeyDown:I,children:[c.jsxs("div",{className:"flex h-5 items-center gap-1.5 flex-shrink-0",children:[c.jsxs("div",{className:"relative flex h-5 w-3.5 items-center justify-center",children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",a&&"opacity-0",!a&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",a&&"opacity-100",!a&&"opacity-0 group-hover/tool:opacity-100"),style:{color:"var(--tools-icon)"},children:a?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx(Pd,{active:s,className:R("flex h-5 items-center typography-markdown font-medium text-[length:var(--text-markdown)] leading-none tracking-normal"),style:ei,title:t==="justification"?"Justification":"Thinking",children:t==="justification"?"Justification":"Thinking"})]}),!a&&v?c.jsx("span",{className:R("flex h-5 flex-1 items-center min-w-0 truncate typography-code font-mono text-[length:var(--text-code)] leading-none tracking-normal"),style:{color:"var(--tools-description)",opacity:.8},title:v,children:v}):null]}),d?c.jsx("div",{ref:x,id:m,"aria-hidden":!a,style:{height:a?"auto":"0px",overflow:a?"visible":"hidden",overflowAnchor:"none"},children:c.jsxs("div",{className:R("relative pt-0.5",i?"pl-0 pb-0":"ml-2 pl-3 pb-1"),style:{opacity:a?1:0,transform:a?"translateY(0)":"translateY(-4px)",transition:"opacity 180ms ease-out, transform 180ms ease-out"},children:[i?null:c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsx(Yn,{ref:u,as:"div",outerClassName:"oc-reasoning-scroll max-h-80 w-full min-w-0",className:"p-0",useScrollShadow:!0,scrollShadowSize:36,userIntentOnly:!0,onWheelCapture:s?E:void 0,onScroll:s?T:void 0,children:A})]})}):null]})},yU=p.memo(({part:e,onContentChange:t,messageId:n,streamPhase:r,withinActivityRail:s=!1})=>{const o=e,i=o.text||o.content||"",a=p.useMemo(()=>lU(i),[i]),l=o.time,f=(r===void 0||r!=="completed")&&o.streaming===!0&&typeof l?.end!="number",u=Q1({text:a,isStreaming:f,identityKey:`${n}:${e.id??"reasoning"}`});return!u||u.trim().length===0?null:c.jsx(gU,{text:u,variant:"thinking",onContentChange:t,blockId:e.id||`${n}-reasoning`,time:l,isStreaming:f,withinActivityRail:s})}),nx=[{variant:"static",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:t,children:e})},{variant:"generate-effect",component:({children:e,className:t,...n})=>{if(e===null||typeof e>"u")return null;const r=typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(s=>typeof s=="string"||typeof s=="number"?String(s):"").join(""):"";return r?c.jsx("span",{className:R("inline-block align-baseline",t),children:r.split("").map((s,o)=>H.createElement(Ec.span,{...n,key:s+String(o),className:R("inline-block whitespace-pre align-baseline"),initial:{opacity:0},animate:{opacity:1},transition:{ease:"easeOut",duration:.14,delay:Math.min(o*.0045,.14)}},s))}):null}},{variant:"glitch",component:({children:e,className:t,...n})=>c.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[c.jsx("span",{...n,className:R("invisible",t),children:e}),c.jsx("span",{...n,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",t),children:e}),c.jsx("span",{...n,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",t),children:e})]})},{variant:"hover-enter",component:({children:e,className:t,...n})=>{if(typeof e!="string")return null;const r=.25,s=.025,o=e.split("").map(i=>i===" "?" ":i);return c.jsxs(Ec.span,{...n,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",t),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[c.jsx("div",{children:o.map((i,a)=>c.jsx(Ec.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))}),c.jsx("div",{className:R("absolute inset-0"),children:o.map((i,a)=>c.jsx(Ec.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))})]})}},{variant:"shake",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:R("text-primary-muted hover:animate-text-shake",t),children:e})},{variant:"hover-decoration",component:({children:e,className:t,...n})=>c.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:c.jsx("span",{...n,className:R("text-primary-muted",t),children:e})})}];function mr({variant:e="static",className:t,...n}){const s=nx.find(o=>o.variant===e)?.component||nx[0].component;return c.jsx(s,{...n,className:t})}const vU=600*1e3,tm=new Map,xU=e=>{const t=Wt(e);if(!t)return;const n=tm.get(t);if(n){if(n.expiresAt<=Date.now()){tm.delete(t);return}return n.outsideFileGrant}},rx=(e,t,n)=>{const r=Wt(e);!r||!t||tm.set(r,{outsideFileGrant:t,expiresAt:Date.now()+vU})},bU=async(e,t)=>{const n=Wt(e);if(!n||!t||Mu(n,t))return;const r=xU(n);if(r)return r;const s=await EC(n);if(!(!s.success||!s.path||!s.outsideFileGrant))return rx(s.path,s.outsideFileGrant),Wt(s.path)!==n&&rx(n,s.outsideFileGrant),s.outsideFileGrant},k7=(e,t)=>{const n=e.trim();if(n){if(Hr.getState().setSelectedSkill(n),re.getState().setSettingsPage("skills.installed"),t){t.openSettings("skills.installed");return}re.getState().setSettingsDialogOpen(!0)}},sx=e=>{if(!e)return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null},ox=e=>{const t=e?.state?.status;return typeof t=="string"?t:null},ix=e=>e?.state,ax=e=>e?.metadata,al=e=>{const t=e?.time;return{start:typeof t?.start=="number"?t.start:null,end:typeof t?.end=="number"?t.end:null}},cx=e=>{const t=e;if(!t)return"";const n=typeof t.text=="string"?t.text:"",r=typeof t.content=="string"?t.content:"",s=typeof t.value=="string"?t.value:"";return[n,r,s].reduce((o,i)=>i.length>o.length?i:o,"")},Tu=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.type!==s.type)return!1;const o=sx(r),i=sx(s);if(o!==i)return!1;if(r.type==="tool"){if(ix(r)!==ix(s)||ax(r)!==ax(s)||ox(r)!==ox(s))return!1;const d=al(r),f=al(s);if(d.start!==f.start||d.end!==f.end)return!1;const u=r.tool,h=s.tool;if(u!==h)return!1;const m=r.output,g=s.output;if(m!==g)return!1;continue}const a=al(r),l=al(s);if(a.start!==l.start||a.end!==l.end)return!1;if(r.type==="file"){const d=r,f=s;if(d.filename!==f.filename||d.mime!==f.mime||d.url!==f.url||d.size!==f.size)return!1}if(r.type==="text"||r.type==="reasoning"){if(cx(r)!==cx(s))return!1;const d=r.shellAction,f=s.shellAction;if((d||f)&&(d?.command!==f?.command||d?.output!==f?.output||d?.status!==f?.status))return!1}}return!0},M7=(e,t)=>e===t?!0:e.id===t.id&&e.role===t.role&&e.sessionID===t.sessionID&&e.finish===t.finish&&e.status===t.status&&e.mode===t.mode&&e.agent===t.agent&&e.providerID===t.providerID&&e.modelID===t.modelID&&e.variant===t.variant&&e.clientRole===t.clientRole&&e.userMessageMarker===t.userMessageMarker&&(e.time?.created??null)===(t.time?.created??null)&&(e.time?.completed??null)===(t.time?.completed??null)&&e.render===t.render&&e.bashExecution===t.bashExecution,I7=(e,t)=>M7(e.info,t.info)&&e.info.error===t.info.error&&Tu(e.parts,t.parts),Dd=(e,t)=>e===t?!0:!e||!t?!1:M7(e.info,t.info),wU=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files,SU=(e,t)=>{if(e===t)return!0;if(!e||!t)return!e&&!t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.file!==s.file||r.additions!==s.additions||r.deletions!==s.deletions)return!1}return!0},eg=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Tu([e.part],[t.part]),CU=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.messageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.messageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!eg(o,i))return!1;r+=1,s+=1}},kU=(e,t)=>{if(e.id!==t.id||e.anchorMessageId!==t.anchorMessageId||e.afterToolPartId!==t.afterToolPartId||e.parts.length!==t.parts.length)return!1;for(let n=0;n<e.parts.length;n+=1)if(!eg(e.parts[n],t.parts[n]))return!1;return!0},lx=(e,t)=>!!e?.some(n=>n.anchorMessageId===t),MU=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.anchorMessageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.anchorMessageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!kU(o,i))return!1;r+=1,s+=1}},E7=(e,t,n,r)=>{if(e===t)return!0;if(!e||!t)return e===t;if(r)return!0;if(e.turnId!==t.turnId||e.isFirstAssistantInTurn!==t.isFirstAssistantInTurn||e.isLastAssistantInTurn!==t.isLastAssistantInTurn||e.isLatestTurn!==t.isLatestTurn||e.isWorking!==t.isWorking||e.hasTools!==t.hasTools||e.hasReasoning!==t.hasReasoning||e.userMessageCreatedAt!==t.userMessageCreatedAt||e.userMessageVariant!==t.userMessageVariant||(e.headerMessageId===n||t.headerMessageId===n)&&e.headerMessageId!==t.headerMessageId)return!1;const o=e.activityOwnerMessageId===n||t.activityOwnerMessageId===n;if(o&&e.activityOwnerMessageId!==t.activityOwnerMessageId||!CU(e.activityParts,t.activityParts,n)||!MU(e.activityGroupSegments,t.activityGroupSegments,n))return!1;const i=lx(e.activityGroupSegments,n)||lx(t.activityGroupSegments,n);return!((o||i)&&!wU(e.diffStats,t.diffStats)||(o||i||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!SU(e.changedFiles,t.changedFiles))},Od=new Map,IU=e=>{const t=Od.get(e);if(t)return t;const n={subscribers:new Set,timerId:null};return Od.set(e,n),n},EU=(e,t)=>{const n=IU(e);return n.subscribers.add(t),t(Date.now()),n.timerId===null&&typeof window<"u"&&(n.timerId=window.setInterval(()=>{const r=Date.now();n.subscribers.forEach(s=>{s(r)})},e)),()=>{const r=Od.get(e);r&&(r.subscribers.delete(t),!(r.subscribers.size>0)&&(r.timerId!==null&&typeof window<"u"&&window.clearInterval(r.timerId),Od.delete(e)))}},_7=(e,t=250)=>{const[n,r]=p.useState(()=>Date.now());return p.useEffect(()=>{if(e)return EU(t,r)},[e,t]),n},dx=e=>typeof e!="string"?null:e.trim()||null,_U=e=>{const t=e.tool?.trim().toLowerCase(),n=e.state,r=n?.input&&typeof n.input=="object"?n.input:void 0;if(t==="skill")return dx(r?.name);if(t!=="read")return null;const s=n?.metadata?.pichamber;if(!s||typeof s!="object")return null;const o=s.skill;return!o||typeof o!="object"?null:dx(o.name)},Ra=e=>{const t="h-3.5 w-3.5 flex-shrink-0",n=e.toLowerCase();return n==="edit"||n==="multiedit"||n==="apply_patch"||n==="str_replace"||n==="str_replace_based_edit_tool"?c.jsx($,{name:"pencil",className:t}):n==="write"||n==="create"||n==="file_write"?c.jsx($,{name:"file-edit",className:t}):n==="read"||n==="view"||n==="file_read"||n==="cat"?c.jsx($,{name:"file-text",className:t}):n==="bash"||n==="shell"||n==="cmd"||n==="terminal"?c.jsx($,{name:"terminal-box",className:t}):n==="list"||n==="ls"||n==="dir"||n==="list_files"?c.jsx($,{name:"folder-6",className:t}):n==="search"||n==="grep"||n==="find"||n==="ripgrep"?c.jsx($,{name:"menu-search",className:t}):n==="glob"?c.jsx($,{name:"file-search",className:t}):n==="fetch"||n==="curl"||n==="wget"||n==="webfetch"?c.jsx($,{name:"global",className:t}):n==="web-search"||n==="websearch"||n==="search_web"||n==="codesearch"||n==="google"||n==="bing"||n==="duckduckgo"||n==="perplexity"?c.jsx($,{name:"global",className:t}):n==="todowrite"||n==="todoread"?c.jsx($,{name:"list-check-3",className:t}):n==="structuredoutput"||n==="structured_output"?c.jsx($,{name:"list-check-2",className:t}):n==="skill"?c.jsx($,{name:"book",className:t}):n==="task"?c.jsx($,{name:"ai-agent",className:t}):n==="pichamber"?c.jsx($,{name:"pichamber",className:t}):n==="question"?c.jsx($,{name:"survey",className:t}):n==="lsp"?c.jsx($,{name:"scan-2",className:t}):n==="plan_enter"?c.jsx($,{name:"file-list-2",className:t}):n==="plan_exit"?c.jsx($,{name:"task",className:t}):n.startsWith("git")?c.jsx($,{name:"git-branch",className:t}):c.jsx($,{name:"tools",className:t})},jU=({href:e})=>{const[t,n]=p.useState(!1),r=p.useMemo(()=>UT(e),[e]);return!r||t?null:c.jsx("span",{className:"inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]",children:c.jsx("img",{src:r,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",className:"size-3.5 rounded-sm",onError:()=>n(!0)})})},TU=e=>{if(e.kind!=="tool")return!1;const n=e.part.state?.status||void 0;return n==="completed"||n==="error"||n==="aborted"||n==="failed"||n==="timeout"||n==="cancelled"?!1:n==="running"||n==="pending"||n==="started"?!0:typeof e.endedAt!="number"},AU=e=>{const n=e.part.state?.time;return{start:typeof n?.start=="number"?n.start:void 0,end:typeof n?.end=="number"?n.end:e.endedAt}},NU=(e,t,n=Date.now())=>{const r=Math.max(0,(t??n)-e)/1e3;return`${(r<.05&&typeof t=="number"?.1:r).toFixed(1)}s`},LU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;if(typeof o=="string"&&o.trim().length>0){const i=o.lastIndexOf("/");return i>=0?o.slice(i+1):o}return null},RU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;return typeof o=="string"&&o.trim().length>0?o:null},PU=e=>{if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="pending"?"pending":t==="in_progress"||t==="in progress"||t==="inprogress"?"in_progress":t==="completed"||t==="done"?"completed":t==="cancelled"||t==="canceled"?"cancelled":null},Ti=e=>{if(e.length===0)return"0 tasks";let t=0,n=0;for(const s of e){if(!s||typeof s!="object")continue;const o=PU(s.status);o&&(o==="pending"&&(t+=1),o==="in_progress"&&(n+=1))}const r=t+n;return r===0?"0 tasks":`${r} ${r===1?"task":"tasks"}`},DU=e=>{const n=e.part.state,r=n?.input,s=n?.output;if(Array.isArray(r?.todos)){const o=Ti(r.todos);if(o)return o}if(Array.isArray(s)){const o=Ti(s);if(o)return o}if(s&&typeof s=="object"&&Array.isArray(s.todos)){const o=Ti(s.todos);if(o)return o}if(typeof s=="string"&&s.trim().length>0)try{const o=JSON.parse(s);if(Array.isArray(o)){const i=Ti(o);if(i)return i}if(o&&typeof o=="object"&&Array.isArray(o.todos)){const i=Ti(o.todos);if(i)return i}}catch{}return null},OU=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=(typeof r?.offset=="number"&&Number.isFinite(r.offset)?r.offset:void 0)??(typeof r?.line=="number"&&Number.isFinite(r.line)?r.line:void 0)??(typeof s?.offset=="number"&&Number.isFinite(s.offset)?s.offset:void 0)??(typeof s?.line=="number"&&Number.isFinite(s.line)?s.line:void 0);if(!(typeof o!="number"||o<=0))return Math.floor(o)},HU=(e,t=!0)=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx(mr,{variant:t?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-title)"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full flex-1 items-center overflow-hidden",Mt),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(mr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:s})]})},FU=e=>{const t=e.part,n=t.tool?.toLowerCase()??"",r=t.state,s=r?.input,o=r?.metadata;if(n==="grep"||n==="search"||n==="find"||n==="ripgrep"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="glob"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="websearch"||n==="web-search"||n==="search_web"||n==="codesearch"||n==="perplexity"){const i=s?.query;if(typeof i=="string"&&i.trim().length>0)return i.length>50?i.slice(0,50)+"...":i}if(n==="skill"){const i=s?.name;if(typeof i=="string"&&i.trim().length>0)return i}if(n==="webfetch"||n==="fetch"||n==="curl"||n==="wget"){const i=typeof s?.url=="string"&&s.url||typeof s?.URL=="string"&&s.URL||typeof o?.url=="string"&&o.url||typeof o?.URL=="string"&&o.URL||"";if(typeof i=="string"&&i.trim().length>0)return i.trim()}return n==="todowrite"||n==="todoread"?DU(e):LU(e)},BU=({toolName:e,activity:t,animateTailText:n})=>{const r=p.useContext($a),s=Ga(),o=nt(A=>A.currentDirectory),i=TU(t),a=AU(t),l=typeof a.start=="number",d=_7(!!(l&&i&&typeof a.end!="number"),250),f=l?NU(a.start,a.end,d):null,u=FU(t),h=_U(t.part),m=e.toLowerCase(),g=m==="skill"||m==="read"&&h!==null,x=m==="read"&&!g,b=g?"skill":e,S=Ka(b).displayName,y=Ra(b),v=x?RU(t):null,C=x?OU(t):void 0,w=v?s4(v,o):null,I=p.useCallback((A,j)=>{const k=Za(o,A);if(!k)return;if(r?.editor){r.editor.openFile(k,j);return}if(s){const L=re.getState(),O=o||uh(o,k);j&&Number.isFinite(j)?L.openContextFileAtLine(O,k,Math.max(1,Math.trunc(j)),1):L.openContextFile(O,k),s.openFiles();return}if(!Mu(k,o)){bU(k,o).then(()=>{const L=re.getState(),O=o||uh(o,k);if(j&&Number.isFinite(j)){L.openContextFileAtLine(O,k,Math.max(1,Math.trunc(j)),1);return}L.openContextFile(O,k)});return}const _=re.getState(),M=uh(o,k);if(j&&Number.isFinite(j)){_.openContextFileAtLine(M,k,Math.max(1,Math.trunc(j)),1);return}_.openContextFile(M,k)},[o,s,r]),E=m==="grep"||m==="search"||m==="find"||m==="ripgrep"||m==="glob",T=m==="webfetch"||m==="fetch"||m==="curl"||m==="wget";return c.jsxs("div",{className:R("oc-static-tool-row flex w-full items-center gap-x-1.5 pr-2 pl-px py-1 min-w-0"),"data-chat-activity-row":"true",children:[c.jsx("div",{className:"inline-flex h-5 items-center flex-shrink-0",style:{color:"var(--tools-icon)"},children:y}),c.jsx(Pd,{active:i,minDurationMs:1e3,className:R(Gr,"inline-flex items-center flex-shrink-0"),style:ei,title:S,children:S}),x&&v&&w?c.jsxs("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),I(v,C)},className:R("inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left hover:text-[var(--status-info)] hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:C?`${w}:${C}`:w,children:[c.jsx(pr,{filePath:v,className:"h-3.5 w-3.5"}),HU(w,n)]}):null,E&&u!==null?c.jsx("span",{className:"inline-flex min-w-0 flex-1",children:c.jsxs(mr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},title:u,children:['"',u,'"']})}):null,T&&u!==null?c.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:R("min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90","truncate whitespace-nowrap",Mt),style:{color:"var(--status-info)"},title:u,children:[c.jsx(jU,{href:u}),c.jsx("span",{className:"min-w-0 truncate",children:u})]}):null,g&&h!==null?c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),k7(h,s)},className:R("inline-flex !min-h-0 h-5 min-w-0 flex-1 items-center truncate whitespace-nowrap text-left hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:`Open ${h} in Settings`,"aria-label":`Open ${h} skill in Settings`,children:h}):null,!x&&!E&&!T&&!g&&u!==null?c.jsx(mr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},children:u}):null,f?c.jsx("span",{className:R("flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:f}):null]})},VU=(e,t)=>e.toolName===t.toolName&&e.animateTailText===t.animateTailText&&eg(e.activity,t.activity),$U=p.memo(BU,VU),zU=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],yQ="diffs-container";(()=>{try{return!1}catch{return!1}})();const UU=/(?=^From [a-f0-9]+ .+$)/m,j7=/(?=^diff --git)/gm,vQ=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: (.*))?/m,xQ=new RegExp("(?<=\\n)"),qU=/^(---|\+\+\+)\s+([^\t\r\n]+)/,WU=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,KU=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,GU=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,bQ="header-prefix",wQ="header-filename-suffix",SQ="header-metadata",CQ="header-custom",kQ={dark:"pierre-dark",light:"pierre-light"},MQ="data-theme-css",IQ="data-unsafe-css",EQ="data-diffs-scrollbar-measure",_Q="--diffs-scrollbar-gutter-measured",jQ=1e5,ZU={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...ZU});const TQ=Object.freeze({fromStart:0,fromEnd:0}),AQ={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},NQ={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};function ux(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}const YU=new TextEncoder,XU=new TextDecoder("utf-8",{ignoreBOM:!0}),JU=/[\uD800-\uDFFF]/,nm=1024;let bo=new Uint8Array(nm);function T7(){bo.length!==nm&&(bo=new Uint8Array(nm))}function Dt(e){if(e.length===0)return e;if(JU.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;bo.length<t&&(bo=new Uint8Array(t));const{written:n}=YU.encodeInto(e,bo);return XU.decode(bo.subarray(0,n))}function QU(e,t,n){try{return eq(e,t,n)}finally{T7()}}function eq(e,t,n=!1){const r=lq(e),s=r?rq(e):sq(e);let o;const i=[];for(const a of s){if(r&&!j7.test(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}else if(!r&&!oq(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}const l=A7(a,{cacheKey:void 0,isGitDiff:r,throwOnError:n});l!=null&&i.push(l)}return{patchMetadata:o,files:i}}function LQ(e,t){try{return A7(e,t)}finally{T7()}}function A7(e,{cacheKey:t,isGitDiff:n=j7.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let i=0;const a=P7(e,"@@ ");let l;const d=r==null||s==null;let f=0,u=0;for(const h of a){const m=N7(h),g=m[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",h);continue}const x=R7(g);let b=0,S=0;if(x==null||l==null){if(l!=null){if(o)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",h);continue}l={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&r!=null&&s!=null?fx(s.contents):[],deletionLines:!d&&r!=null&&s!=null?fx(r.contents):[],cacheKey:mx(t)},l.additionLines.length===1&&s?.contents===""&&(l.additionLines.length=0),l.deletionLines.length===1&&r?.contents===""&&(l.deletionLines.length=0);for(const A of m){if(A.startsWith("diff --git")){const k=A.trim().match(KU),_=k?.[1]??k?.[2],M=k?.[3]??k?.[4];if(_==null||M==null){if(o)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}l.name=Dt(M.trim()),_!==M&&(l.prevName=Dt(_.trim()));continue}const j=A.startsWith("---")||A.startsWith("+++")?A.match(n?WU:qU):null;if(j!=null){const[,k,_]=j;if(k==="---"&&_!=="/dev/null"){const M=Dt(_.trim());l.prevName=M,l.name=M}else k==="+++"&&_!=="/dev/null"&&(l.name=Dt(_.trim()))}else if(n){if(A.startsWith("new mode ")&&(l.mode=Dt(A.slice(8).trim())),A.startsWith("old mode ")&&(l.prevMode=Dt(A.slice(8).trim())),A.startsWith("new file mode")&&(l.type="new",l.mode=Dt(A.slice(13).trim())),A.startsWith("deleted file mode")&&(l.type="deleted",l.mode=Dt(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?l.type="rename-pure":l.type="rename-changed"),A.startsWith("index ")){const[,k,_,M]=A.trim().match(GU)??[];k!=null&&(l.prevObjectId=Dt(k)),_!=null&&(l.newObjectId=Dt(_)),M!=null&&(l.mode=Dt(M))}A.startsWith("rename from ")&&(l.prevName=Dt(A.slice(12).trim())),A.startsWith("rename to ")&&(l.name=Dt(A.slice(10).trim()))}}continue}let y,v;for(;m.length>0&&(m[m.length-1]===`
154
- `||m[m.length-1]==="\r"||m[m.length-1]===`\r
155
- `||m[m.length-1]==="");)m.pop();const{additionStart:C,deletionStart:w}=x;f=d?f:w-1,u=d?u:C-1;const I={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:C,additionLines:b,deletionCount:x.deletionCount,deletionStart:w,deletionLines:S,deletionLineIndex:f,additionLineIndex:u,hunkContent:[],hunkContext:mx(x.hunkContext),hunkSpecs:Dt(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let E=0,T=0;for(let A=1;A<m.length;A++){const j=m[A];if(E>=I.additionCount&&T>=I.deletionCount&&!j.startsWith("\\")){if(o&&iq(j)&&!aq(j))throw Error("parsePatchContent: hunk has more lines than expected");break}const k=j[0];if(k!=="+"&&k!=="-"&&k!==" "&&k!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${k}", full line: "${j}"`),console.error("processFile: invalid rawLine:",j);continue}const _=dq(k);if(_==="addition"){if(o&&E>=I.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const M=Mh(j);(y==null||y.type!=="change")&&(y=Ih("change",f,u),I.hunkContent.push(y)),u++,E++,d&&l.additionLines.push(M),y.additions++,b++,v="addition"}else if(_==="deletion"){if(o&&T>=I.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const M=Mh(j);(y==null||y.type!=="change")&&(y=Ih("change",f,u),I.hunkContent.push(y)),f++,T++,d&&l.deletionLines.push(M),y.deletions++,S++,v="deletion"}else if(_==="context"){if(o&&(T>=I.deletionCount||E>=I.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const M=Mh(j);(y==null||y.type!=="context")&&(y=Ih("context",f,u),I.hunkContent.push(y)),u++,f++,E++,T++,d&&(l.deletionLines.push(M),l.additionLines.push(M)),y.lines++,v="context"}else if(_==="metadata"&&y!=null){if(y.type==="context"?(I.noEOFCRAdditions=!0,I.noEOFCRDeletions=!0):v==="deletion"?I.noEOFCRDeletions=!0:v==="addition"&&(I.noEOFCRAdditions=!0),d&&(v==="addition"||v==="context")){const M=l.additionLines.length-1;M>=0&&(l.additionLines[M]=ux(l.additionLines[M]))}if(d&&(v==="deletion"||v==="context")){const M=l.deletionLines.length-1;M>=0&&(l.deletionLines[M]=ux(l.deletionLines[M]))}}}if(o&&(E!==I.additionCount||T!==I.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");I.additionLines=b,I.deletionLines=S,I.collapsedBefore=Math.max(I.additionStart-1-i,0),l.hunks.push(I),i=I.additionStart+I.additionCount-1;for(const A of I.hunkContent)A.type==="context"?(I.splitLineCount+=A.lines,I.unifiedLineCount+=A.lines):(I.splitLineCount+=Math.max(A.additions,A.deletions),I.unifiedLineCount+=A.deletions+A.additions);I.splitLineStart=l.splitLineCount+I.collapsedBefore,I.unifiedLineStart=l.unifiedLineCount+I.collapsedBefore,l.splitLineCount+=I.collapsedBefore+I.splitLineCount,l.unifiedLineCount+=I.collapsedBefore+I.unifiedLineCount}if(l!=null){if(o&&d&&!n&&l.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(l.hunks.length>0&&!d&&l.additionLines.length>0&&l.deletionLines.length>0){const h=l.hunks[l.hunks.length-1],m=h.additionStart+h.additionCount-1,g=l.additionLines.length,x=Math.max(g-m,0);l.splitLineCount+=x,l.unifiedLineCount+=x}return n||(l.prevName!=null&&l.name!==l.prevName?l.hunks.length>0?l.type="rename-changed":l.type="rename-pure":(r==null||r.contents==="")&&s!=null&&s.contents!==""?l.type="new":r!=null&&r.contents!==""&&(s==null||s.contents==="")&&(l.type="deleted")),l.type!=="rename-pure"&&l.type!=="rename-changed"&&(l.prevName=void 0),l}}function tq(e,t,n=!1){const r=[],s=nq(e)?e.split(UU):[e];for(const o of s)try{r.push(QU(o,t!=null?`${t}-${r.length}`:void 0,n))}catch(i){if(n)throw i;console.error(i)}return r}function nq(e){return e.startsWith("From ")||e.includes(`
156
- From `)}function fx(e){const t=N7(e);for(let n=0;n<t.length;n++)t[n]=Dt(t[n]);return t}function N7(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const r=e.indexOf(`
157
- `,n);if(r===-1)break;t.push(e.slice(n,r+1)),n=r+1}return n<e.length&&t.push(e.slice(n)),t}function rq(e){return P7(e,"diff --git")}function sq(e){if(e.length===0)return[""];const t=[];let n=0,r=0,s=0,o=0,i=!1;for(;r<e.length;){const a=rm(e,r);if(s<=0&&o<=0){if(L7(e,r)){r>n&&t.push(e.slice(n,r)),n=r,i=!0,r=rm(e,a);continue}if(i&&e.startsWith("@@ -",r)){const d=R7(e.slice(r,a));d!=null&&(s=d.deletionCount,o=d.additionCount)}r=a;continue}const l=e[r];if(l==="\\"){r=a;continue}l===" "?(s=Math.max(s-1,0),o=Math.max(o-1,0)):l==="-"?s=Math.max(s-1,0):l==="+"&&(o=Math.max(o-1,0)),r=a}return t.push(e.slice(n)),t}function oq(e){return L7(e,0)}function L7(e,t){const n=rm(e,t);return hx(e,t,"---")&&hx(e,n,"+++")}function hx(e,t,n){if(!e.startsWith(n,t))return!1;const r=e[t+n.length];if(r!==" "&&r!==" ")return!1;for(let s=t+n.length+1;s<e.length;s++){const o=e[s];if(o===`
158
- `||o==="\r")break;if(o!==" "&&o!==" ")return!0}return!1}function rm(e,t){const n=e.indexOf(`
159
- `,t);return n===-1?e.length:n+1}function iq(e){const t=e[0];return t==="+"||t==="-"||t===" "}function aq(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
160
- `&&n!=="\r")return!1}return!0}function R7(e){if(!e.startsWith("@@ -"))return;let t=4;const n=cl(e,t);if(n==null)return;const r=n.value;t=n.endIndex;let s=1;if(e[t]===","){const f=cl(e,t+1);if(f==null)return;s=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const o=cl(e,t);if(o==null)return;const i=o.value;t=o.endIndex;let a=1;if(e[t]===","){const f=cl(e,t+1);if(f==null)return;a=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let l;const d=t+3;return e[d]===" "&&(l=cq(e.slice(d+1))),{additionCount:a,additionStart:i,deletionCount:s,deletionStart:r,hunkContext:l}}function cl(e,t){let n=t,r=0;for(;n<e.length;n++){const s=e.charCodeAt(n)-48;if(s<0||s>9)break;r=r*10+s}if(n!==t)return{value:r,endIndex:n}}function cq(e){return e.endsWith(`\r
161
- `)?e.slice(0,-2):e.endsWith(`
162
- `)?e.slice(0,-1):e}function lq(e){return e.startsWith("diff --git")||e.includes(`
163
- diff --git`)}function P7(e,t){if(e.length===0)return[""];const n=`
164
- ${t}`,r=e.startsWith(t)?0:px(e,n,0);if(r===-1)return[e];const s=[];r>0&&s.push(e.slice(0,r));let o=r;for(;;){const i=px(e,n,o+1);if(i===-1)break;s.push(e.slice(o,i)),o=i}return s.push(e.slice(o)),s}function px(e,t,n){const r=e.indexOf(t,n);return r===-1?-1:r+1}function mx(e){return e==null?e:Dt(e)}function dq(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Mh(e){const t=e.slice(1);return Dt(t===""?`
165
- `:t)}function Ih(e,t,n){return e==="change"?{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t}:{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}const D7=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Hd=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,uq=/(?=^diff --git\s+)/gm,O7=/^diff --git\s+/m,fq=/(?=^---\s+\S)/gm,H7=/^---\s+\S/m,Zr=e=>typeof e=="object"&&e!==null,hq=e=>e.replace(/\r\n/g,`
166
- `).replace(/\r/g,`
167
- `).trim(),pq=e=>{let t=!1;return e.split(`
168
- `).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(t)return n;const r=n.match(/^\s*(---|\+\+\+)\s+(.+)$/);if(!r)return n;const s=r[1],o=r[2]??"";return o.trim()==="/dev/null"?`${s} /dev/null`:`${s} ${o.replace(/\\/g,"/")}`}).join(`
169
- `)},mq=e=>{let t=!1;return e.split(`
170
- `).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(!t||n.startsWith("--- ")||n.startsWith("+++ ")||n.startsWith("diff --git"))return n;if(n.length===0)return" ";const r=n[0];return r===" "||r==="+"||r==="-"||r==="\\"?n:` ${n}`}).join(`
171
- `)},gx=(e,t)=>t===1?e:`${e},${t}`,gq=e=>{const t=e.split(`
172
- `),n=[...t];for(let r=0;r<t.length;r+=1){const o=(t[r]??"").match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)$/);if(!o)continue;let i=0,a=0;for(let l=r+1;l<t.length;l+=1){const d=t[l]??"";if(d.startsWith("@@")||d.startsWith("--- ")||d.startsWith("diff --git"))break;if(!d.startsWith("\\")){if(d.startsWith("+")){a+=1;continue}if(d.startsWith("-")){i+=1;continue}i+=1,a+=1}}n[r]=`@@ -${gx(o[1]??"0",i)} +${gx(o[2]??"0",a)} @@${o[3]??""}`}return n.join(`
173
- `)},F7=e=>gq(mq(pq(hq(e)))),Ut=e=>{if(typeof e=="string")return/\S/.test(e)?e:void 0;if(Zr(e)){const t=e.patch;if(typeof t=="string")return/\S/.test(t)?t:void 0}},Xa=e=>Zr(e)?typeof e.movePath=="string"?e.movePath:typeof e.filePath=="string"?e.filePath:typeof e.relativePath=="string"?e.relativePath:null:null,tg=(e,t,n)=>{if(e==="apply_patch"){const r=Array.isArray(n?.files)?n.files:[];for(const s of r)if(Zr(s)&&s.type!=="delete"){const o=Xa(s);if(o)return o}return null}if(e==="edit"||e==="multiedit"){const r=Zr(n?.filediff)?n.filediff:void 0;return r&&typeof r.file=="string"?r.file:typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null}return e==="write"?typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null:null},yq=(e,t,n)=>{if(e==="apply_patch"){const s=Array.isArray(n?.files)?n.files:[],o=new Set;for(const i of s){if(!Zr(i))continue;const a=Xa(i);a&&o.add(a),i.type==="move"&&typeof i.filePath=="string"&&o.add(i.filePath)}return[...o]}const r=tg(e,t,n);return r?[r]:[]},vq=e=>e==="edit"||e==="multiedit"||e==="apply_patch",yx=(e,t)=>{const n=Array.isArray(e.files)?e.files:[];if(!t){const r=n[0];return Zr(r)?r:void 0}return n.find(r=>Zr(r)&&(r.relativePath===t||r.filePath===t||r.movePath===t))},ya=e=>{if(!e)return;let t,n;for(const r of e.split(`
174
- `)){const s=r.replace(/\r$/,""),o=s.match(/^@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);if(o){const i=Number.parseInt(o[1]??"",10);Number.isFinite(i)&&(t=Math.max(1,i),n??=t);continue}if(t!==void 0&&!(s.startsWith("+++")||s.startsWith("---")||s.startsWith("diff "))){if(s.startsWith("+"))return t;s.startsWith(" ")&&(t+=1)}}return n},vx=(e,t,n)=>{if(!t||!vq(e))return;if(n){const i=yx(t,n),a=Ut(i?.patch)??Ut(i?.diff);if(a){const l=ya(a);if(l!==void 0)return l}}const r=Ut(t.patch)??Ut(t.diff);if(r){const i=ya(r);if(i!==void 0)return i}const s=yx(t),o=Ut(s?.patch)??Ut(s?.diff);return o?ya(o):void 0},xq=e=>{const t=(e??"").trim().replace(/\t.*$/,"");return!t||t==="/dev/null"?"":t.replace(/^[ab]\//,"")},bq=e=>{const t=e.trim().replace(/\s+/g,"-");return t.length>0?t:"file"},wq=e=>{let t=!1;for(const n of e.split(`
175
- `)){if(n.startsWith("@@")){if(!Hd.test(n))return!1;t=!0;continue}if(!t||n.length===0)continue;const r=n[0];if(r!==" "&&r!=="+"&&r!=="-"&&r!=="\\")return!1}return!0},Eh=e=>{const t=F7(e);if(!t||D7.test(t)||!Hd.test(t)||!wq(t))return null;try{const n=tq(t,void 0,!0);if(n.length!==1)return null;const r=n[0]?.files??[],s=r[0];return r.length!==1||!s||s.hunks.length===0?null:{patch:t,title:xq(s.name)}}catch{return null}},Sq=e=>{const t=O7.test(e),n=H7.test(e);return!t&&!n?[]:e.split(t?uq:fq).map(r=>r.trim()).filter(r=>r.length>0)},xx=(e,t,n,r)=>{const s=F7(e);if(!s)return[];const o=Eh(s);if(o){const a=o.title?r(o.title):r(t);return[{id:`${n}-0`,title:a,patch:o.patch,renderMode:"diff"}]}const i=[];for(const a of Sq(s)){const l=Eh(a),d=l?.title?r(l.title):r(t);if(!l){(Hd.test(a)||O7.test(a)||H7.test(a))&&i.push({id:`${n}-${i.length}`,title:d,patch:a,renderMode:"text"});continue}i.push({id:`${n}-${i.length}`,title:d,patch:l.patch,renderMode:"diff"})}if(i.length>0)return i;if(!D7.test(s)&&Hd.test(s)){const a=bq(t),l=Eh(`--- ${a}
176
- +++ ${a}
177
- ${s}`);if(l)return[{id:`${n}-0`,title:r(t),patch:l.patch,renderMode:"diff"}]}return[{id:`${n}-0`,title:r(t),patch:s,renderMode:"text"}]},Cq=e=>{if(!Zr(e))return null;const t=Ut(e.patch)??Ut(e.diff);if(!t)return null;const n=typeof e.relativePath=="string"?e.relativePath:typeof e.filePath=="string"?e.filePath:"";return{filePath:Xa(e)??void 0,patch:t,title:n}},kq=(e,t,n)=>{const s=(Array.isArray(e?.files)?e.files:[]).flatMap((i,a)=>{const l=Cq(i);return l?xx(l.patch,l.title||`File ${a+1}`,`file-${a}`,n).map(d=>({...d,filePath:l.filePath})):[]});return s.length>0?s:xx(typeof t=="string"?t:"","Diff","fallback",n)},Mq=new Set(["read","skill"]),Bs=e=>{if(typeof e!="string")return"";const t=e.trim().toLowerCase();if(!t)return"";const n=t.replace(/:\d+$/,"");if(n.includes(".")){const r=n.split(".").filter(Boolean);return r[r.length-1]??n}return n},Iq=e=>!Eq(e),Eq=e=>Mq.has(Bs(e)),_q=(e,t,n)=>{if(typeof t=="string"&&t.trim().length>0)return t;const r=Bs(e)==="glob"?n?.pattern:void 0;return typeof r=="string"?r:""},jq=(e,t)=>{const n=t.replace(/\r\n/g,`
178
- `);if(!n.trim())return;const r=(()=>{const a=(e??"").trim();return a?a.startsWith("/")?a.slice(1):a:"new-file"})(),s=n.split(`
179
- `),o=s.length,i=s.map(a=>`+${a}`).join(`
180
- `);return["--- /dev/null",`+++ b/${r}`,`@@ -0,0 +1,${o} @@`,i].join(`
181
- `)},Fd=e=>{const t=e.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/");return!t||t==="/"?t:t.replace(/\/+$/,"")},Kn=(e,t)=>{const n=Fd(e),r=Fd(t);if(!n)return"";if(!r)return n;if(n===r)return".";const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n},Tq=5,va=e=>typeof e=="object"&&e!==null,Aq=e=>{if(!va(e))return null;const t=typeof e.message=="string"?e.message.trim():"";if(!t)return null;const n=typeof e.severity=="number"&&Number.isFinite(e.severity)?Math.trunc(e.severity):void 0;if(n!==void 0&&n!==1)return null;const r=va(e.range)?e.range:void 0,s=r&&va(r.start)?r.start:void 0,o=typeof s?.line=="number"&&Number.isFinite(s.line)?Math.max(0,Math.trunc(s.line)):0,i=typeof s?.character=="number"&&Number.isFinite(s.character)?Math.max(0,Math.trunc(s.character)):0;return{message:t,line:o+1,character:i+1}},Nq=(e,t,n,r)=>{if(!["edit","multiedit","write","apply_patch"].includes(e))return null;const s=tg(e,t,n);if(!s||!n||!va(n.diagnostics))return null;const o=Fd(s),i=o.startsWith("/")?o:`${Fd(r)}/${o}`.replace(/\/+/g,"/"),a=n.diagnostics[o]??n.diagnostics[i];if(!Array.isArray(a))return null;const l=a.map(f=>Aq(f)).filter(f=>!!f);if(l.length===0)return null;const d=l.slice(0,Tq);return{displayPath:o.startsWith("/")?Kn(o,r):o,diagnostics:d,remaining:Math.max(0,l.length-d.length)}},Lq=e=>{const t=e.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!t)return null;const n=[],r=t[1],s=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let o;for(;(o=s.exec(r))!==null;)n.push({question:o[1],answer:o[2]});return n.length>0?n:null},Rq=e=>{const t=Ut(e?.patch)??Ut(e?.diff);if(!t)return null;let n=0,r=0,s=0;for(let o=0;o<=t.length;o+=1){if(o<t.length&&t.charCodeAt(o)!==10)continue;const i=t.slice(s,o);i.startsWith("+")&&!i.startsWith("+++")&&n++,i.startsWith("-")&&!i.startsWith("---")&&r++,s=o+1}return n===0&&r===0?null:{added:n,removed:r}},Pq=e=>{if(!e?.content||typeof e.content!="string")return null;let t=1;for(let n=0;n<e.content.length;n+=1)e.content.charCodeAt(n)===10&&(t+=1);return t},B7=(e,t,n)=>{const r=t,s=r.metadata,o=r.input;if(e.tool==="apply_patch"){const i=Array.isArray(s?.files)?s?.files:[],a=i[0],l=a?.relativePath||a?.filePath;return i.length>1?null:typeof l=="string"?Kn(l,n):null}if((e.tool==="edit"||e.tool==="multiedit")&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Kn(i,n)}if(e.tool==="read"&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Kn(i,n)}if(e.tool&&["write","create","file_write"].includes(e.tool)&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Kn(i,n)}if(e.tool==="lsp"&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Kn(i,n)}return null},Dq=(e,t)=>{if(!e)return"";const n=typeof e.operation=="string"?e.operation:"lsp";if(n==="workspaceSymbol"){const l=typeof e.query=="string"&&e.query.trim().length>0?` "${e.query.trim()}"`:"";return`${n}${l}`}const r=typeof e.filePath=="string"?e.filePath:typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:"",s=r?Kn(r,t):"";if(n==="documentSymbol")return s?`${n} ${s}`:n;const o=typeof e.line=="number"&&Number.isFinite(e.line)?Math.trunc(e.line):void 0,i=typeof e.character=="number"&&Number.isFinite(e.character)?Math.trunc(e.character):void 0,a=o!==void 0&&i!==void 0?`:${o}:${i}`:"";return s?`${n} ${s}${a}`:n},Oq=(e,t,n)=>{const r=t,s=r.metadata,o=r.input,i=B7(e,t,n);if(i)return i;if(e.tool==="apply_patch"){const l=Array.isArray(s?.files)?s?.files:[];return l.length>1?`${l.length} files`:""}if(e.tool==="question"&&o?.questions&&Array.isArray(o.questions)){const l=o.questions.length;return`Asked ${l} question${l!==1?"s":""}`}if(e.tool==="bash"&&o?.command&&typeof o.command=="string")return o.command.split(`
182
- `)[0].substring(0,100);if(e.tool==="task"&&o?.description&&typeof o.description=="string")return o.description.substring(0,80);if(e.tool==="lsp")return Dq(o,n);const a=o?.description||s?.description||"title"in t&&t.title||"";return _q(e.tool,a,o)},V7=e=>{const t=e.state?.title;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.state?.input;if(n&&typeof n=="object"){const r=n.filePath??n.file_path??n.path;if(typeof r=="string"&&r.trim().length>0)return r.trim();const s=n.url;if(typeof s=="string"&&s.trim().length>0)return s.trim()}return""},Zo=e=>{const t=Bs(e.tool),n=e.state?.status??"",r=V7(e);return`${e.id??""}${t}${n}${r}`},Hq=({isTaskTool:e,isExpanded:t,isActive:n,hasFinalMetadataSummary:r,taskSessionId:s})=>e&&!!s&&!r&&(t||n),Yo=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},bx=e=>{if(!e||typeof e!="object")return;const t=e;return Yo(t.sessionID)??Yo(t.sessionId)},$7=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n=="string"){t.push({tool:"tool",state:{status:"completed",title:n}});continue}if(!n||typeof n!="object")continue;const r=n;t.push({id:typeof r.id=="string"?r.id:void 0,tool:typeof r.tool=="string"?r.tool:"tool",state:{status:typeof r.state?.status=="string"?r.state.status:typeof r.status=="string"?r.status:void 0,title:typeof r.state?.title=="string"?r.state.title:typeof r.title=="string"?r.title:void 0,input:r.state?.input&&typeof r.state.input=="object"?r.state.input:void 0}})}return t},z7=e=>{if(typeof e!="string"||e.trim().length===0)return{summaryEntries:[]};const t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);if(!t?.[1])return{summaryEntries:[]};try{const n=JSON.parse(t[1].trim());return{sessionId:Yo(n.sessionId)??Yo(n.sessionID),summaryEntries:$7(n.summary??n.entries??n.tools??n.calls)}}catch{return{summaryEntries:[]}}},Fq=e=>{if(typeof e!="string"||e.trim().length===0)return;const t=z7(e);if(t.sessionId)return t.sessionId;const n=e.match(/task_id\s*:\s*([^\s<"']+)/i),r=e.match(/session[_\s-]?id\s*:\s*([^\s<"']+)/i),s=n?.[1]??r?.[1];return Yo(s||zU(e))},wx=new WeakMap,Bq=e=>e.type==="tool",Vq=e=>{const t=wx.get(e);if(t)return t;const n=[];if(e.info.role==="assistant")for(const r of e.parts){if(!Bq(r))continue;const s=r.tool?.trim().toLowerCase();if(!s||s==="task"||s==="todowrite"||s==="todoread")continue;const o=r.state;n.push({id:r.id,tool:r.tool,state:{status:o?.status,title:o?.title,input:o?.input&&typeof o.input=="object"?o.input:void 0}})}return wx.set(e,n),n},$q=e=>{const t=[];for(const n of e)t.push(...Vq(n));return t},zq=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Sx=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e));if(typeof e=="string"){const t=Number.parseInt(e,10);return Number.isFinite(t)?Math.max(0,t):null}return null},Cx=(e,t)=>e===null?t:t===null?e:e+t,Uq=e=>{const t=Array.isArray(e?.files)?e.files:[],n=new Map;for(const r of t){if(!r||typeof r!="object")continue;const s=r,o=typeof s.relativePath=="string"?s.relativePath:typeof s.filePath=="string"?s.filePath:"";if(!o)continue;const i=Sx(s.additions),a=Sx(s.deletions),l=n.get(o);if(l){l.added=Cx(l.added,i),l.removed=Cx(l.removed,a);continue}n.set(o,{file:s,path:o,name:o.split("/").pop()||o,added:i,removed:a})}return Array.from(n.values())},qq=({animate:e=!0,metadata:t,onFileClick:n,openDiffLabel:r,showFileIcons:s=!0,textClassName:o})=>{const i=Uq(t);return i.length<=1?null:c.jsx(c.Fragment,{children:i.map(a=>{const l=a.added!==null||a.removed!==null,d=c.jsxs(c.Fragment,{children:[s?c.jsx(pr,{filePath:a.path,className:"h-3.5 w-3.5"}):null,c.jsx(mr,{variant:e?"generate-effect":"static",className:R("min-w-0 max-w-full truncate",o),style:{color:"var(--tools-description)"},title:a.path,children:a.name}),l?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.added??0]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.removed??0]})]}):null]}),f=n&&a.file.type!=="delete"&&Xa(a.file),u=`${r}: ${a.path}`;return f?c.jsx(be,{variant:"ghost",size:"xs",className:R("min-w-0 max-w-full gap-1 normal-case font-normal tracking-normal",o),"aria-label":u,title:u,onClick:h=>n(a.file,h),children:d},a.path):c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1",o),style:{color:"var(--tools-description)"},children:d},a.path)})})},Wq=({currentDirectory:e,editor:t,file:n})=>{const r=Xa(n);if(!r||n.type==="delete")return!1;const s=Ut(n.patch)??Ut(n.diff),o=s?ya(s):void 0,i=Za(e,r);return t.openFile(i,o),!0},U7=({children:e,animate:t,className:n})=>c.jsx("div",{className:R(t&&"oc-step-in",n),children:e}),ng=({children:e,maxHeightClass:t="max-h-[60vh]",className:n,outerClassName:r,disableHorizontal:s=!1,followKey:o})=>{const i=p.useRef(null),a=p.useRef(!0);return p.useLayoutEffect(()=>{const l=i.current;if(o===void 0){a.current=!0;return}!l||!a.current||(l.scrollTop=l.scrollHeight)},[o]),c.jsx("div",{className:R("w-full min-w-0 flex-none overflow-hidden",r),children:c.jsx(Su,{ref:i,"data-scrollable":"true",onWheelCapture:l=>{o!==void 0&&l.deltaY<0&&(a.current=!1)},onScroll:l=>{if(o===void 0)return;const d=l.currentTarget;a.current=d.scrollHeight-d.scrollTop-d.clientHeight<=2},className:R("tool-output-surface p-2 rounded-xl w-full min-w-0",t,s?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),children:c.jsx("div",{className:"w-full min-w-0",children:e})})})},kx=({path:e,grow:t=!0})=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx("span",{className:R("min-w-0 truncate typography-ui-label text-foreground",t&&"flex-1"),style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 flex items-baseline overflow-hidden typography-ui-label",t&&"flex-1"),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0 text-muted-foreground",children:"/"}):null,c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:s})]})]})},sm=({path:e,animate:t=!0,grow:n=!0,showFileIcons:r=!0})=>{const s=e.lastIndexOf("/");if(s===-1)return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(pr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx(mr,{variant:t?"generate-effect":"static",className:R("min-w-0 truncate whitespace-nowrap",Mt,n&&"flex-1"),style:{color:"var(--tools-title)"},children:e})]});const o=e.slice(0,s),i=e.slice(s+1),a=o.startsWith("/"),l=a?o.slice(1):o;return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(pr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full items-baseline overflow-hidden",Mt,n&&"flex-1"),children:[a?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:l}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(mr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:i})]})]})},Kq=new Set(["read","view","file_read","cat","write","create","file_write","edit","multiedit","apply_patch"]),Gq=(e,t)=>{if(!Kq.has(e.toLowerCase()))return!1;const n=t.trim();if(!n||n==="Patch"||/^\d+\s+files$/.test(n))return!1;if(n.includes("/")||n.includes("\\"))return!0;const r=n.split(/[\\/]/).pop()||n;return r.startsWith(".")||r.includes(".")?!0:/^[A-Za-z0-9_-]+$/.test(r)},Zq=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(Zo(e[n])!==Zo(t[n]))return!1;return!0},q7=p.memo(({entry:e,isMobile:t,animateTailText:n})=>{const r=Bs(e.tool),s=r.length>0?r:"tool",o=V7(e),i=o.trim().length>0,a=e.state?.status,l=Ka(s).displayName;return c.jsx(U7,{animate:n,children:c.jsxs("div",{className:R("flex gap-2 min-w-0 w-full",a==="error"&&t?"items-start":"items-center"),children:[c.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:Ra(s)}),c.jsx("span",{className:R(Gr,"text-foreground/80 flex-shrink-0"),style:ei,title:l,children:l}),i?a!=="error"&&Gq(s,o)?c.jsx(sm,{path:o,animate:n,showFileIcons:!0}):a==="error"?c.jsx("span",{className:R(Mt,"flex-1 min-w-0 text-[var(--status-error)]",t?"whitespace-normal break-words":"truncate"),children:o}):c.jsx(mr,{variant:n?"generate-effect":"static",className:R(Mt,"flex-1 min-w-0 truncate text-subtle-foreground"),style:{color:"var(--tools-description)"},title:o,children:o}):null]})})},(e,t)=>e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Zo(e.entry)===Zo(t.entry));q7.displayName="TaskSummaryEntryRow";const W7=p.memo(({entries:e,isExpanded:t,isMobile:n,animateTailText:r})=>{const s=t?e:e.slice(-6),o=Math.max(0,e.length-s.length),i=e.length-s.length;return c.jsx(ng,{maxHeightClass:t?"max-h-[40vh]":"max-h-[min(17.5rem,45vh)]",disableHorizontal:!0,children:c.jsxs("div",{className:"w-full min-w-0 space-y-1","data-chat-task-entries-list":"true",children:[o>0?c.jsxs("div",{className:"typography-micro text-subtle-foreground",children:["+",o," more…"]}):null,s.map((a,l)=>{const d=t?l:i+l,f=a.id??`${Zo(a)}:${d}`;return c.jsx(q7,{entry:a,isMobile:n,animateTailText:r},f)})]})})},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Zq(e.entries,t.entries));W7.displayName="TaskSummaryEntriesList";const Yq=({entries:e,isExpanded:t,isMobile:n,output:r,sessionId:s,onShowPopup:o,input:i,animateTailText:a=!0,isActive:l=!1})=>{const d=Xn(),f=he(S=>S.setCurrentSession),u=typeof r=="string"?zq(r):"",h=u.length>0,[m,g]=p.useState(!1),x=S=>{S.stopPropagation(),s&&d&&f(s,d)},b=typeof i?.subagent_type=="string"?i.subagent_type:"subagent";return e.length===0&&!h&&!s?c.jsx("div",{className:"oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",children:c.jsx("div",{className:"typography-meta text-subtle-foreground",children:l?"Waiting for subagent activity...":"No subagent session id on task metadata."})}):c.jsxs("div",{className:R("oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-[var(--tools-border)] before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[e.length>0?c.jsx(W7,{entries:e,isExpanded:t,isMobile:n,animateTailText:a}):null,s&&c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:S=>S.stopPropagation(),onClick:x,children:[c.jsx($,{name:"external-link",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-primary font-medium",children:`Open ${b.charAt(0).toUpperCase()+b.slice(1)} subtask`})]}),h?c.jsxs("div",{className:R("space-y-1",(e.length>0||s)&&"pt-1"),children:[c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),g(y=>!y)},children:[m?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?c.jsx(ng,{maxHeightClass:"max-h-[50vh]",children:c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Wa,{content:u,variant:"tool",onShowPopup:o})})}):null]}):null]})},Xq=e=>{const t=e.colors.syntax.base,n=e.colors.syntax.tokens??{},r=e.colors.status;return{"--md-syntax-foreground":t.foreground,"--md-syntax-comment":t.comment,"--md-syntax-string":t.string,"--md-syntax-number":t.number,"--md-syntax-keyword":t.keyword,"--md-syntax-operator":t.operator,"--md-syntax-function":t.function,"--md-syntax-type":t.type,"--md-syntax-variable":t.variable,"--md-syntax-property":n.variableProperty??t.variable,"--md-syntax-inserted":r.success,"--md-syntax-deleted":r.error}},Jq="/assets/markdown-shiki.worker-BVA5NZBT.js";let $n,Qq=0;const Pa=new Map,om=new Set,Mx=()=>{Pa.forEach(e=>e(null)),Pa.clear(),om.clear(),$n?.terminate(),$n=void 0},eW=()=>{if($n)return $n;if(!(typeof window>"u"||typeof Worker>"u")){try{$n=new Worker(Jq,{type:"module"})}catch(e){console.error("Failed to create Shiki worker:",e);return}return $n.onmessage=e=>{const t=Pa.get(e.data.id);t&&(Pa.delete(e.data.id),t(e.data))},$n.onerror=Mx,$n.onmessageerror=Mx,$n.postMessage({type:"init"}),$n}},rg=e=>{const t=eW();if(!t)return Promise.resolve(null);const n=++Qq;return new Promise(r=>{Pa.set(n,r),t.postMessage(e(n))})},tW=async(e,t)=>{const n=await rg(r=>({type:"highlight",id:r,code:e,lang:t}));return n?.type==="highlight"?n.html:null},RQ=async(e,t)=>{const n=await rg(r=>({type:"highlightLines",id:r,code:e,lang:t}));return n?.type==="highlightLines"?n.lines:null},PQ=async(e,t,n,r)=>{const s=!om.has(n),o=await rg(i=>({type:"highlightTokens",id:i,code:e,lang:t,themeName:n,...s?{theme:r}:{}}));return o?.type==="highlightTokens"?(om.add(n),o.lines):null},nW=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),rW=e=>e?Object.entries(e).map(([t,n])=>n==null?"":`${t.startsWith("--")?t:t.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`)}:${typeof n=="number"?`${n}px`:n};`).join(""):"",Ix=(e,t,n)=>{const r=e.querySelector("pre");r&&(r.style.margin="0",r.style.background="transparent",r.style.whiteSpace=t?"pre-wrap":"pre",t&&(r.style.wordBreak="break-word",r.style.overflowWrap="break-word"));const s=e.querySelector("code");if(s){const o=rW(n);o&&s.setAttribute("style",`${s.getAttribute("style")??""}${o}`)}},sW=e=>`<pre><code>${nW(e)}</code></pre>`,Bd=({code:e,language:t,className:n,style:r,codeStyle:s,wrap:o=!1})=>{const{currentTheme:i}=vr(),a=p.useRef(null),l=p.useMemo(()=>Xq(i),[i]);return p.useLayoutEffect(()=>{const d=a.current;d&&(d.innerHTML=sW(e),Ix(d,o,s))},[e,o,s]),p.useEffect(()=>{const d=a.current;if(!d)return;let f=!0;return tW(e,(t||"text").toLowerCase()).then(u=>{!f||!d||!u||(d.innerHTML=u,Ix(d,o,s))}),()=>{f=!1}},[e,t,o,s]),c.jsx("div",{ref:a,className:R("typography-code",n),style:{...l,...r}})},oW={maxDepth:50,maxNodes:1e5,initiallyExpandedDepth:2};function iW(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="object"?"object":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":"null"}function aW(e){if(e.length===0)return"root";let t="root";for(const n of e)/^\d+$/.test(n)?t+=`[${n}]`:t+=`.${n}`;return t}let im=0;function K7(e,t,n,r,s){if(im>=s.maxNodes)return null;im++;const o=iW(e),i=aW(n),a=o==="object"||o==="array",l={id:i,key:t,value:e,type:o,depth:r,path:n,isExpandable:a};if(a&&r<s.maxDepth){const d=o==="array"?e.map((f,u)=>[String(u),f]):Object.entries(e);l.childCount=d.length,l.children=[];for(const[f,u]of d){const h=[...n,f],m=K7(u,f,h,r+1,s);m&&l.children.push(m)}}else a&&(l.childCount=o==="array"?e.length:Object.keys(e).length);return l}function cW(e,t){const n={...oW,...t};im=0;try{const r=e.trim();if(!r)return null;const s=JSON.parse(r);return K7(s,"root",[],0,n)}catch{return null}}function lW(e,t){if(!e)return[];const n=[];function r(s){const o=!t.has(s.id);if(n.push({node:s,isExpanded:o}),s.isExpandable&&o&&s.children)for(const i of s.children)r(i)}return r(e),n}function dW(e){if(!e)return[];const t=[];function n(r){if(r.isExpandable&&(t.push(r.id),r.children))for(const s of r.children)n(s)}return n(e),t}function uW(e,t){if(!e)return[];const n=[];function r(s){if(s.isExpandable&&s.depth>=t&&n.push(s.id),s.children)for(const o of s.children)r(o)}return r(e),n}const Ex=["var(--syntax-key)","color-mix(in oklch, var(--syntax-key) 85%, var(--syntax-string))","color-mix(in oklch, var(--syntax-key) 70%, var(--syntax-number))","color-mix(in oklch, var(--syntax-key) 55%, var(--syntax-function))","color-mix(in oklch, var(--syntax-key) 40%, var(--syntax-type))","color-mix(in oklch, var(--syntax-key) 30%, var(--syntax-keyword))"];function fW(e){return Ex[e%Ex.length]}function hW(e){switch(e.type){case"string":return"var(--syntax-string)";case"number":return"var(--syntax-number)";case"boolean":return"var(--syntax-keyword)";case"null":return"var(--syntax-comment)";default:return"var(--surface-foreground)"}}function am(e){switch(e.type){case"string":{const t=e.value;return t.length>60?`"${t.slice(0,57)}..."`:`"${t}"`}case"number":case"boolean":return String(e.value);case"null":return"null";case"object":return`{${e.childCount??0} ${e.childCount===1?"item":"items"}}`;case"array":return`[${e.childCount??0}]`;default:return String(e.value)}}function pW(e){if(e.type==="object"){const t=e.children?.map(r=>r.key).slice(0,3)??[],n=(e.childCount??0)>3?", ...":"";return`{ ${t.map(r=>`"${r}": ...`).join(", ")}${n} }`}if(e.type==="array"){const t=e.childCount??0;return t<=3?`[${e.children?.map(r=>am(r)).join(", ")??""}]`:`[${t} items]`}return am(e)}const cm=p.memo(({flatNode:e,onToggle:t,onCopyPath:n})=>{const{node:r,isExpanded:s}=e,o=r.depth*20,i=p.useCallback(()=>{t(r.id)},[t,r.id]),a=p.useCallback(u=>{n&&(u.preventDefault(),n(r.id))},[n,r.id]),l=fW(r.depth),d=hW(r),f=r.isExpandable&&r.children&&r.children.length>0;return c.jsxs("div",{className:"flex items-center py-0.5 px-2 hover:bg-[var(--surface-hover)] rounded-sm cursor-default font-mono text-xs leading-5 whitespace-nowrap",style:{paddingLeft:`${o+8}px`},onContextMenu:a,children:[f?c.jsx("button",{type:"button",onClick:i,className:"mr-1 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm hover:bg-[var(--interactive-hover)] text-muted-foreground",children:s?c.jsx($,{name:"arrow-down-s",className:"h-3 w-3"}):c.jsx($,{name:"arrow-right-s",className:"h-3 w-3"})}):c.jsx("span",{className:"mr-1 w-4"}),r.key!=="root"&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"mr-1 font-semibold",style:{color:l},children:/^\d+$/.test(r.key)?r.key:`"${r.key}"`}),c.jsx("span",{className:"mr-1 text-[var(--surface-foreground)]",children:":"})]}),r.isExpandable?s?c.jsx("span",{className:"text-[var(--surface-foreground)]",children:r.type==="object"?"{":"["}):c.jsx("span",{style:{color:"var(--surface-mutedForeground)"},children:pW(r)}):c.jsx("span",{style:{color:d},children:am(r)})]})});cm.displayName="JsonRow";const mW=200,gW=22,yW=p.forwardRef(function({data:t,className:n,maxHeight:r="100%",initiallyExpandedDepth:s=2,onCopyPath:o},i){const a=p.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]),l=p.useMemo(()=>a?cW(a):null,[a]),[d,f]=p.useState(()=>l?new Set(uW(l,s)):new Set),u=p.useMemo(()=>lW(l,d),[l,d]),h=u.length>mW,m=p.useRef(null),g=X5({count:u.length,enabled:h,getScrollElement:()=>m.current,estimateSize:()=>gW,overscan:20,getItemKey:y=>u[y]?.node.id??y}),x=p.useCallback(y=>{f(v=>{const C=new Set(v);return C.has(y)?C.delete(y):C.add(y),C})},[]),b=p.useCallback(()=>{f(new Set)},[]),S=p.useCallback(()=>{l&&f(new Set(dW(l)))},[l]);return p.useImperativeHandle(i,()=>({expandAll:b,collapseAll:S}),[b,S]),l?h?c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:c.jsx("div",{style:{height:g.getTotalSize(),position:"relative"},children:g.getVirtualItems().map(y=>{const v=u[y.index];return v?c.jsx("div",{"data-index":y.index,ref:g.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${y.start}px)`},children:c.jsx(cm,{flatNode:v,onToggle:x,onCopyPath:o})},v.node.id):null})})}):c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:u.map(y=>c.jsx(cm,{flatNode:y,onToggle:x,onCopyPath:o},y.node.id))}):null}),vW=({mode:e,onModeChange:t,className:n})=>{const r=p.useCallback(s=>{s.stopPropagation(),t(e==="side-by-side"?"unified":"side-by-side")},[e,t]);return c.jsx(be,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",n),onClick:r,title:e==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:e==="side-by-side"?c.jsx($,{name:"align-justify",className:"h-3 w-3"}):c.jsx($,{name:"layout-column",className:"h-3 w-3"})})},xW=e=>{let t=e.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return t=t.replace(/^\s*\d{5}\|\s?/gm,""),t.trim()},vn=(e,t="")=>{if(typeof e=="string")return e;if(e==null)return t;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e)}catch{return t}},bW=e=>e?e.includes("<diagnostics")||e.includes("<file_diagnostics>")||e.includes("LSP errors detected")||e.includes("This file has errors"):!1,wW=e=>e?e.replace(/\n{0,2}LSP errors detected[\s\S]*?<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/\n{0,2}This file has errors[\s\S]*?<\/file_diagnostics>/g,"").replace(/<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/<file_diagnostics>[\s\S]*?<\/file_diagnostics>/g,"").trim():"",_x=(e,t)=>!e||typeof e!="object"?String(e):pP(e,t||""),ll=e=>{if(typeof e=="string"){const t=e.trim();return t.length>0?t:void 0}if(e&&typeof e=="object"){const t=e.patch;if(typeof t=="string"){const n=t.trim();return n.length>0?n:void 0}}},SW=e=>{if(!e||typeof e!="object")return;const t=ll(e.patch)??ll(e.diff);if(t)return t;const n=Array.isArray(e.files)?e.files:[];for(const r of n){if(!r||typeof r!="object")continue;const s=ll(r.patch)??ll(r.diff);if(s)return s}},CW=e=>{if(!e||typeof e!="string")return{data:null,isJson:!1};const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return{data:null,isJson:!1};if(!t.endsWith("}")&&!t.endsWith("]"))return{data:null,isJson:!1};if(t.length<2)return{data:null,isJson:!1};try{const n=JSON.parse(t);return n!==null&&typeof n=="object"?{data:n,isJson:!0}:{data:null,isJson:!1}}catch{return{data:null,isJson:!1}}},G7=(e,t,n)=>{let r=xW(e);if((t==="edit"||t==="multiedit"||t==="write"||t==="apply_patch")&&bW(r)&&(r=wW(r)),(t==="edit"||t==="multiedit"||t==="apply_patch")&&r.trim().length===0){const s=SW(n);if(s)return s}return r},DQ=e=>{const n=e.match(/<type>(file|directory)<\/type>/i)?.[1]?.toLowerCase()??"unknown",i=(e.match(/<content>([\s\S]*?)<\/content>/i)?.[1]??e).replace(/\r\n/g,`
183
- `).split(`
184
- `),a=f=>/\(\s*File has more lines\..*offset.*\)/i.test(f.trim()),d=i.map(f=>{const u=f.trim(),h=u.startsWith("(")&&u.endsWith(")")||a(u);if(n!=="directory"){const m=f.match(/^(\d+):\s?(.*)$/);if(m){const g=m[2],x=g.trim(),b=x.startsWith("(")&&x.endsWith(")")||a(x);return{lineNumber:b?null:Number(m[1]),text:g,isInfo:b}}}return{lineNumber:null,text:f,isInfo:h}}).filter((f,u,h)=>{if(f.text.trim().length>0)return!0;const m=h[u-1],g=h[u+1],x=!!(m?.isInfo||g?.isInfo),b=f.lineNumber!==null;return!(x&&b)});return{type:n,lines:d}},OQ=(e,t)=>{try{const n=e.trim().split(`
185
- `).filter(Boolean);if(n.length===0)return null;const r=[];return n.forEach(s=>{const o=s.match(/^(\s*)(.+)$/);if(o){const[,i,a]=o,l=Math.floor(i.length/2),d=!a.endsWith("/");r.push({name:a.replace(/\/$/,""),depth:l,isFile:d})}}),c.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:r.map((s,o)=>c.jsx("div",{className:"min-w-0",style:{paddingLeft:`${s.depth*20}px`},children:s.isFile?c.jsx("span",{className:"text-foreground block truncate",children:s.name}):c.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[s.name,"/"]})},o))})}catch{return null}},kW={backgroundColor:"var(--status-info)",opacity:.6},HQ=(e,t,n)=>{try{const r=e.trim().split(`
186
- `).filter(Boolean);if(r.length===0)return null;const s={};return r.forEach(o=>{const i=o.match(/^(.+?):(\d+):(.*)$/)||o.match(/^(.+?):(.*)$/);if(i){const[,a,l,d]=i,f=d!==void 0?l:"",u=d!==void 0?d:l;s[a]||(s[a]=[]),s[a].push({lineNum:f,content:u})}}),c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," match",r.length!==1?"es":""]}),Object.entries(s).map(([o,i])=>c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:o}),c.jsx("div",{className:"pl-4 space-y-1",children:i.map((a,l)=>!a.lineNum&&!a.content?null:c.jsxs("div",{className:R("flex items-start gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:kW}),c.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[a.lineNum&&c.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",a.lineNum,":"]}),c.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:a.content||" "})]})]},l))})]},o))]})}catch{return null}},MW={backgroundColor:"var(--status-info)",opacity:.6},FQ=(e,t,n)=>{try{const r=e.trim().split(`
187
- `).filter(Boolean);if(r.length===0)return null;const s={};r.forEach(i=>{const a=i.lastIndexOf("/"),l=a>0?i.substring(0,a):"/",d=a>=0?i.substring(a+1):i;s[l]||(s[l]=[]),s[l].push(d)});const o=Object.keys(s).sort();return c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," file",r.length!==1?"s":""]}),o.map(i=>c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:[i,"/"]}),c.jsx("div",{className:R("pl-4 grid gap-1",t?"grid-cols-1":"grid-cols-2"),children:s[i].sort().map(a=>c.jsxs("div",{className:R("flex items-center gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:MW}),c.jsx("span",{className:"text-foreground font-mono truncate",children:a})]},a))})]},i))]})}catch{return null}},IW=(e,t,n)=>{try{const r=JSON.parse(e);if(!Array.isArray(r))return null;const s=r.filter(a=>!!a&&typeof a=="object"&&typeof a.content=="string"&&typeof a.status=="string");if(s.length===0)return null;const o=s.reduce((a,l)=>{const d=l.status;return d in a&&a[d].push(l),a},{in_progress:[],pending:[],completed:[],cancelled:[]}),i=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return c.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return c.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return c.jsxs("div",{className:R("space-y-3 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Da.tool.popup,children:[c.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[c.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:[t.total,": ",s.length]}),o.in_progress.length>0&&c.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:[t.inProgress,": ",o.in_progress.length]}),o.pending.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)"},children:[t.pending,": ",o.pending.length]}),o.completed.length>0&&c.jsxs("span",{style:{color:"var(--status-success)"},children:[t.completed,": ",o.completed.length]}),o.cancelled.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:[t.cancelled,": ",o.cancelled.length]})]}),o.in_progress.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),c.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:t.inProgress})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.in_progress.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.pending.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),c.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:t.pending})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.pending.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.completed.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx($,{name:"check",className:"w-3 h-3",style:{color:"var(--status-success)"}}),c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:t.completed})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.completed.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx($,{name:"check",className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.cancelled.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-subtle-foreground",children:"×"}),c.jsx("span",{className:"typography-meta font-semibold text-subtle-foreground uppercase tracking-wide",children:t.cancelled})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.cancelled.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-subtle-foreground mt-0.5 flex-shrink-0",children:"×"}),c.jsx("span",{className:"typography-code text-subtle-foreground line-through flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]})]})}catch{return null}},BQ=(e,t)=>{try{return c.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Da.tool.popup,children:c.jsx(Wa,{content:e,variant:"tool"})})}catch{return null}},EW=(e,t,n)=>hP(t,e,n),_W=new Set(["id","identifier","title","name"]),jW=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dl=e=>e.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^./,t=>t.toUpperCase()),TW=e=>{const t=typeof e.id=="string"?e.id:typeof e.identifier=="string"?e.identifier:"",n=typeof e.title=="string"?e.title:typeof e.name=="string"?e.name:"";return t&&n?`${t} · ${n}`:n||t||null},AW=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},Vd=p.memo(({value:e,label:t,depth:n})=>{if(Array.isArray(e)){const o=t?`${dl(t)} (${e.length})`:`(${e.length})`;return c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]",children:[c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:o})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"space-y-1",children:e.map((i,a)=>c.jsx(Vd,{value:i,depth:n+1},a))})]})]})}if(jW(e)){const o=TW(e),i=Object.entries(e).filter(([d])=>!_W.has(d)),a=t?`${dl(t)}${o?` · ${o}`:""}`:o,l=c.jsx("div",{className:"space-y-1",children:i.map(([d,f])=>c.jsx(Vd,{label:d,value:f,depth:n+1},d))});return!t&&n===0?c.jsxs("div",{className:"space-y-2",children:[o?c.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)]",children:o}):null,l]}):c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]",children:[c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:a??(t?dl(t):"{}")})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),l]})]})}const r=e===null?"null":typeof e=="boolean"?e?"true":"false":String(e),s=typeof e=="string"&&AW(e)?c.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[var(--status-info)] underline underline-offset-2 hover:opacity-80",title:e,children:e}):c.jsx("span",{className:R("min-w-0 break-words",e===null?"text-[var(--surface-mutedForeground)]":"text-[var(--surface-foreground)]"),children:r});return c.jsxs("div",{className:"grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-2 py-1 typography-meta",children:[t?c.jsx("span",{className:"truncate text-[var(--surface-mutedForeground)]",title:t,children:dl(t)}):c.jsx("span",{}),s]})});Vd.displayName="JsonSummaryValue";const $d=p.memo(({data:e})=>c.jsx("div",{className:"space-y-1",children:c.jsx(Vd,{value:e,depth:0})}));$d.displayName="JsonSummaryView";const Z7=({diff:e})=>c.jsx("pre",{className:"m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg p-2 typography-code",style:{backgroundColor:"var(--syntax-base-background)",color:"var(--syntax-base-foreground)"},children:e}),Y7=1e5,jx=(e,t,n)=>{const r=Math.max(0,t-e.length+1),s=Y7-n.syntheticCells,o=Math.min(r,s),i=Math.min(t,e.length+o-1);for(;e.length<=i;)e.push([]);return n.syntheticCells+=o,i},NW=(e,t,n,r,s)=>{const o=e[t],i=Y7-s.syntheticCells,a=Math.min(n,o.length+i),l=Math.max(0,a-o.length);for(;o.length<a;)o.push(" ");return s.syntheticCells+=l,o[a]=r,a},Tx=e=>{if(!e.includes("\x1B")&&!e.includes("\r")&&!e.includes("\b"))return e;const t=[[]],n={syntheticCells:0};let r=0,s=0;for(let o=0;o<e.length;o+=1){const i=e[o];if(i===`
188
- `){r+=1,s=0,t[r]??=[];continue}if(i==="\r"){s=0;continue}if(i==="\b"){s=Math.max(0,s-1);continue}if(i!=="\x1B"){s=NW(t,r,s,i,n)+1;continue}const a=e[o+1];if(a==="["){const l=o+2;let d=l;for(;d<e.length&&!/[\x40-\x7E]/.test(e[d]);)d+=1;if(d===e.length)break;const f=e[d],u=e.slice(l,d).split(";").map(m=>Number.parseInt(m,10)||0),h=u[0]||1;if(f==="A")r=Math.max(0,r-h);else if(f==="B")r=jx(t,r+h,n);else if(f==="C")s+=h;else if(f==="D")s=Math.max(0,s-h);else if(f==="G")s=Math.max(0,h-1);else if(f==="H"||f==="f")r=jx(t,Math.max(0,(u[0]||1)-1),n),s=Math.max(0,(u[1]||1)-1);else if(f==="K"){const m=t[r],g=u[0];if(g===1)for(let x=0;x<=s&&x<m.length;x+=1)m[x]=" ";else g===2?t[r]=[]:m.length=Math.min(m.length,s)}o=d;continue}if(a==="]"){const l=e.indexOf("\x07",o+2),d=e.indexOf("\x1B\\",o+2),f=l===-1?d:d===-1?l:Math.min(l,d);if(f===-1)break;o=e[f]==="\x07"?f:f+1;continue}o+=1}return t.map(o=>o.join("")).join(`
189
- `)},LW=(e,t,n,r)=>{const s=e==="bash",o=s&&r!=="running";if(typeof t=="string")return o?Tx(t):t;if(s&&typeof n=="string"&&n.length>0)return o?Tx(n):n},RW=(e,t)=>t.startsWith(e)?t.slice(e.length):void 0,X7=16,PW=(e,t=X7)=>{if(t<=0||e.length===0)return e;let n=1;for(let r=e.length-1;r>=0;r-=1)if(e.charCodeAt(r)===10&&(n+=1,n>t))return e.slice(r+1);return e},DW=(e,t,n,r)=>t.tool==="bash"?"bash":EW(G7(e,t.tool||"",n),t.tool||"",r),OW=(e,t,n)=>t.tool==="bash"?e:G7(e,t.tool||"",n),HW=({output:e})=>{const t=p.useRef(null),n=p.useRef("");return p.useLayoutEffect(()=>{const r=t.current;if(!r)return;const s=r.firstChild,o=s instanceof globalThis.Text?s:document.createTextNode("");o!==s&&r.replaceChildren(o);const i=PW(e,X7),a=RW(n.current,i);a===void 0?o.data=i:a.length>0&&o.appendData(a),n.current=i},[e]),c.jsx("pre",{ref:t,className:"m-0 whitespace-pre-wrap break-words",style:{...em,lineHeight:"round(var(--code-block-line-height), 1px)",overflowWrap:"break-word"}})},lm=({output:e,part:t,metadata:n,input:r,isStreaming:s=!1})=>{const o=OW(e,t,n),i=DW(e,t,n,r),a=p.useMemo(()=>CW(o),[o]),[l,d]=p.useState("summary"),[f,u]=p.useState(!1);p.useEffect(()=>{d("summary"),u(!1)},[o]);const h=p.useCallback((g,x)=>{x.stopPropagation(),d(g)},[]),m=p.useCallback(async g=>{if(g.stopPropagation(),!(await yr(o)).ok){Ce.error("Failed to copy output");return}u(!0),typeof window<"u"&&window.setTimeout(()=>u(!1),1200)},[o]);return t.tool==="bash"&&s?c.jsx("div",{className:"typography-code text-muted-foreground",children:c.jsx(HW,{output:o})}):a.isJson?c.jsxs("div",{className:"tool-output-surface relative p-2 rounded-xl w-full min-w-0",children:[c.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1",children:[c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="summary"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("summary",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show navigable JSON",title:"Show navigable JSON",children:c.jsx($,{name:"list-unordered",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="formatted"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("formatted",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show formatted JSON",title:"Show formatted JSON",children:c.jsx($,{name:"node-tree",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="raw"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("raw",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show raw JSON",title:"Show raw JSON",children:c.jsx($,{name:"code-box",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-md bg-[var(--surface-elevated)]/80 text-muted-foreground hover:text-foreground",onClick:m,onPointerDown:g=>g.stopPropagation(),"aria-label":f?"Copied output":"Copy output",title:f?"Copied output":"Copy output",children:c.jsx($,{name:f?"check":"file-copy",className:"h-3.5 w-3.5"})})]}),l==="summary"?c.jsx($d,{data:a.data}):l==="formatted"?c.jsx(yW,{data:a.data,initiallyExpandedDepth:1,maxHeight:"400px"}):c.jsx("div",{className:"typography-code pr-12 text-muted-foreground",children:c.jsx(Bd,{language:"json",code:o,style:em,codeStyle:ex.style,wrap:!0})})]}):c.jsx("div",{className:t.tool==="bash"?"typography-code text-muted-foreground":void 0,children:c.jsx(Bd,{language:i,code:o,style:em,codeStyle:ex.style,wrap:!0})})};lm.displayName="ToolScrollableTextOutput";const FW=Fs(()=>mt(()=>import("./ToolPartDiffPreview-C6Sm4eVf.js"),__vite__mapDeps([82,5,1,6,77,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,78,79,80,81,25,17,11,18,19,20,43,42]))),Ax=({diff:e,diffViewMode:t})=>c.jsx(p.Suspense,{fallback:c.jsx(Z7,{diff:e}),children:c.jsx(FW,{diff:e,diffViewMode:t})}),J7=p.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,onShowPopup:s})=>{const o=Ga(),[i,a]=p.useState("unified"),l=t,d=l.metadata,f=l.input,u=LW(e.tool||"",l.output,d?.output,t.status),h=typeof u=="string"&&u.length>0,m=typeof u=="string"?u:"",g=e.tool==="bash"&&t.status==="running",x=Q1({text:m,isStreaming:g,identityKey:e.id,allowTextReplacement:g}),b=g?x:m,S=l.attachments,y=va(d?.filediff)?d.filediff:void 0,v=Ut(d?.patch)??Ut(d?.diff)??Ut(y?.patch)??Ut(y?.diff)??null,C=p.useMemo(()=>kq(d,v??void 0,W=>Kn(W,n)),[n,v,d]),w=C.some(W=>W.renderMode==="diff"),I=e.tool==="pichamber"||e.tool==="apply_patch"||e.tool==="edit"||e.tool==="multiedit",E=p.useMemo(()=>Nq(e.tool||"",f,d,n),[n,f,d,e.tool]),T=p.useMemo(()=>!f||typeof f!="object"||Object.keys(f).length===0?"":"command"in f&&typeof f.command=="string"&&e.tool==="bash"?_x(f,e.tool):typeof f.content=="string"?f.content??"":_x(f,e.tool),[f,e.tool]),A=!I&&T.trim().length>0,j=e.tool==="write"||e.tool==="create"||e.tool==="file_write",k=e.tool==="todowrite"||e.tool==="todoread",_=p.useMemo(()=>Array.isArray(f?.todos)?JSON.stringify(f.todos):b,[f?.todos,b]),M=p.useMemo(()=>{if(!j||!A)return;const W=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;return jq(W,T)},[A,f?.filePath,f?.file_path,f?.path,T,j]);p.useEffect(()=>{a("unified")},[e.id]);const L=(W,z)=>c.jsx(ng,{maxHeightClass:z?.maxHeightClass,className:z?.className,disableHorizontal:z?.disableHorizontal,outerClassName:z?.outerClassName,followKey:z?.followKey,children:W}),O=()=>{const W=U=>Za(n,U.filePath??U.title),z=(U,P)=>{P.stopPropagation();const q=ya(U.patch),B=W(U);re.getState().openContextFileAtLine(n,B,q??1,1),o?.openFiles()},X=(U,P)=>{P.stopPropagation();const q=W(U),B=re.getState(),ee=Kn(q,n);if(B.isMobile){B.navigateToDiff(ee);return}B.openContextDiff(n,ee)},F=()=>E?c.jsxs("div",{className:"tool-output-surface rounded-xl border p-2 space-y-2",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--status-error-background)"},children:[c.jsx("div",{className:"typography-meta font-medium",style:{color:"var(--status-error)"},children:"LSP errors"}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-1 min-w-0",children:c.jsx(kx,{path:E.displayPath,grow:!1})}),c.jsx("div",{className:"space-y-1",children:E.diagnostics.map((U,P)=>c.jsx("div",{className:"rounded-md border px-2 py-1",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--surface-elevated)"},children:c.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[c.jsxs("span",{className:"typography-micro shrink-0",style:{color:"var(--status-error)"},children:["[",U.line,":",U.character,"]"]}),c.jsx("span",{className:"typography-meta text-foreground whitespace-pre-wrap break-words",children:U.message})]})},`${E.displayPath}:${U.line}:${U.character}:${P}`))}),E.remaining>0?c.jsx("div",{className:"typography-micro text-muted-foreground",children:`+${E.remaining} more errors`}):null]})]}):null;if(e.tool==="question"){if(t.status==="completed"&&h){const P=Lq(b);if(P&&P.length>0)return L(c.jsx("div",{className:"space-y-2",children:P.map((q,B)=>c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground",children:q.question}),c.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:q.answer})]},B))}),{maxHeightClass:"max-h-[40vh]"})}if(t.status==="error"&&"error"in t)return c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:vn(t.error)})]});const U=f;return U?.questions&&Array.isArray(U.questions)&&U.questions.length>0?L(c.jsx("div",{className:"space-y-2",children:U.questions.map((P,q)=>c.jsxs("div",{className:"space-y-0.5",children:[P.header?c.jsx("div",{className:"typography-micro text-muted-foreground",children:vn(P.header)}):null,c.jsx("div",{className:"typography-meta text-foreground",children:vn(P.question)}),Array.isArray(P.options)&&P.options.length>0?c.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.options.map(B=>c.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground",children:vn(B.label)},vn(B.label)))}):null]},q))}),{maxHeightClass:"max-h-[40vh]"}):c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(e.tool==="task"&&h)return L(c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Wa,{content:vn(b),variant:"tool",onShowPopup:s})}));if((e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&(C.length>0||E))return L(c.jsxs("div",{className:"space-y-3",children:[C.map(U=>c.jsxs("div",{className:"w-full min-w-0",children:[c.jsxs("div",{className:"mb-1 flex min-w-0 items-center gap-1 px-2 py-1",children:[c.jsx("div",{className:"min-w-0 flex-1 typography-meta font-medium text-muted-foreground",children:c.jsx(kx,{path:U.title})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>z(U,P),"aria-label":"Open file at first change",title:"Open file at first change",children:c.jsx($,{name:"file-edit",className:"h-3.5 w-3.5"})}),c.jsx(be,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>X(U,P),"aria-label":"Open file diff",title:"Open file diff",children:c.jsx($,{name:"git-pull-request",className:"h-3.5 w-3.5"})})]}),U.renderMode==="diff"?c.jsx(Ax,{diff:U.patch,diffViewMode:i}):c.jsx(Z7,{diff:U.patch})]},U.id)),F()]}),{className:"p-1"});if(e.tool==="write"&&E)return L(c.jsx("div",{className:"space-y-3",children:F()}),{className:"p-1"});if(j)return null;if(h&&b.trim()){const U=c.jsx(lm,{output:vn(b),part:e,metadata:d,input:f,isStreaming:g});return L(U,{className:e.tool==="bash"?"p-1 rounded-none":"p-1",maxHeightClass:g?"max-h-64":e.tool==="bash"?"max-h-[46vh]":void 0,followKey:g?b:void 0})}return L(c.jsx("div",{className:"typography-meta text-subtle-foreground",children:"No output produced"}),{maxHeightClass:"max-h-60"})},N=b.trim().length>0,D=t.status==="completed"&&"output"in t||e.tool==="bash"&&N;if(k){if(t.status==="error"&&"error"in t)return c.jsxs("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:[c.jsx("div",{className:"typography-meta font-medium text-subtle-foreground mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:t.error})]});const W=IW(_,{total:"Total",inProgress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},{unstyled:!0});return c.jsx("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:L(W??c.jsx(lm,{output:_,part:e,metadata:d,input:f}),{className:"p-2",maxHeightClass:"max-h-[46vh]"})})}return c.jsxs("div",{className:R("oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4"),children:[e.tool==="question"?O():c.jsxs(c.Fragment,{children:[A?c.jsx("div",{className:"my-1",children:L(e.tool==="bash"?c.jsx("pre",{className:"tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground m-0 p-0",children:T}):j&&M?c.jsx(Ax,{diff:M,diffViewMode:i}):c.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-subtle-foreground",children:T}),{maxHeightClass:j&&M&&r?"max-h-[50vh]":"max-h-60",className:e.tool==="bash"?"tool-input-surface p-0 rounded-none":"tool-input-surface"})}):null,D&&c.jsxs("div",{children:[(e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&w?c.jsx("div",{className:"mb-1 flex items-center justify-end gap-2",children:c.jsx(vW,{mode:i,onModeChange:a,className:"h-5 w-5 p-0"})}):null,O()]}),t.status==="error"&&"error"in t&&c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-subtle-foreground mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:vn(t.error)})]})]}),Array.isArray(S)&&S.length>0&&t.status==="completed"?c.jsx(M1,{files:S,onShowPopup:s,compact:!0}):null]})});J7.displayName="ToolExpandedContent";const ql=[];let xa;const Q7=()=>{for(;ql.length>0;){const e=ql.pop();if(!e)break;if(e.active){e.fn(),xa=ql.length>0?window.requestAnimationFrame(Q7):void 0;return}}xa=void 0},BW=e=>{if(typeof window>"u")return e(),()=>{};const t={active:!0,fn:e};return ql.push(t),xa===void 0&&(xa=window.requestAnimationFrame(()=>{xa=window.requestAnimationFrame(Q7)})),()=>{t.active=!1}},Nx=e=>{const[t,n]=p.useState(e),r=p.useRef(!1);return p.useEffect(()=>{if(!e){r.current=!0,n(!1);return}if(!r.current){r.current=!0,n(!0);return}return BW(()=>{n(!0)})},[e]),t},VW=new Set(["bash","edit","write","apply_patch","patch"]),$W=(e,t,n=Date.now())=>{const s=Math.max(0,(t??n)-e)/1e3;return`${(s<.05&&t!==void 0?.1:s).toFixed(1)}s`},Lx=({start:e,end:t,active:n})=>{const r=_7(n,250);return c.jsx(c.Fragment,{children:$W(e,t,r)})},Rx=(e,t)=>{if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},zW=(e,t)=>Rx(e.call,t.call)&&Rx(e.result,t.result),UW=p.memo(({call:e,result:t})=>{const n=Array.isArray(e)&&e.length>0,r=Array.isArray(t)&&t.length>0;return!n&&!r?null:c.jsxs("div",{className:R("my-1 ml-5 overflow-x-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2","font-mono typography-code whitespace-pre max-h-80 overflow-y-auto"),"data-chat-tool-extension-render":"true",children:[n&&e.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`call-${o}`)),r&&t.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`res-${o}`))]})},zW),qW=({part:e,isExpanded:t,onToggle:n,isMobile:r,onContentChange:s,onShowPopup:o,animateTailText:i=!0})=>{const a=he(ce=>ce.currentSessionId),l=e.state?.deferredBody===!0,d=h_(a,e.id,t&&l),f=t&&d&&d.type==="tool"?d:e,u=f.state,h=u,m=h.metadata,g=h.input,x=Xn()??"",b=u?.render,S=!!(b&&(Array.isArray(b.call)&&b.call.length>0||Array.isArray(b.result)&&b.result.length>0||Array.isArray(b.resultExpanded)&&b.resultExpanded.length>0)),y=Bs(e.tool),v=y==="task",C=u?.status,w=C==="completed"||C==="error"||C==="aborted"||C==="failed"||C==="timeout"||C==="cancelled",I=C==="completed",E=C==="error"||C==="failed",[T,A]=p.useState(!w),j=p.useRef(e.id),k=p.useRef(!w);p.useEffect(()=>{j.current!==e.id&&(j.current=e.id,k.current=!w,A(!w))},[w,e.id]),p.useEffect(()=>{w||A(!0)},[w]),p.useEffect(()=>{if(!w){k.current=!0;return}if(!k.current)return;if(!I||!VW.has(y)){k.current=!1;return}if(!x)return;k.current=!1;const J=yq(y,g,m).map(ne=>Kn(ne,x));Cu.requestGitRefresh({directory:x,...J.length>0?{paths:J}:{}})},[x,g,w,I,m,y]);const _=w||v||S,M=p.useRef(s);M.current=s;const L=p.useRef(null);p.useLayoutEffect(()=>{if(v||S)return;const ce=L.current;ce&&(ce.style.height=t?"auto":"0px",ce.style.overflow=t?"visible":"hidden",_&&M.current?.("structural"))},[S,t,v,_]);const O=p.useRef(t);p.useEffect(()=>{const ce=O.current!==t;O.current=t,!(!S||!t&&!ce)&&M.current?.("structural")},[S,t,b?.call,b?.result,b?.resultExpanded]);const N=e.metadata,D=h.time,[W,z]=p.useState(()=>({start:typeof D?.start=="number"?D.start:void 0,end:typeof D?.end=="number"?D.end:void 0})),[X,F]=p.useState(void 0),[U,P]=p.useState(void 0);p.useEffect(()=>{z({}),F(void 0),P(void 0)},[e.id]),p.useEffect(()=>{w||typeof D?.start!="number"&&F(ce=>ce??Date.now())},[w,D?.start]),p.useEffect(()=>{z(ce=>{const J={...ce};let ne=!1;return typeof D?.start=="number"&&(typeof ce.start!="number"||D.start<ce.start)&&(J.start=D.start,ne=!0),typeof D?.end=="number"&&(typeof ce.end!="number"||D.end>ce.end)&&(J.end=D.end,ne=!0),ne?J:ce})},[D?.end,D?.start]);const q=p.useMemo(()=>{const ce=[W.start,D?.start].filter(J=>typeof J=="number");return ce.length>0?Math.min(...ce):X},[X,W.start,D?.start]),B=p.useMemo(()=>typeof h.output=="string"?h.output:void 0,[h.output]),ee=p.useMemo(()=>z7(B),[B]),G=p.useMemo(()=>{if(!v)return[];const ce=m,J=$7(ce?.summary??ce?.entries??ce?.tools??ce?.calls);return J.length>0?J:ee.summaryEntries},[v,m,ee.summaryEntries]),K=w&&G.length>0,se=p.useMemo(()=>{if(!v)return;const ce=bx(m);if(ce)return ce;const J=bx(N);return J||(ee.sessionId?ee.sessionId:Fq(B))},[v,m,ee.sessionId,N,B]);p.useEffect(()=>{if(typeof D?.end=="number"||typeof W.end=="number"){P(void 0);return}typeof q=="number"&&w&&P(ce=>ce??Date.now())},[q,w,W.end,D?.end]);const le=w?W.end??D?.end??U:void 0,oe=!w&&T,ue=w,ye=Hq({isTaskTool:v,isExpanded:t,isActive:oe,hasFinalMetadataSummary:K,taskSessionId:se})?se??"":"",we=fu(ye);g_(ye);const Me=p.useMemo(()=>!v||!se?[]:!Array.isArray(we)||we.length===0?[]:$q(we),[we,v,se]),He=p.useMemo(()=>Me.length>0?Me:G,[Me,G]),Ae=p.useMemo(()=>He.map(Zo).join("\0"),[He]),Ge=p.useRef(null);p.useEffect(()=>{if(!v){Ge.current=null;return}const ce=Ge.current;Ge.current=Ae,!(ce===null||ce===Ae||He.length===0)&&M.current?.("structural")},[v,He.length,Ae]);const et=p.useMemo(()=>y==="edit"||y==="multiedit"||y==="apply_patch"?Rq(m):null,[m,y]),Xe=p.useMemo(()=>y==="write"?Pq(g):null,[g,y]),te=y==="apply_patch"&&Array.isArray(m?.files)&&(m?.files).length>1,Q=y!==e.tool?{...e,tool:y}:e,me=u?B7(Q,u,x):void 0,Se=u?Oq(Q,u,x):void 0,_e=Ka(y||e.tool||"").displayName,Fe=p.useMemo(()=>{if(y==="bash"||y==="apply_patch"||y==="lsp"||me&&(y==="apply_patch"||y==="edit"||y==="multiedit"||y==="write"))return null;const ce=h.title;if(typeof ce=="string"&&ce.trim().length>0)return ce;const J=g?.description;return typeof J=="string"&&J.trim().length>0?J:null},[me,y,h,g]),ht=!!(Fe||Se||et||Xe),ge=p.useContext($a),Ze=(ce,J)=>{ge?.editor&&(J.stopPropagation(),Wq({currentDirectory:x,editor:ge.editor,file:ce}))},Be=ce=>{if(v||S||!ge?.editor){n(e.id);return}let J,ne;if(y==="edit"||y==="multiedit")J=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path,typeof J=="string"&&(ne=vx(y,m,J));else if(y==="apply_patch")J=tg(y,g,m),typeof J=="string"&&(ne=vx(y,m,J));else if(["write","create","file_write"].includes(y))J=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path;else if(y==="lsp"){J=g?.filePath||g?.file_path||g?.path;const fe=g?.line;ne=typeof fe=="number"&&Number.isFinite(fe)?Math.trunc(fe):void 0}if(typeof J=="string"){ce.stopPropagation();const fe=Za(x,J);ge.editor.openFile(fe,ne)}else n(e.id)},ie=ce=>{ce.key!=="Enter"&&ce.key!==" "||(ce.preventDefault(),Be(ce))},ke=!v&&E?x7:b7,ve=!v&&E?w7:ei,xe=Nx(v&&(He.length>0||oe||ue||!!se)),je=Nx(!v&&!S&&t);return!ue&&!oe&&!v?null:c.jsxs("div",{children:[c.jsxs("div",{className:R("group/tool flex w-full min-w-0 gap-x-1.5 rounded-md pr-2 pl-px py-1 transition-colors hover:bg-[var(--interactive-hover)]",te?"flex-wrap items-start cursor-pointer":"items-center cursor-pointer"),"data-chat-activity-row":"true",onClick:te?()=>n(e.id):Be,onKeyDown:te?ce=>{ce.target===ce.currentTarget&&(ce.key!=="Enter"&&ce.key!==" "||(ce.preventDefault(),n(e.id)))}:ie,role:"button",tabIndex:0,children:[c.jsx("div",{className:R("flex min-w-0",te?"w-full flex-wrap items-center gap-x-2 gap-y-0.5":"flex-shrink-0 items-center gap-x-1.5"),children:te?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex h-5 flex-shrink-0 items-center gap-1.5",children:[c.jsxs("span",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[c.jsx("span",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t?"opacity-0":"group-hover/tool:opacity-0"),style:ke,children:Ra(y||e.tool)}),c.jsx($,{name:t?"arrow-down-s":"arrow-right-s",className:R("absolute inset-0 h-3.5 w-3.5 transition-opacity",t?"opacity-100":"opacity-0 group-hover/tool:opacity-100")})]}),c.jsx(Pd,{active:!!(oe&&!E),minDurationMs:300,className:R(Gr,"flex-shrink-0"),style:ve,children:_e})]}),c.jsx(qq,{metadata:m,animate:i,showFileIcons:!0,textClassName:Mt,openDiffLabel:"Open file diff",onFileClick:ge?.editor?Ze:void 0}),typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:c.jsx(Lx,{start:q,end:typeof le=="number"?le:void 0,active:!!(oe&&typeof le!="number")})}):null]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"relative h-5 w-3.5 flex-shrink-0 cursor-pointer",onClick:ce=>{ce.stopPropagation(),n(e.id)},children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t&&"opacity-0",!t&&"group-hover/tool:opacity-0"),style:ke,children:Ra(y||e.tool||"")}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",t&&"opacity-100",!t&&"opacity-0 group-hover/tool:opacity-100"),children:t?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx("div",{className:"flex min-w-0 flex-shrink-0 items-center gap-x-1.5",children:c.jsx(Pd,{active:!!(oe&&!E),minDurationMs:300,className:R(Gr,"flex-shrink-0"),style:ve,title:_e,children:_e})})]})}),!te&&ht?c.jsx("div",{className:R("flex min-w-0 flex-1 items-center",Mt),style:{color:"var(--tools-description)"},children:c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1 overflow-hidden rounded-md bg-[var(--surface-subtle)] px-1.5 py-0.5",Mt),children:c.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-hidden",children:[Fe&&c.jsx("span",{className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)",opacity:.8},title:Fe,children:Fe}),!Fe&&y==="lsp"&&me?c.jsx(sm,{path:me,animate:i,grow:!1,showFileIcons:!0}):null,!Fe&&y!=="lsp"&&Se&&(me&&Se===me?c.jsx(sm,{path:me,animate:i,grow:!1,showFileIcons:!0}):c.jsx(mr,{variant:i?"generate-effect":"static",className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)"},title:Se,children:Se})),et&&c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",et.added]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",et.removed]})]}),Xe&&c.jsx("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",Xe]})})]})})}):null,!te&&typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-subtle-foreground",Mt),"aria-label":"Tool duration",children:c.jsx(Lx,{start:q,end:typeof le=="number"?le:void 0,active:!!(oe&&typeof le!="number")})}):null]}),S&&t?c.jsx(UW,{call:b?.call,result:b?.resultExpanded&&b.resultExpanded.length>0?b.resultExpanded:b?.result}):null,xe?c.jsx(Yq,{entries:He,isExpanded:t,isMobile:r,output:B,sessionId:se,onShowPopup:o,input:g,animateTailText:i,isActive:oe}):null,!v&&!S?c.jsx("div",{ref:L,"aria-hidden":!t,style:{height:t?"auto":"0px",overflow:t?"visible":"hidden",overflowAnchor:"none"},children:je?c.jsxs("div",{className:"relative ml-2 pl-3","data-chat-tool-indent":"true",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute left-0 top-px bottom-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),u?c.jsx(J7,{part:f,state:u,currentDirectory:x,isExpanded:t,onShowPopup:o}):null]}):null}):null]})};class WW extends p.Component{state={hasError:!1};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1,error:void 0})}componentDidCatch(t){}render(){if(!this.state.hasError)return this.props.children;const t=this.state.error?.message;return c.jsxs("div",{className:"flex items-center gap-1.5 pr-2 pl-px py-1 min-w-0","data-chat-activity-row":"true",children:[c.jsx("div",{className:"h-3.5 w-3.5 flex-shrink-0",style:x7,children:Ra(this.props.toolName)}),c.jsx("span",{className:R(Gr,"flex-shrink-0"),style:w7,children:this.props.displayName}),t?c.jsxs("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:t,children:[this.props.errorLabel,": ",t]}):null]})}}const KW=e=>{const t=Bs(e.part.tool)||"tool",n=Ka(t).displayName;return c.jsx(WW,{displayName:n,errorLabel:"Error:",resetKey:e.part,toolName:t,children:c.jsx(qW,{...e})})},GW=p.memo(KW,(e,t)=>Tu([e.part],[t.part])&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.alwaysShowActions===t.alwaysShowActions&&e.onContentChange===t.onContentChange&&e.onShowPopup===t.onShowPopup&&e.animateTailText===t.animateTailText),e9=p.createContext(!1),Px=({disabled:e,children:t})=>c.jsx(e9.Provider,{value:e,children:t}),sg=({children:e,className:t,skipAnimation:n,forceAnimation:r=!1,ignoreContextDisabled:s=!1,respectReducedMotion:o=!1})=>{const i=p.useContext(e9),a=o&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,l=!!n||!s&&i||a,d=r,f=p.useRef(null);f.current===null&&(f.current=d&&!l);const u=f.current,[h,m]=p.useState(!u);return p.useEffect(()=>{if(!u)return;let g=null;const x=()=>m(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?g=window.requestAnimationFrame(x):x(),()=>{g!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(g)}},[u]),u?c.jsx("div",{className:R("w-full transition-all duration-300 ease-out",h?"opacity-100 translate-y-0":"opacity-0 translate-y-2",t),children:e}):c.jsx(c.Fragment,{children:e})},ZW=4e3,po=new Map,t9=e=>{const t=po.get(e);return t?new Set(t):new Set},YW=(e,t)=>{if(po.size>=ZW&&!po.has(e)){const n=po.keys().next().value;typeof n=="string"&&po.delete(n)}po.set(e,new Set(t))},XW=e=>{const t=new Set,n=new Map;for(const r of e){const s=n.get(r.messageId)??new Set;s.add(r.id),n.set(r.messageId,s)}for(const[r,s]of n){const o=t9(r);for(const i of s)o.has(i)&&t.add(i)}return t},JW=({messageId:e,ownerToolIds:t,nextValue:n,read:r,write:s})=>{const o=r(e);for(const i of t)n.has(i)?o.add(i):o.delete(i);s(e,o)};function QW({activities:e}){const t=re(g=>g.setImagePreviewOpen),n=p.useMemo(()=>e.filter(g=>g.kind==="tool"&&g.part.type==="tool"),[e]),r=p.useMemo(()=>{const g=new Map;for(const x of n)g.set(x.id,x.messageId);return g},[n]),s=p.useMemo(()=>{const g=new Map;for(const x of n){const b=g.get(x.messageId)??new Set;b.add(x.id),g.set(x.messageId,b)}return g},[n]),[o,i]=p.useState(()=>XW(n)),[a,l]=p.useState({open:!1,title:"",content:""}),d=o,f=p.useRef({ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d});f.current={ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d};const u=p.useCallback(g=>{const x=f.current,b=x.ownerByToolId.get(g);if(!b)return;const S=x.toolIdsByOwner.get(b)??new Set;i(y=>{const v=new Set(y);return v.has(g)?v.delete(g):v.add(g),JW({messageId:b,ownerToolIds:S,nextValue:v,read:t9,write:YW}),v})},[]),h=p.useCallback(g=>{(g.image||g.mermaid)&&(l(g),t(!0))},[t]),m=p.useCallback(g=>{l(x=>({...x,open:g})),t(g)},[t]);return{effectiveExpandedTools:d,popupContent:a,handleToggleTool:u,handleShowPopup:h,handlePopupChange:m}}const eK=Fs(()=>mt(()=>import("./ToolOutputDialog-DdMIfrnK.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),tK=e=>{const t=p.useRef(e),[n,r]=p.useState(e);return e&&(t.current=!0),p.useEffect(()=>{const s=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;let o;return e?s||typeof requestAnimationFrame!="function"?r(!0):o=requestAnimationFrame(()=>r(!0)):r(!1),()=>{o!==void 0&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(o)}},[e]),{isMounted:t.current,isVisible:n}},nK=({activity:e,isLiveTurn:t,activeStreamingMessageId:n,activeStreamingPhase:r})=>t&&n&&e.messageId===n?r??"streaming":"completed",n9=p.memo(({activity:e,animate:t,isExpanded:n,isMobile:r,onContentChange:s,onToggle:o,onShowPopup:i})=>{const a=Bs(e.part.tool),l=Iq(a)?c.jsx(GW,{part:e.part,isExpanded:n,onToggle:o,isMobile:r,alwaysShowActions:r,onContentChange:s,onShowPopup:i,animateTailText:t}):c.jsx($U,{toolName:a,activity:e,animateTailText:t});return c.jsx(sg,{children:c.jsx(U7,{animate:t,children:l})})},(e,t)=>e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.endedAt===t.activity.endedAt&&Tu([e.activity.part],[t.activity.part])&&e.animate===t.animate&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.onContentChange===t.onContentChange&&e.onToggle===t.onToggle&&e.onShowPopup===t.onShowPopup);n9.displayName="TurnToolActivityRow";const rK=({turn:e,isExpanded:t,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s,onContentChange:o})=>{const{isMobile:i}=Dn(),[a,l]=p.useState(tU),d=tK(t),f=p.useRef(o);f.current=o;const u=p.useCallback(T=>{f.current?.(T)},[]),h=e.activityParts,m=p.useMemo(()=>h.reduce((T,A)=>T+(A.kind==="tool"?1:0),0),[h]),g=p.useMemo(()=>rU(h,a),[h,a]),{effectiveExpandedTools:x,popupContent:b,handleToggleTool:S,handleShowPopup:y,handlePopupChange:v}=QW({activities:h}),C=p.useMemo(()=>h.filter(T=>T.kind==="tool").map(T=>T.id),[h]),w=p.useRef({turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set});if(w.current.turnId!==e.turnId&&(w.current={turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set}),n&&w.current.committed)for(const T of C)w.current.knownToolIds.has(T)||w.current.animatedToolIds.add(T);p.useEffect(()=>{const T=w.current;for(const A of C)T.knownToolIds.add(A);T.committed=!0},[C]);const I=p.useCallback(()=>{l(T=>Math.min(m,T+nU)),u("structural")},[u,m]),E=p.useCallback(T=>{const A=nK({activity:T,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s}),j=w.current.animatedToolIds.has(T.id);return T.kind==="reasoning"?c.jsx(yU,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.kind==="justification"?c.jsx(v7,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.part.type!=="tool"?null:c.jsx(n9,{activity:T,animate:j,isExpanded:x.has(T.id),isMobile:i,onContentChange:u,onToggle:S,onShowPopup:y},T.id)},[r,s,x,y,S,n,i,u]);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"chat-message-column",children:c.jsx("div",{id:`turn-${e.turnId}-activity`,className:"relative min-w-0 pl-[18px]","data-turn-activity-rail":"true","data-turn-activity-expanded":t?"true":"false","aria-hidden":!t,children:d.isMounted?c.jsxs("div",{className:R("relative grid origin-top transition-[grid-template-rows,opacity,transform] duration-200 ease-out motion-reduce:transition-none motion-reduce:transform-none",d.isVisible?"grid-rows-[1fr] translate-y-0 opacity-100":"grid-rows-[0fr] -translate-y-1 opacity-0"),"data-turn-activity-panel":"true","data-turn-activity-visible":d.isVisible?"true":"false",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 -left-[18px] top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsxs("div",{className:"relative min-h-0 overflow-hidden",children:[t&&g.hiddenToolCount>0?c.jsx(be,{type:"button",variant:"ghost",size:"xs",className:"-ml-1.5 mb-0.5 justify-start px-1.5 text-muted-foreground","aria-label":"Load earlier activity",onClick:I,children:"Load earlier activity"}):null,c.jsx("div",{className:"min-w-0 space-y-1","data-chat-activity-list":"true",children:g.activities.map(E)})]})]}):null})}),b.open?c.jsx(p.Suspense,{fallback:null,children:c.jsx(eK,{popup:b,onOpenChange:v,isMobile:i})}):null]})},sK=p.memo(rK),Wl=new Map,oK=(e,t)=>{const n=Wl.get(e);if(!n)return!1;let r=!1;for(const s of n)r=s(t)||r;return r},iK=(e,t)=>{const n=Wl.get(e)??new Set;return n.add(t),Wl.set(e,n),()=>{n.delete(t),n.size===0&&Wl.delete(e)}},aK=e=>e.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
190
- `).replace(/\n\s*\n+/g,`
191
- `),cK="Authentication failed for this provider. Please re-authenticate and retry.",lK=e=>{if(typeof e!="string")return!1;const t=e.toLowerCase().trim();if(!t)return!1;if(t.includes("token refresh failed")||t.includes("unauthorized")||t.includes("invalid token")||t.includes("expired token"))return!0;const n=t.includes("oauth"),r=t.includes("failed")||t.includes("invalid")||t.includes("expired");if(n&&r)return!0;const s=/\b401\b/.test(t),o=t.includes("auth")||t.includes("token")||t.includes("unauthorized");return s&&o},r9=e=>{const t=e?.error;if(!t)return;const n=typeof t.data?.message=="string"?t.data.message:void 0,r=typeof t.message=="string"?t.message:void 0,s=typeof t.name=="string"?t.name:void 0,o=n||r||s;if(o){if(s==="SessionRetry")return{text:`Retrying after an error:
192
- \`${o}\``,variant:"info"};if(s==="SessionCompaction"){const i=t.data?.phase,a=t.data?.reason;if(i==="running")return{text:a==="threshold"?"Context is nearly full. Compacting automatically...":a==="overflow"?"Context limit reached. Compacting before retrying...":"Compacting session context...",variant:"info"};if(i==="retrying"){const d=typeof t.data?.attempt=="number"?t.data.attempt:void 0,f=typeof t.data?.maxAttempts=="number"?t.data.maxAttempts:void 0,u=d&&f?` (${d}/${f})`:"",h=typeof t.data?.message=="string"&&t.data.message.trim()?`
193
- \`${t.data.message.trim()}\``:"";return{text:`Compaction failed temporarily. Retrying${u}...${h}`,variant:"info"}}if(i==="completed"){const d=typeof t.data?.tokensBefore=="number"?t.data.tokensBefore:void 0,f=typeof t.data?.estimatedTokensAfter=="number"?t.data.estimatedTokensAfter:void 0,u=d!==void 0&&f!==void 0?`
194
- ${d.toLocaleString()} → approximately ${f.toLocaleString()} tokens`:"",h=t.data?.willRetry===!0?`
195
- Retrying the interrupted turn.`:"";return{text:`Session compacted${u}${h}`,variant:"info"}}return i==="aborted"?{text:"Compaction stopped.",variant:"info"}:{text:`Compaction failed.${typeof t.data?.message=="string"&&t.data.message.trim()?`
196
- \`${t.data.message.trim()}\``:""}`,variant:"error"}}return lK(o)?{text:cK,variant:"error"}:o.trim().toLowerCase()==="aborted"?{text:"The running turn was stopped before the next message could be sent.",variant:"info"}:{text:`Failed to send message with error:
197
- \`${o}\``,variant:"error"}}},dK=({isUser:e,displayParts:t,assistantErrorText:n})=>{if(e){const r=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.output;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);if(r.length>0)return r.join(`
198
-
199
- `);const s=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.command;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);return s.length>0?s.join(`
200
- `):t.filter(a=>a.type==="text").map(a=>(a.text||a.content||"").trim()).filter(a=>a.length>0).join(`
201
- `).replace(/\n\s*\n+/g,`
202
- `)}return n&&n.trim().length>0?n:aK(t)},s9=e=>e.type==="subtask",o9=e=>{const t=e;return t.type==="text"&&typeof t.shellAction=="object"&&t.shellAction!==null},uK=e=>!!(e&&typeof e=="object"&&typeof e.type=="string"),Au=e=>e.filter(uK),og=e=>{const t=e,n=t.text;return typeof n=="string"?n:t.content||t.value||""},i9=e=>{if(e.type!=="text")return!1;const t=og(e);return!t||t.trim().length===0},a9=e=>e.type==="text"?!i9(e):s9(e)||o9(e),ig=e=>e.filter(t=>i9(t)?!1:t.type!=="compaction"),c9=(e,t,n)=>e.filter((r,s)=>{if(r.type==="tool"||r.type==="reasoning")return!1;if(r.type!=="text")return!0;const o=r.id??`${n}-part-${s}-${r.type}`;return!t.has(o)}),fK=(e,t)=>typeof t=="string"&&t.trim().length>0?!0:ig(e).length>0,ag=(e,t={})=>{const{includeReasoning:n=!0}=t,r=Au(e),s=r.some(o=>!o.synthetic);return r.filter(o=>{const a=!!o.synthetic;return a&&o.type==="text"&&og(o).includes("<system-reminder>")||a&&s||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})},hK=(e,t)=>{const n=r9(e.info)?.text;if(typeof n=="string"&&n.trim().length>0)return!0;const r=ag(e.parts),s=c9(r,t,e.info.id);return ig(s).length>0},_h=32,Dx=32,pK=({turnId:e,assistantMessages:t,renderMessage:n,deferEarlierMessages:r,activityPartIds:s})=>{const[o,i]=p.useState(_h),a=t[0],l=p.useMemo(()=>t.filter(y=>hK(y,s)),[s,t]),d=p.useMemo(()=>l.filter(y=>y!==a),[l,a]),f=r&&l.length>_h,u=f?Math.max(0,o-1):d.length,h=u>=d.length?d:d.slice(-u),m=d.length-h.length;p.useEffect(()=>{i(_h)},[e]),p.useEffect(()=>iK(e,y=>{if(a?.info.id===y)return!0;const v=d.findIndex(w=>w.info.id===y);if(v<0)return!1;const C=d.length-h.length;return!f||v>=C||i(w=>Math.max(w,d.length-v+1)),!0}),[d,a,f,e,h.length]);const g=p.useCallback(()=>{i(y=>Math.min(d.length+1,y+Dx))},[d.length]),x=p.useCallback(()=>{i(d.length+1)},[d.length]),b=p.useCallback(y=>c.jsx(mK,{message:y,renderMessage:n},y.info.id),[n]);if(!f||m===0)return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,d.map(b)]});const S=m>Dx;return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,c.jsxs("div",{className:"chat-message-column flex flex-wrap items-center justify-center gap-2 py-3",children:[c.jsxs(be,{type:"button",variant:"secondary",size:"sm",onClick:g,"aria-label":"Load earlier response",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx($,{name:"history",className:"size-3.5"}),"Load earlier response"]}),S?c.jsx(be,{type:"button",variant:"ghost",size:"sm",onClick:x,"aria-label":"Load full response",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load full response"}):null]}),h.map(b)]})},mK=p.memo(function({message:t,renderMessage:n}){return n(t)},(e,t)=>e.message===t.message),gK=p.memo(pK),yK="GitHub issue context (JSON)",vK="GitHub pull request context (JSON)",Zi=e=>!e||typeof e!="object"?!1:!!e.synthetic,xK=e=>!Array.isArray(e)||e.length===0?!1:e.every(t=>Zi(t)),bK=e=>{if(!Array.isArray(e)||e.length===0)return[];const t=e.some(r=>!Zi(r)),n=r=>{if(!Zi(r)||r.type!=="text")return!1;const s=r.text;if(typeof s!="string")return!1;const o=s.trimStart();return o.startsWith(yK)||o.startsWith(vK)};return t&&e.some(s=>Zi(s))?e.filter(s=>!Zi(s)||n(s)):e},wK={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:null},SK=new Map,l9="\0",CK=new Set(["apply_patch","create","edit","file_write","multiedit","str_replace","str_replace_based_edit_tool","write"]),kK={read:"reading files",view:"reading files",file_read:"reading files",cat:"reading files",write:"editing files",create:"editing files",file_write:"editing files",edit:"editing files",multiedit:"editing files",apply_patch:"editing files",str_replace:"editing files",str_replace_based_edit_tool:"editing files",bash:"executing commands",shell:"executing commands",cmd:"executing commands",terminal:"executing commands",grep:"searching code",search:"searching code",find:"searching files",ripgrep:"searching code",glob:"searching files",list:"listing files",ls:"listing files",dir:"listing files",list_files:"listing files",task:"delegating work",subagent:"delegating work",webfetch:"fetching a URL",fetch:"fetching a URL",websearch:"searching the web",web_search:"searching the web",search_web:"searching the web",codesearch:"searching code",todowrite:"updating tasks",todoread:"reviewing tasks",skill:"loading a skill",question:"waiting for input",lsp:"inspecting code",structuredoutput:"formatting the response",structured_output:"formatting the response",pichamber:"working in PiChamber",plan_enter:"switching to planning",plan_exit:"switching to building"},Ox=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],d9=e=>{const t=e.trim().toLowerCase().replace(/:\d+$/,"");if(!t.includes("."))return t;const n=t.split(".").filter(Boolean);return n[n.length-1]??t},MK=e=>{const t=d9(e);return kK[t]??`using ${t.replaceAll("_"," ")}`},IK=e=>{let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)},EK=e=>Ox[IK(e)%Ox.length]??"working",Hx=(e,t,n)=>{for(let r=t.length-1;r>=0;r-=1){const s=t[r],o=s?e.get(s):void 0;if(o){if(o.type==="tool"&&(o.tool?.state==="running"||o.tool?.state==="pending")){const i=d9(o.tool.name);return{activePartType:CK.has(i)?"editing":"tool",activeToolName:i,statusText:MK(i),isGenericStatus:!1}}if(o.type==="thinking"&&o.streaming)return{activePartType:"reasoning",activeToolName:void 0,statusText:"thinking",isGenericStatus:!1};if(o.type==="text"&&o.streaming&&o.text.trim().length>0)return{activePartType:"text",activeToolName:void 0,statusText:"writing response",isGenericStatus:!1}}}return{activePartType:void 0,activeToolName:void 0,statusText:EK(n),isGenericStatus:!0}},_K=e=>[e.activePartType??"",e.activeToolName??"",e.statusText,e.isGenericStatus?"1":"0"].join(l9),jK=e=>{const[t,n,r="working",s]=e.split(l9);return{activePartType:t==="text"||t==="tool"||t==="reasoning"||t==="editing"?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:s==="1"}},TK=e=>{let t=null,n=null;for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="assistant")continue;const o=s;t=s.id,n=typeof o.parentID=="string"&&o.parentID.trim().length>0?o.parentID:null;break}if(!t||!n)return{assistantId:t,model:null};for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="user"||s.id!==n)continue;const o=s,i=typeof o.model?.providerID=="string"?o.model.providerID.trim():"",a=typeof o.model?.modelID=="string"?o.model.modelID.trim():"";return{assistantId:t,model:i&&a?{providerId:i,modelId:a}:null}}return{assistantId:t,model:null}};function u9(){const e=he(b=>b.currentSessionId);he(b=>b.currentSessionDirectory);const t=Qm(e??""),n=p.useMemo(()=>TK(t),[t]),r=n.assistantId,s=ze(p.useCallback(b=>{const S=`${e??""}:${r??""}`,y=e?b.reducer.bySession.get(e):void 0,v=Ma(y)??r,C=v?y?.partOrder.get(v)??[]:[],w=y?Hx(y.parts,C,S):Hx(SK,[],S);return _K(w)},[e,r]),void 0,e?`session:${e}`:"chrome"),o=he(p.useCallback(b=>e?b.sessionAbortFlags?.get(e)??null:null,[e])),{phase:i,isWorking:a}=h1(),l=du(e??""),d=l?.type==="retry"?l.attempt:void 0,f=l?.type==="retry"?l.next:void 0,u=p.useMemo(()=>jK(s),[s]),h=p.useMemo(()=>{const b=!!(o&&!o.acknowledged);return{wasAborted:b,abortActive:b}},[o]),m=p.useMemo(()=>{if(h.wasAborted)return{...wK,wasAborted:!0,abortActive:h.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};const b=a,S=i==="busy",y=!1,v=i==="retry";let C="idle";b&&(u.activePartType==="tool"||u.activePartType==="editing"?C="tooling":C="streaming");const w=v?{attempt:d,next:f}:null;return{activity:C,hasWorkingContext:b,hasActiveTools:u.activePartType==="tool"||u.activePartType==="editing",isWorking:b,isStreaming:S,isCooldown:y,lifecyclePhase:S?"streaming":null,statusText:b?u.statusText:null,isGenericStatus:b?u.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:b,compactionDeadline:null,activePartType:b?u.activePartType:void 0,activeToolName:b?u.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:w}},[i,a,u,h,d,f]),g=p.useMemo(()=>({isActive:a&&u.activePartType==="text",characterCount:0}),[a,u.activePartType]),x=m;return{activeModel:n.model,forming:g,working:x}}const AK=({startedAt:e,completedAt:t,durationMs:n})=>typeof n=="number"&&Number.isFinite(n)&&n>=0?n:typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)&&t>=e?t-e:null,NK=e=>{const t=Math.max(.1,e/1e3);if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${r}s`},f9=p.memo(({isWorking:e,startedAt:t,statusText:n})=>{const r=he(h=>h.currentSessionId),s=ze(p.useCallback(h=>(r?h.reducer.bySession.get(r):void 0)?.extensionWorking,[r]),(h,m)=>h?.message===m?.message&&h?.visible===m?.visible,r?`session:${r}`:"chrome"),{activeModel:o,working:i}=u9(),a=qb(r??""),l=We(h=>h.providers),d=p.useMemo(()=>{if(!o)return null;const h=l.find(m=>m.id===o.providerId);return j1(h,o.modelId)||null},[o,l]);if(s?.visible===!1)return null;const f=s?.message?Nn(s.message):n??i.statusText,u=s?.message||n?!1:i.isGenericStatus;return c.jsx(X3,{isWorking:e||i.isWorking,statusText:f,isGenericStatus:u,isWaitingForPermission:i.isWaitingForPermission,retryInfo:i.retryInfo,modelName:d,providerId:o?.providerId??null,startedAt:n?t??a??null:a??t??null})});f9.displayName="LiveTurnStatus";const LK=({turnId:e,isLiveTurn:t,isWorking:n,isAwaitingRecovery:r=!1,hasActivity:s,isActivityExpanded:o,onToggleActivity:i,startedAt:a,completedAt:l,durationMs:d,liveStatusText:f,wasSteered:u})=>{const h=AK({startedAt:a,completedAt:l,durationMs:d}),m=!t&&r,g=t?"Agent working":m?"Reconnecting · last seen working":h!==null?`Worked for ${NK(h)}${u?" · Steered":""}`:s?"Agent activity":null,x=`turn-${e}-activity`;return c.jsx("div",{className:"chat-message-column mb-1","data-turn-working-header":"true","data-turn-working":t&&n?"true":"false",children:c.jsxs("div",{className:"flex min-h-6 items-center gap-1 py-0.5",children:[c.jsx("div",{className:"flex min-w-0 items-center overflow-hidden",children:t?c.jsx(f9,{isWorking:n,startedAt:a,statusText:f}):g?c.jsx("span",{className:"typography-markdown inline-flex min-w-0 items-center leading-5 text-muted-foreground",role:"status","aria-label":g,...m?{"data-turn-reconnecting":"true"}:{"data-agent-worked-row":"true"},children:g}):null}),s?c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:R("h-6 w-6 shrink-0 rounded-md p-0 text-muted-foreground","hover:bg-interactive-hover hover:text-foreground"),"aria-expanded":o,"aria-controls":x,"aria-label":o?"Collapse activity":"Expand activity","data-turn-activity-toggle":"true",onClick:i,children:c.jsx($,{name:"arrow-right-s",className:R("size-4 transition-transform duration-200 ease-out motion-reduce:transition-none",o&&"rotate-90"),"aria-hidden":"true"})}):null]})})},RK=p.memo(LK),PK=({isExpanded:e,userToggled:t,wasAutoCollapsed:n,hasActivity:r,showWorkingStatus:s,hasFinalText:o,previousHadFinalText:i,hasNewActivity:a})=>r?s&&o&&!i?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:t}:t?{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:a&&n?{isExpanded:!0,wasAutoCollapsed:!1,resetUserToggle:!1}:s&&!o&&!e?{isExpanded:!0,wasAutoCollapsed:n,resetUserToggle:!1}:s&&o&&e?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1},DK=p.memo(function({userMessage:t,renderMessage:n}){return n(t)},(e,t)=>e.userMessage===t.userMessage),OK=e=>{const t=e.summary.sourcePartId;return!t||!e.summary.text||e.summary.text.trim().length===0?!1:!e.activityParts.some(n=>n.id===t&&n.kind==="justification")},HK=({turn:e,renderMessage:t,deferEarlierAssistantMessages:n,showWorkingStatus:r=!1,isAwaitingRecovery:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,onActivityContentChange:a})=>{const l=p.useMemo(()=>e.activityParts.length>0,[e.activityParts]),d=p.useMemo(()=>OK(e),[e]),[f,u]=p.useState(()=>r&&l&&!d),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(e.activityParts.length),x=p.useRef(d);p.useLayoutEffect(()=>{const v=g.current,C=x.current,w=e.activityParts.length>v;g.current=e.activityParts.length,x.current=d;const I=PK({isExpanded:f,userToggled:h.current,wasAutoCollapsed:m.current,hasActivity:l,showWorkingStatus:r,hasFinalText:d,previousHadFinalText:C,hasNewActivity:w});m.current=I.wasAutoCollapsed,I.resetUserToggle&&(h.current=!1),I.isExpanded!==f&&u(I.isExpanded)},[l,d,f,r,e.activityParts.length]);const b=p.useCallback(()=>{h.current=!0,u(v=>!v),a?.("structural")},[a]),S=e.assistantMessages.length>0||r||s,y=p.useMemo(()=>new Set(e.activityParts.map(v=>v.id)),[e.activityParts]);return c.jsxs("section",{className:"relative w-full",id:`turn-${e.turnId}`,"data-turn-id":e.turnId,"data-scroll-spy-id":e.turnId,children:[c.jsx(DK,{userMessage:e.userMessage,renderMessage:t}),e.notices.length>0?e.notices.map(v=>c.jsx(p.Fragment,{children:t(v)},v.info.id)):null,S?c.jsx(RK,{turnId:e.turnId,isLiveTurn:r,isWorking:r,isAwaitingRecovery:s,hasActivity:l,isActivityExpanded:f,onToggleActivity:b,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,liveStatusText:e.isSteering?"Steering agent":void 0,wasSteered:e.stream.settledReason==="steered"}):null,l?c.jsx(sK,{turn:e,isExpanded:f,isLiveTurn:r,activeStreamingMessageId:o,activeStreamingPhase:i,onContentChange:a},e.turnId):null,c.jsx(gK,{turnId:e.turnId,assistantMessages:e.assistantMessages,renderMessage:t,deferEarlierMessages:n,activityPartIds:y})]})},FK=p.memo(HK),dm="#pichamber-skill:",um="#pichamber-agent:",BK=e=>`${dm}${encodeURIComponent(e)}`,VK=e=>`${um}${encodeURIComponent(e)}`,$K=e=>{if(!e?.startsWith(dm))return null;try{return decodeURIComponent(e.slice(dm.length))}catch{return null}},VQ=e=>{if(!e?.startsWith(um))return null;try{return decodeURIComponent(e.slice(um.length))}catch{return null}},zK=/(^|\s)\/skill:([A-Za-z0-9][A-Za-z0-9_-]*)/g,UK=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,qK=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),h9=(e,t)=>e.split(UK).map((n,r)=>r%2===1?n:t(n)).join(""),WK=e=>h9(e,t=>t.replace(/ *\n/g,`
203
- `)),KK=({textContent:e,agentMention:t,skillNames:n})=>{let r=h9(e,qK);if(t?.token&&r.includes(t.token)){const s=`[${t.token}](${VK(t.name)})`;r=r.replace(t.token,s)}return r=r.replace(zK,(s,o,i)=>n.has(i)?`${o}[/skill:${i}](${BK(i)})`:s),WK(r)},GK=({part:e,messageId:t,agentMention:n})=>{const r=e,s=r.text,i=typeof s=="string"?s:r.content||r.value||"",[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=Hr(w=>w.skills),h=Ga(),m=!a,g=p.useRef(null),x=p.useMemo(()=>new Map(u.map(w=>[w.name,w])),[u]),b=p.useCallback(w=>{x.has(w)&&k7(w,h)},[h,x]),S=p.useCallback(w=>{if(typeof window>"u")return!1;const I=window.getSelection();if(!I||I.isCollapsed||I.rangeCount===0)return!1;const E=I.getRangeAt(0);return w.contains(E.startContainer)||w.contains(E.endContainer)},[]);p.useEffect(()=>{const w=g.current;if(!w)return;const I=()=>{a||f(w.scrollHeight>w.clientHeight)};I();const E=new ResizeObserver(I);return E.observe(w),()=>E.disconnect()},[i,a]);const y=p.useCallback(w=>{const I=w.target,T=I?.closest("[data-skill-name]")?.dataset.skillName??$K(I?.closest("a[href]")?.getAttribute("href"));if(T){w.preventDefault(),w.stopPropagation(),b(T);return}const A=g.current;A&&(S(A)||!a&&d&&l(!0))},[S,a,d,b]),v=p.useCallback(w=>{w.stopPropagation(),l(!1)},[]),C=p.useMemo(()=>KK({textContent:i,agentMention:n,skillNames:new Set(x.keys())}),[n,x,i]);return!i||i.trim().length===0?null:c.jsxs("div",{className:"relative",children:[a&&c.jsx("button",{type:"button",onClick:v,className:"absolute top-0 right-0 z-10 flex items-center justify-center rounded-sm bg-[var(--surface-elevated)] p-0.5 text-[var(--surface-mutedForeground)] hover:text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] transition-colors","aria-label":"Collapse user message",children:c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("break-words font-sans typography-markdown-body",a&&"pb-3",m&&"line-clamp-2",d&&!a&&"cursor-pointer"),ref:g,onClick:y,children:c.jsx(Wa,{content:C,className:R("[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",m&&["[&_.markdown-content>*]:my-0","[&_[data-component='markdown-code']]:my-0","[&_[data-component='markdown-code']]:inline","[&_[data-component='markdown-code']]:border-0","[&_[data-component='markdown-code']]:bg-transparent","[&_[data-component='markdown-code']>*:first-child]:hidden","[&_[data-component='markdown-code']>div]:inline","[&_[data-component='markdown-code']>div]:p-0","[&_[data-component='markdown-code']_pre]:inline","[&_[data-component='markdown-code']_code]:inline","[&_[data-md-code-line]]:!inline","[&_[data-md-code-line-number]]:hidden","[&_[data-md-code-line-break]]:!inline"]),disableLinkSafety:!0,enableFileReferences:!1})})]},e.id||`${t}-user-text`)},ZK=p.memo(GK),YK="application/vnd.github.issue-link",XK="application/vnd.github.pull-request-link",p9=e=>e.mime===YK?"issue":e.mime===XK?"pr":null,m9=e=>!e||!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,JK=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},QK=e=>{if(!e)return"Unnamed file";const n=e.replace(/\\/g,"/").split("/");return n[n.length-1]||e},fm=e=>p9(e)!==null&&typeof e.filename=="string"&&e.filename.trim().length>0?e.filename.trim():QK(e.filename||e.url),g9=H.memo(({files:e,onShowPopup:t,className:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(null),a=H.useRef(null),l=H.useMemo(()=>e.filter(b=>b.type==="file"&&(b.filename||b.mime||b.url)),[e]),d=l.length,f=H.useCallback(()=>{const b=a.current?.closest('[data-slot="dialog-content"], [role="dialog"]');i(b||null)},[]),u=H.useCallback(b=>{re.getState().navigateToDiagram(b),s(!1)},[]);if(d===0)return null;const h=l[0],m=fm(h),g=m9(h.size),x=d===1?`${m}${g?` (${g})`:""}`:`${d} attachments`;return c.jsxs(z5,{open:r,onOpenChange:s,children:[c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(U5,{render:c.jsxs("button",{ref:a,type:"button",className:R("inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 text-xs font-medium","text-subtle-foreground hover:text-foreground transition-colors cursor-pointer select-none",n),"aria-label":`View ${d} attachment${d!==1?"s":""}`,onPointerDownCapture:f,onFocusCapture:f,children:[c.jsx($,{name:"attachment-2",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate max-w-[200px]",children:x}),c.jsx($,{name:r?"arrow-up-s":"arrow-down-s",className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})})}),c.jsx(Ct,{side:"top",children:d===1?`Attachment: ${m}`:`View ${d} attachments`})]}),c.jsx(q5,{container:o||void 0,children:c.jsx(W5,{side:"top",align:"end",sideOffset:6,collisionPadding:8,children:c.jsxs(K5,{style:a4,className:R(i4,"w-84 max-h-96 overflow-y-auto p-3 space-y-3 transition-all duration-150 ease-out scrollbar-thin","data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95"),children:[c.jsx("div",{className:"flex items-center justify-between border-b border-border/30 pb-2",children:c.jsxs("span",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[c.jsx($,{name:"attachment-2",className:"h-3.5 w-3.5 text-muted-foreground"}),"Attachments (",d,")"]})}),c.jsx("div",{className:"space-y-3 divide-y divide-border/20",children:l.map((b,S)=>{const y=b.url||`${fm(b)}-${S}`;return c.jsx(eG,{file:b,onShowPopup:t,onNavigateToDiagram:u},y)})})]})})})]})}),eG=H.memo(function({file:t,onShowPopup:n,onNavigateToDiagram:r}){const s=fm(t),o=JK(s),i=m9(t.size),l=!!(t.mime?.startsWith("image/")&&t.url),d=p9(t),f=t.source,u=typeof f?.type=="string"?f.type:void 0,h=f&&typeof f.path=="string"?f.path:void 0,m=u==="file"&&h?h:t.url||"",g=m&&R3(m),x=H.useCallback(()=>{n&&t.url&&n({open:!0,title:s,content:"",image:{url:t.url,mimeType:t.mime,filename:s,size:t.size}})},[n,t.url,t.mime,t.size,s]),b=H.useCallback(v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),x())},[x]),S=c.jsxs("div",{className:"flex items-start gap-2.5",children:[c.jsx(pr,{filePath:s,extension:o,className:"size-5 shrink-0 mt-0.5"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"text-xs font-medium text-foreground truncate",title:s,children:s}),c.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:[o.toUpperCase()||"FILE",t.mime,i].filter(Boolean).join(" · ")})]}),d&&t.url?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),ja(t.url||"")},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open on GitHub","aria-label":"Open on GitHub",children:c.jsx($,{name:"github",className:"h-4 w-4"})}):g?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),r(m)},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open in diagram view","aria-label":"Open in diagram view",children:c.jsx($,{name:"external-link",className:"h-4 w-4"})}):null]});if(!l||!t.url)return c.jsx("div",{className:"pt-3 first:pt-0 space-y-2",children:S});const y=t.url;return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx("div",{role:"button",tabIndex:0,"aria-label":`Preview ${s}`,onClick:x,onKeyDown:b,className:"pt-3 first:pt-0 space-y-2 cursor-pointer rounded-lg",children:S})}),c.jsx(Ct,{side:"left",className:R(D3),children:c.jsx(O3,{imageUrl:y,filename:s,metaLine:[o.toUpperCase(),i].filter(Boolean).join(" · ")})})]})});g9.displayName="UserMessageAttachments";const y9=e=>{if(e==="12h")return!0;if(e==="24h")return!1},tG=(e,t,n={})=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleTimeString("en-US",{hour:n.hour??"numeric",minute:"2-digit",second:n.precision==="second"?"2-digit":void 0,hour12:y9(t)}):n.fallback??""},$Q=(e,t,n)=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleString("en-US",{...n,hour12:n.hour?y9(t):n.hour12}):""},v9=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),nG=(e,t)=>{const n=new Date(t);return n.setDate(t.getDate()-1),v9(e,n)},rG=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),x9=(e,t)=>{if(!rG(e))return"";const n=new Date(e),r=new Date,s=tG(n,t),o="en-US";if(v9(n,r))return s;if(nG(n,r))return`Yesterday ${s}`;const i=n.toLocaleString(o,{month:"short"}),a=n.getDate(),l=`${i} ${a}`;return n.getFullYear()===r.getFullYear()?`${l}, ${s}`:`${l}, ${n.getFullYear()}, ${s}`},sG=e=>{const[t,n]=p.useState(()=>{if(!e)return!1;const r=qe().getState().reducer.bySession.get(e);return r?.lifecycle==="busy"||r?.lifecycle==="retry"});return p.useEffect(()=>{if(!e){n(!1);return}const r=()=>{const s=qe().getState().reducer.bySession.get(e);n(s?.lifecycle==="busy"||s?.lifecycle==="retry")};return r(),qe().subscribe(r,`session:${e}`)},[e]),t},oG=e=>e.includes(":")?e.split(":")[0]??e:e,zd=(e,t,n)=>{const r=he(d=>d.revertToMessage),s=he(d=>d.forkFromMessage),o=sG(t),[i,a]=p.useState(!1);return{run:p.useCallback(async()=>{if(!t||!n||i||o)return;const d=oG(n);a(!0);try{e==="revert"?(await r(t,d),Ce.success("Reverted — conversation rewound. Files on disk were not changed.")):(await s(t,d),Ce.success("Forked — new session created from this message."))}catch(f){const u=e==="revert"?"Failed to revert conversation":"Failed to fork session";Ce.error(f instanceof Error?f.message:u)}finally{a(!1)}},[i,s,o,e,n,r,t]),busy:i,disabled:i||o||!t||!n}},cg=p.memo(({sessionId:e,messageId:t,size:n="user",isLatestMessage:r=!1})=>{const{run:s,busy:o,disabled:i}=zd("revert",e,t),a=p.useCallback(f=>{f.stopPropagation(),f.preventDefault(),s()},[s]),l=n==="user"?"h-6 w-6":"h-8 w-8",d=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return r?null:c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",disabled:i,"aria-label":"Revert conversation to here",className:R(l,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",i&&"opacity-50"),onPointerDown:f=>f.stopPropagation(),onClick:a,children:o?c.jsx($,{name:"loader-4",className:R(d,"animate-spin"),"aria-hidden":"true"}):c.jsx($,{name:"history",className:d,"aria-hidden":"true"})})}),c.jsx(Ct,{sideOffset:6,children:"Revert to here"})]})});cg.displayName="MessageRevertAction";const lg=p.memo(({sessionId:e,messageId:t,size:n="user"})=>{const{run:r,busy:s,disabled:o}=zd("fork",e,t),i=p.useCallback(d=>{d.stopPropagation(),d.preventDefault(),r()},[r]),a=n==="user"?"h-6 w-6":"h-8 w-8",l=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",disabled:o,"aria-label":"Fork conversation from here",className:R(a,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",o&&"opacity-50"),onPointerDown:d=>d.stopPropagation(),onClick:i,children:s?c.jsx($,{name:"loader-4",className:R(l,"animate-spin"),"aria-hidden":"true"}):c.jsx($,{name:"git-branch",className:l,"aria-hidden":"true"})})}),c.jsx(Ct,{sideOffset:6,children:"Fork to new session"})]})});lg.displayName="MessageForkAction";const dg=p.memo(({sessionId:e,messageId:t,showRevert:n,onSaveImage:r,saveImageDisabled:s=!1,size:o="user"})=>{const i=zd("revert",e,t),a=zd("fork",e,t),l=p.useRef(null),d=i.busy||a.busy;return c.jsxs(Fa,{children:[c.jsx(Ba,{asChild:!0,children:c.jsx(be,{ref:l,type:"button",variant:"ghost",size:"icon","aria-label":"More message actions",className:R(o==="user"?"h-6 w-6":"h-8 w-8","text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50"),onPointerDown:f=>f.stopPropagation(),children:d?c.jsx($,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):c.jsx($,{name:"more-fill",className:"h-3.5 w-3.5","aria-hidden":"true"})})}),c.jsxs(Va,{align:"end",className:"min-w-44",children:[n?c.jsx(ur,{disabled:i.disabled,onSelect:()=>{i.run()},children:"Revert to here"}):null,c.jsx(ur,{disabled:a.disabled,onSelect:()=>{a.run()},children:"Fork to new session"}),r?c.jsx(ur,{disabled:s,onSelect:()=>{l.current&&r(l.current)},children:"Save as image"}):null]})]})});dg.displayName="MessageMoreActions";const iG=e=>{if(!e||typeof e!="object")return null;const t=typeof e.providerID=="string"?e.providerID.trim():"",n=typeof e.modelID=="string"?e.modelID.trim():"";return!t||!n?null:`${t}/${n}`},aG=({part:e})=>{const[t,n]=p.useState(!1),r=Xn(),s=he(m=>m.setCurrentSession),o=Ga(),i=typeof e.description=="string"?e.description.trim():"",a=typeof e.command=="string"?e.command.trim():"",l=typeof e.agent=="string"?e.agent.trim():"",d=typeof e.prompt=="string"?e.prompt.trim():"",f=typeof e.taskSessionID=="string"?e.taskSessionID.trim():"",u=iG(e.model),h=p.useCallback(()=>{!r||!f||(s(f,r),o?.closeDrawers?.())},[r,f,s,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Delegated task"}),a?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:["/",a]}):null,l?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:["@",l]}):null,u?c.jsx("span",{className:"inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none bg-foreground/5 text-muted-foreground",children:u}):null]}),i?c.jsx("div",{className:"typography-ui-label text-foreground mt-1.5",children:i}):null,d?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>n(m=>!m),children:t?"Hide prompt":"Show prompt"}),t?c.jsx("pre",{className:"typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85","data-no-drawer-swipe":"true",children:d}):null]}):null,f?c.jsx("div",{className:"mt-1.5",children:c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:h,children:"Open subtask session"})}):null]})},Fx={background:"transparent",backgroundColor:"transparent"},cG=({part:e})=>{const t=typeof e.shellAction?.output=="string"?e.shellAction.output:"",[n,r]=p.useState(!0),{value:s,show:o}=U1(!1,2e3),i=typeof e.shellAction?.command=="string"?e.shellAction.command.trim():"",a=typeof e.shellAction?.status=="string"?e.shellAction.status.trim().toLowerCase():"",l=t.trim().length>0,d=p.useCallback(async()=>{!l||!(await yr(t)).ok||o(!0)},[l,t,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Shell command"}),a?c.jsx("span",{className:R("inline-flex h-5 items-center rounded px-1.5 typography-micro leading-none",a==="error"?"bg-[var(--status-error-background)] text-[var(--status-error)]":"bg-foreground/5 text-muted-foreground"),children:a}):null]}),i?c.jsx("div",{className:"typography-meta mt-1.5 overflow-x-auto font-mono","data-no-drawer-swipe":"true",children:c.jsx(Bd,{language:"bash",code:i,codeStyle:Fx,wrap:!0})}):null,l?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>r(f=>!f),children:n?"Hide output":"Show output"}),c.jsx("button",{type:"button",className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:()=>{d()},"aria-label":s?"Copied":"Copy output",title:s?"Copied":"Copy output",children:s?c.jsx($,{name:"check",className:"h-3.5 w-3.5"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})]}),n?c.jsx("div",{className:"typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85",children:c.jsx(Bd,{language:"bash",code:t,codeStyle:Fx,wrap:!0})}):null]}):null]})},lG={contain:"layout",transform:"translateZ(0)"},dG=p.memo(function({sessionId:t,messageId:n,parts:r,messageCreatedAt:s,isLatestMessage:o=!1,isMobile:i,alwaysShowActions:a=i,hasTouchInput:l,hasTextContent:d,onCopyMessage:f,copiedMessage:u,onShowPopup:h,agentMention:m,userActionsMode:g="inline"}){const x=re(z=>z.timeFormatPreference),[b,S]=p.useState(!1),y=p.useRef(null),v=p.useMemo(()=>r.filter(a9),[r]),C=p.useMemo(()=>r.filter(z=>z.type==="file"&&!!(z.filename||z.mime||z.url)),[r]),w=m?.token;let I=!1;const E=!!f,T=!!u,A=!!(l??i),j=!!d,k=g!=="external-actions",_=g!=="external-content",M=p.useCallback(()=>{y.current!==null&&typeof window<"u"&&(window.clearTimeout(y.current),y.current=null)},[]),L=p.useCallback(()=>{!A||!E||!j||typeof window>"u"||(M(),S(!0),y.current=window.setTimeout(()=>{S(!1),y.current=null},1800))},[E,M,j,A]);p.useEffect(()=>{j||(S(!1),M())},[M,j]);const O=p.useCallback(z=>{!f||!j||(z.stopPropagation(),z.preventDefault(),f(),A&&L())},[j,A,f,L]),N=p.useMemo(()=>{if(typeof s!="number"||s<=0)return null;const z=x9(s,x);return z.length>0?z:null},[s,x]),D=i||a,W=_?c.jsx("div",{className:R("group/user-actions",D?g==="inline"?"mt-2 mb-1 flex items-center justify-end":"flex min-h-11 items-start justify-end pt-0":g==="inline"?"absolute top-full left-0 right-0 z-10 pt-5":"flex min-h-8 items-start justify-end pt-2"),children:c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-1",children:[c.jsxs("div",{className:R("flex items-center justify-start gap-1.5",g==="inline"?"translate-x-5":"translate-x-0",a?"pointer-events-auto opacity-100":"pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100 group-hover/user-shell:pointer-events-auto group-hover/user-shell:opacity-100"),children:[N?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("span",{className:"mr-1 flex items-center gap-1 typography-meta tabular-nums text-subtle-foreground","aria-label":`Message time: ${N}`,children:[c.jsx($,{name:"time",className:"size-3"}),c.jsx("span",{className:"message-footer__label",children:N})]})}),c.jsx(Ct,{children:N})]}):null,!A&&!o?c.jsx(cg,{sessionId:t??null,messageId:n,size:"assistant"}):null,A?null:c.jsx(lg,{sessionId:t??null,messageId:n,size:"assistant"}),E&&j&&c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon","data-visible":b||T?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:z=>z.stopPropagation(),onClick:O,onFocus:()=>S(!0),onBlur:()=>{T||S(!1)},children:T?c.jsx($,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:"Copy message"})]}),A?c.jsx(dg,{sessionId:t??null,messageId:n,showRevert:!o,size:"assistant"}):null]}),C.length>0?c.jsx(g9,{files:C,onShowPopup:h}):null]})}):null;return k?c.jsxs("div",{className:"relative w-full group/message",style:lG,onTouchStart:A&&E&&j?L:void 0,children:[c.jsx("div",{className:R("leading-relaxed text-foreground text-base overflow-x-hidden","overflow-y-hidden"),style:void 0,children:v.map((z,X)=>{if(s9(z))return c.jsx(p.Fragment,{children:c.jsx(aG,{part:z})},z.id??`user-subtask-${X}`);if(o9(z))return c.jsx(p.Fragment,{children:c.jsx(cG,{part:z})},z.id??`user-shell-${X}`);let F;return m&&w&&!I&&og(z).includes(w)&&(F=m,I=!0),c.jsx(p.Fragment,{children:c.jsx(ZK,{part:z,messageId:n,isMobile:i,agentMention:F})},z.id??`user-text-${X}`)})}),W]}):c.jsx(c.Fragment,{children:W})}),Bx=8,uG=280,fG=({containerRef:e})=>{const[t,n]=p.useState({x:0,y:0,show:!1}),[r,s]=p.useState(""),[o,i]=p.useState(""),a=p.useRef(!1),[l,d]=p.useState(!1),f=p.useRef(null),u=p.useRef(uG),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(!1),b=he(j=>j.createSession),S=Ye(j=>j.setPendingInputText),y=re(j=>j.isMobile);p.useEffect(()=>{x.current=t.show},[t.show]),p.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),g.current!==null&&(window.clearTimeout(g.current),g.current=null)},[]);const v=p.useCallback(()=>{h.current=null,x.current&&(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),d(!1),n(j=>({...j,show:!1})),s(""),i(""),x.current=!1)},[]),C=p.useCallback(j=>{if(typeof window>"u")return j;const k=window.innerWidth,M=u.current/2,L=Bx+M,O=k-Bx-M;return L>O?k/2:Math.min(Math.max(j,L),O)},[]),w=p.useCallback(()=>{if(!h.current)return;const{plainText:j,markdownText:k,rect:_}=h.current,M=!t.show,L=y?_.left+_.width/2:C(_.left+_.width/2),O=_.top-10;s(j),i(k),n({x:L,y:O,show:!0}),x.current=!0,M&&(d(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{d(!1),m.current=null}))},[C,y,t.show]);p.useLayoutEffect(()=>{if(!t.show||y||!f.current)return;const j=f.current.offsetWidth;!Number.isFinite(j)||j<=0||j===u.current||(u.current=j,n(k=>({...k,x:C(k.x)})))},[C,y,t.show]),p.useEffect(()=>{if(!t.show||y)return;const j=()=>{n(k=>({...k,x:C(k.x)}))};return window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j)}},[C,y,t.show]);const I=p.useCallback(()=>{const j=window.getSelection(),k=e.current;if(!j||!k){a.current||v();return}const _=wn(j.toString());if(!_){a.current||v();return}const M=j.getRangeAt(0);if(!k.contains(M.commonAncestorContainer)){a.current||v();return}const L=M.getBoundingClientRect();h.current={plainText:_,markdownText:g3(M,_),rect:L},a.current||w()},[e,v,w]);p.useEffect(()=>{const j=e.current;if(!j)return;const k=()=>{a.current=!0,v()},_=()=>{a.current=!1,h.current&&(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null;const L=window.getSelection();L&&L.toString().trim()?w():v()},10))};document.addEventListener("selectionchange",I),j.addEventListener("mousedown",k),document.addEventListener("mouseup",_);const M=L=>{f.current&&!f.current.contains(L.target)&&!window.getSelection()?.toString().trim()&&v()};return document.addEventListener("mousedown",M),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),document.removeEventListener("selectionchange",I),j.removeEventListener("mousedown",k),document.removeEventListener("mouseup",_),document.removeEventListener("mousedown",M)}},[e,I,v,w]);const E=p.useCallback(()=>{if(!o)return;const j=x1(o);S(j,"append"),v(),window.getSelection()?.removeAllRanges(),queueMicrotask(()=>{To()})},[o,S,v]),T=p.useCallback(async()=>{if(!r)return;await b(void 0,null,null)&&S(r,"replace"),v(),window.getSelection()?.removeAllRanges()},[r,b,S,v]),A=p.useCallback(async()=>{if(!r)return;const j=await yr(r);j.ok||console.error("Failed to copy:",j.error),v(),window.getSelection()?.removeAllRanges()},[r,v]);return t.show?y?ba.createPortal(c.jsx("div",{ref:f,className:R("fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]","rounded-2xl border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] p-2 shadow-lg","safe-area-bottom","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",l?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),style:{bottom:"calc(0.5rem + env(safe-area-inset-bottom, 0px))"},children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("button",{onClick:E,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--primary-base)] text-[var(--primary-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Add to current chat",type:"button",children:[c.jsx($,{name:"add",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Add to chat"})]}),c.jsxs("button",{onClick:T,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Create new session with selection",type:"button",children:[c.jsx($,{name:"chat-new",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"New session"})]}),c.jsxs("button",{onClick:A,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--surface-muted)] text-[var(--surface-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Copy",type:"button",children:[c.jsx($,{name:"file-copy",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Copy"})]})]})}),document.body):ba.createPortal(c.jsx("div",{ref:f,className:"fixed z-50",style:{left:t.x,top:t.y,transform:"translate(-50%, -100%)"},children:c.jsxs("div",{className:R("flex items-center gap-1 whitespace-nowrap","rounded-lg border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-none","px-1.5 py-1","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",l?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),children:[c.jsxs("button",{onClick:E,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Add to current chat",type:"button",children:[c.jsx($,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"Add to chat"})]}),c.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),c.jsxs("button",{onClick:T,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Create new session with selection",type:"button",children:[c.jsx($,{name:"chat-new",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"New session"})]})]})}),document.body):null},ul=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function hG(e){if(!e||e==="build")return ul[0];let t=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}const n=1+Math.abs(t)%(ul.length-1);return ul[n]}const pG=p.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,onShareImage:r,sessionId:s,messageId:o,isLatestMessage:i=!1})=>{const a=Iu(),[l,d]=p.useState(!1),{value:f,show:u,clear:h}=U1(!1,2e3),[m,g]=p.useState(!1),x=p.useRef(null),b=!!n,S=p.useCallback(()=>{x.current!==null&&typeof window<"u"&&(window.clearTimeout(x.current),x.current=null)},[]);p.useEffect(()=>S,[S]),p.useEffect(()=>{(!e||!b)&&(d(!1),S(),h())},[b,S,h,e]);const y=p.useCallback(()=>{!t||!b||!e||typeof window>"u"||(S(),d(!0),x.current=window.setTimeout(()=>{d(!1),x.current=null},1800))},[b,S,e,t]),v=p.useCallback(async E=>{!n||!e||(E.stopPropagation(),E.preventDefault(),await n()===!1)||(u(!0),t&&y())},[e,t,n,y,u]),C=p.useCallback(async E=>{if(!(m||!e)){g(!0);try{const A=E.closest("[data-message-text-export-root]")?.querySelector("[data-message-text-export-source]")??null;await r(A)}finally{g(!1)}}},[e,m,r]),w=p.useCallback(async E=>{E.stopPropagation(),E.preventDefault(),await C(E.currentTarget)},[C]),I=t&&!!(s&&o);return c.jsxs(c.Fragment,{children:[!I&&s&&o&&!i?c.jsx(cg,{sessionId:s,messageId:o,size:"assistant"},"message-revert"):null,!I&&s&&o?c.jsx(lg,{sessionId:s,messageId:o,size:"assistant"},"message-fork"):null,n&&c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon","data-visible":l||f?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!e&&"opacity-50"),disabled:!e,"aria-label":"Copy message text","aria-hidden":!e,onPointerDown:E=>E.stopPropagation(),onClick:E=>{v(E)},onFocus:()=>{e&&d(!0)},onBlur:()=>{f||d(!1)},children:f?c.jsx($,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(Ct,{sideOffset:6,children:"Copy answer"})]},"message-copy"),I&&o?c.jsx(dg,{sessionId:s,messageId:o,showRevert:!i,size:"assistant",onSaveImage:a!=="mini-chat"?E=>{C(E)}:void 0,saveImageDisabled:m||!e},"message-more"):null,!I&&a!=="mini-chat"?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",size:"icon",variant:"ghost",disabled:m||!e,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",(!e||m)&&"opacity-50"),onPointerDown:E=>E.stopPropagation(),onClick:E=>{w(E)},children:m?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"image-download",className:"h-4 w-4"})})}),c.jsx(Ct,{sideOffset:6,children:m?"Saving image...":"Save as image"})]},"message-share"):null]})});async function mG(e,t){const n=t;if(!n)return;let r=null;try{const{toPng:s}=await mt(async()=>{const{toPng:y}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{toPng:y}},[]),o=n,i=window.getComputedStyle(o),l=window.getComputedStyle(document.documentElement).getPropertyValue("--surface-background").trim()||i.backgroundColor||window.getComputedStyle(document.body).backgroundColor,d=24;r=document.createElement("div"),r.setAttribute("data-message-image-export","true"),r.style.cssText=`
204
- padding: ${d}px;
205
- background-color: ${l};
206
- display: inline-block;
207
- `;const f=o.cloneNode(!0);f.style.cssText=`
208
- ${i.cssText}
209
- transform: none;
210
- contain: none;
211
- `,f.querySelectorAll('[data-message-actions="true"]').forEach(y=>{y.style.display="none"}),f.querySelectorAll('[data-message-action-group="true"]').forEach(y=>{y.style.display="none"});const m=f.querySelectorAll('[aria-label^="Message time:"]'),g=new Set;m.forEach(y=>{const C=y.getAttribute("aria-label")?.replace("Message time:","").trim();if(!C||y.textContent?.includes(C))return;const w=document.createElement("span");w.style.marginLeft="4px",w.textContent=C,y.appendChild(w);const E=y.parentElement?.parentElement;!E||g.has(E)||(E.style.justifyContent="flex-start",g.add(E))}),r.appendChild(f),document.body.appendChild(r);const x=await s(r,{quality:1,pixelRatio:2,backgroundColor:l}),b=`message-${e}.png`,S=await V8({filename:b,mimeType:"image/png",data:x});S==="downloaded"?Ce.success("Image saved"):S==="shared"&&Ce.success("Image shared")}catch(s){console.error("Failed to generate image:",s),Ce.error("Failed to generate image")}finally{r&&r.parentNode&&r.parentNode.removeChild(r)}}function gG({visibleParts:e,isMessageCompleted:t,messageFinish:n,messageCompletedAt:r,messageCreatedAt:s,turnGroupingContext:o,errorMessage:i,isMobile:a,isMiniChatSurface:l,timeFormatPreference:d}){const f=p.useMemo(()=>e.filter(v=>v.type==="text"),[e]),u=p.useMemo(()=>{if(a||l)return null;for(const v of f){const C=v.text;if(typeof C!="string"||C.length===0)continue;const w=GT(C)[0];if(w)return w.includes("0.0.0.0")?w.replace("0.0.0.0","127.0.0.1"):w}return null},[f,a,l]),h=o?.isLastAssistantInTurn??!1,m=!!o?.isWorking,g=p.useRef(m),x=g.current&&!m;p.useEffect(()=>{g.current=m},[m]);const b=n==="stop"||t&&!i,S=!t,y=p.useMemo(()=>{const v=typeof r=="number"&&r>0?r:typeof s=="number"&&s>0?s:null;if(v===null)return null;const C=x9(v,d);return C.length>0?C:null},[r,s,d]);return{messagePreviewUrl:u,isLastAssistantInTurn:h,isTurnWorking:m,shouldAnimateTurnFooter:x,hasStopFinish:b,awaitingMessageCompletion:S,footerTimestamp:y}}const yG={contain:"layout",transform:"translateZ(0)"},vG={containerType:"inline-size",containerName:"message-footer"},xG=p.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,isLatestMessage:a=!1,isMobile:l,alwaysShowActions:d,hasTouchInput:f,onShowPopup:u,streamPhase:h,onContentChange:m,hasTextContent:g=!1,onCopyMessage:x,turnGroupingContext:b,errorMessage:S,errorVariant:y="error",footerProviderID:v,footerModelName:C,footerAgentName:w,footerVariant:I,isDarkTheme:E=!1})=>{const T=Iu(),A=p.useRef(null),j=p.useRef(null),k=!!(f??l),_=!!(d??l),{src:M,onError:L,hasLogo:O}=I1(v??null),N=p.useMemo(()=>ig(n),[n]),D=T==="mini-chat",W=he(te=>te.currentSessionId),z=he(te=>te.getDirectoryForSession),X=Xn(),F=re(te=>te.timeFormatPreference),U=re(te=>te.openContextPreview),{messagePreviewUrl:P,isLastAssistantInTurn:q,isTurnWorking:B,shouldAnimateTurnFooter:ee,hasStopFinish:G,awaitingMessageCompletion:K,footerTimestamp:se}=gG({visibleParts:N,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,turnGroupingContext:b,errorMessage:S,isMobile:l,isMiniChatSurface:D,timeFormatPreference:F}),le=G?"completed":h,oe=!!g&&!K,ue=p.useCallback(async te=>{const Q=te??j.current??A.current;await mG(t,Q)},[t]),ye=!!S,we=y==="info"?"information":"error-warning",Me=q&&(g||!!S)&&!B,He=p.useMemo(()=>c.jsx(pG,{hasCopyableText:oe,isTouchContext:k,onCopyMessage:x,onShareImage:ue,sessionId:e,messageId:t,isLatestMessage:a}),[ue,oe,a,k,t,x,e]),Ae=p.useMemo(()=>{const te=[];let Q=0;for(;Q<N.length;){const me=N[Q];if(me.type!=="text"){Q++;continue}te.push(c.jsx("div",{ref:j,"data-message-text-export-source":"true",children:c.jsx(v7,{part:me,sessionId:e,messageId:t,streamPhase:le,onContentChange:m,onShowPopup:u})},`assistant-text-${t}-${Q}`)),Q++}return te},[t,e,m,u,le,N]),Ge="typography-meta text-muted-foreground tabular-nums flex items-center gap-1",et=!D&&!l,Xe=c.jsx(c.Fragment,{children:et&&P?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsx(be,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Open preview",onPointerDown:te=>te.stopPropagation(),onClick:()=>{const te=X??(W?z(W):null);te&&U(te,P)},children:c.jsx($,{name:"global",className:"h-4 w-4"})})}),c.jsx(Ct,{sideOffset:6,children:"Open preview"})]}):null});return c.jsxs("div",{ref:A,"data-message-text-export-root":"true",className:R("relative w-full group/message"),style:yG,children:[c.jsx(fG,{containerRef:A}),c.jsxs("div",{children:[c.jsxs("div",{className:"message-content-text space-y-2 leading-relaxed overflow-hidden text-foreground [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ae,ye&&c.jsx(sg,{children:c.jsx("div",{className:R("group/assistant-text relative mt-3 p-3 rounded-lg border break-words max-w-full",y==="info"?"bg-[var(--status-info-background)] border-[var(--status-info-border)]":"bg-[var(--status-error-background)] border-[var(--status-error-border)]"),children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx($,{name:we,className:R("h-4 w-4 shrink-0",y==="info"?"text-[var(--status-info)]":"text-[var(--status-error)]")}),c.jsx("div",{className:"min-w-0 flex-1 break-words",children:c.jsx(Wa,{content:S??"",onShowPopup:u,className:"[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",enableFileReferences:!1})})]})})},"assistant-error")]}),c.jsx(M1,{files:n,onShowPopup:u}),Me&&c.jsxs("div",{className:R("mt-2 mb-1 flex flex-wrap items-center justify-start gap-x-3 gap-y-1.5",ee&&"message-footer-enter"),style:vG,children:[c.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1 typography-meta text-muted-foreground",children:[C?c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[O&&M?c.jsx("img",{src:M,alt:"",className:"h-3.5 w-3.5 flex-shrink-0",style:{filter:E?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:L}):c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0",style:{color:`var(${hG(w).var})`}}),c.jsx("span",{className:"truncate",children:C})]}):null,I&&!["default","none"].includes(I.toLowerCase())?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:I[0].toLowerCase()+I.slice(1)})]}):null,w?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx($,{name:"ai-agent",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:w})]}):null,se?c.jsxs(wt,{children:[c.jsx(St,{asChild:!0,children:c.jsxs("span",{className:R(Ge,"message-footer__timestamp"),"aria-label":`Message time: ${se}`,children:[c.jsx($,{name:"time",className:"h-3.5 w-3.5"}),c.jsx("span",{className:"message-footer__label",children:se})]})}),c.jsx(Ct,{children:se})]}):null]}),c.jsxs("div",{className:R("flex items-center gap-1.5",_||k?void 0:"pointer-events-none opacity-0 transition-opacity duration-150 focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100"),"data-message-action-group":"true",children:[He,Xe]})]})]})]})}),jh=p.memo(({isUser:e,...t})=>e?c.jsx(dG,{sessionId:t.sessionId,messageId:t.messageId,parts:t.parts,messageCreatedAt:t.messageCreatedAt,isMobile:t.isMobile,alwaysShowActions:t.alwaysShowActions,hasTouchInput:t.hasTouchInput,hasTextContent:t.hasTextContent,onCopyMessage:t.onCopyMessage,copiedMessage:t.copiedMessage,onShowPopup:t.onShowPopup,agentMention:t.agentMention,userActionsMode:t.userActionsMode}):c.jsx(xG,{...t})),Ud=e=>{const t=e,n=t?.clientRole,r=t?.role;return t?.userMessageMarker===!0||n==="user"||r==="user"||t?.origin==="user"||t?.source==="user"?{role:"user",isUser:!0}:{role:n||r||"assistant",isUser:!1}},b9="GitHub issue context (JSON)",w9="GitHub pull request context (JSON)",Vx=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,$x=(e,t)=>{const n=e.trimStart();if(!n.startsWith(t))return null;const r=n.indexOf("{");if(r<0)return null;try{return JSON.parse(n.slice(r))}catch{return null}},bG=e=>{const t=$x(e,b9);if(t){const r=t.issue,s=r?.number,o=r?.title,i=r?.url;return!Vx(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.issue-link",filename:`Issue #${s}: ${o}`,url:i}}const n=$x(e,w9);if(n){const r=n.pr,s=r?.number,o=r?.title,i=r?.url;return!Vx(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.pull-request-link",filename:`PR #${s}: ${o}`,url:i}}return null},wG=e=>!!e.trim().startsWith("The following tool was executed by the user"),ug=e=>e.filter(t=>{if(!(t.synthetic===!0))return!0;if(t.type!=="text")return!1;const r=t.text;if(typeof r!="string")return!1;const s=r.trimStart();return wG(r)||s.startsWith(b9)||s.startsWith(w9)}).map(t=>{const n=t;if(n.type==="compaction")return{type:"text",text:"/compact"};if(n.type==="text"){const r=typeof n.text=="string"?n.text.trim():"";if(n.synthetic===!0){const o=bG(r);if(o)return o}if(r.startsWith("The following tool was executed by the user"))return{type:"text",text:"/shell"}}return t}),zx=new WeakMap,S9=e=>{if(!e||!Ud(e.info).isUser)return!1;const t=zx.get(e.parts);if(t!==void 0)return t;const n=ug(Au(e.parts)),r=ag(n,{includeReasoning:!0}).length===0;return zx.set(e.parts,r),r};function Th(e){const[t,n]=p.useState(e);return p.useEffect(()=>{e!=null&&n(e)},[e]),e??t}const xn=(e,t)=>{if(typeof e=="object"&&e!==null)return e[t]},ps=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Ux=e=>{const t=xn(e,"model"),n=typeof t=="object"&&t!==null?t:null;return{providerId:ps(xn(e,"providerID"))??ps(n?.providerID)??ps(n?.providerId),modelId:ps(xn(e,"modelID"))??ps(n?.modelID)??ps(n?.modelId)}};function SG({message:e,previousMessage:t,isUser:n,sessionId:r,isInActiveTurn:s,turnGroupingContext:o}){const i=We(_=>_.providers),a=Lt(_=>_.getAgentModelForSession),l=Lt(_=>_.getSessionModelSelection),d=Lt(F8(_=>s&&r?_.sessionAgentSelections.get(r)??null:null)),f=p.useMemo(()=>{if(n||!t)return null;const _=xn(t.info,"clientRole"),M=xn(t.info,"role");if((typeof _=="string"?_:typeof M=="string"?M:void 0)!=="user")return null;const O=xn(t.info,"mode"),N=xn(t.info,"agent"),D=Ux(t.info),W=xn(t.info,"variant"),z=typeof O=="string"&&O.trim().length>0?O:typeof N=="string"&&N.trim().length>0?N:void 0,X=D.providerId,F=D.modelId,U=typeof W=="string"&&W.trim().length>0?W:void 0;return!z&&!X&&!F&&!U?null:{agentName:z,providerId:X,modelId:F,variant:U}},[n,t]),u=p.useMemo(()=>{if(n)return;const _=xn(e.info,"mode");if(typeof _=="string"&&_.trim().length>0)return _;const M=xn(e.info,"agent");if(typeof M=="string"&&M.trim().length>0)return M;if(f?.agentName)return f.agentName;if(r)return d??void 0},[n,e.info,f,r,d]),h=n?{providerId:void 0,modelId:void 0}:Ux(e.info),m=h.providerId??null,g=h.modelId??null,x=p.useMemo(()=>{if(n||!r)return null;if(f?.providerId&&f?.modelId)return{providerId:f.providerId,modelId:f.modelId};if(u){const M=a(r,u);if(M?.providerId&&M?.modelId)return M}const _=l(r);return _?.providerId&&_?.modelId?_:null},[n,r,u,f,a,l]),b=p.useMemo(()=>n?null:typeof m=="string"&&m.trim().length>0?m:x?.providerId??null,[n,m,x]),S=p.useMemo(()=>n?null:typeof g=="string"&&g.trim().length>0?g:x?.modelId??null,[n,g,x]),y=p.useMemo(()=>{if(n)return;const _=b&&i.length>0?i.find(M=>M.id===b):void 0;return j1(_,S)||void 0},[n,b,S,i]),v=p.useMemo(()=>{if(n||!b||!S)return!1;const _=i.find(O=>O.id===b);if(!_?.models||!Array.isArray(_.models))return!1;const L=_.models.find(O=>O.id===S)?.variants;return!!(L&&Object.keys(L).length>0)},[n,S,b,i]),C=Th(u),w=Th(b??void 0),I=Th(y),E=C??void 0,T=w??null,A=I??void 0,j=n?void 0:ps(xn(e.info,"variant"))??o?.userMessageVariant??f?.variant;return{headerAgentName:E,headerProviderID:T,headerModelName:A,headerVariant:n?void 0:v?j??"Default":j}}class ks{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return ks.instance||(ks.instance=new ks),ks.instance}recordSessionStart(t){this.sessionStartTimes.set(t,Date.now())}getSessionStartTime(t){return this.sessionStartTimes.get(t)}shouldAnimateMessage(t,n){if(t.role!=="assistant"||this.seenMessageIds.has(t.id))return!1;const r=t.time?.created;if(typeof r!="number"||!Number.isFinite(r))return this.seenMessageIds.add(t.id),!1;const s=this.sessionStartTimes.get(n);if(!s)return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),!1;const o=r>s-5e3;return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),o}clearSession(t){this.sessionStartTimes.delete(t)}hasSessionTiming(t){return this.sessionStartTimes.has(t)}hasBeenAnimated(t){return this.seenMessageIds.has(t)}markMessageAsAnimated(t,n){this.seenMessageIds.add(t),this.messageCreationTimes.set(t,n)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function CG({message:e,isUser:t,sessionId:n,streamPhase:r,assistantTextParts:s,shouldCoordinateRendering:o,animationHandlers:i,messageContainerRef:a}){const l=p.useMemo(()=>t||!n?!1:ks.getInstance().shouldAnimateMessage(e.info,n),[e.info,t,n]),d=i??null,f=p.useRef(!1),u=p.useRef(!1),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(!1);p.useEffect(()=>{f.current=!1,u.current=!1,h.current=!1,m.current=!1,g.current=!1},[e.info.id]);const x=!!xn(e.info,"animationSettled"),b=r==="streaming"||r==="cooldown";b&&(g.current=!0);const S=l&&!x&&!b&&!g.current,y=!t&&l&&s.length>0&&!o;p.useEffect(()=>{if(d?.onStreamingCandidate){if(!y){u.current&&(d?.onReservationCancelled&&d.onReservationCancelled(),u.current=!1);return}m.current||(m.current=!0,d.onStreamingCandidate(),u.current=!0)}},[d,y]),p.useEffect(()=>{d?.onAnimationStart&&S&&(h.current||(d.onAnimationStart(),h.current=!0))},[d,S]),p.useEffect(()=>{if(t)return;const v=d?.onAnimatedHeightChange;if(!v||!(S||y))return;const w=a.current;if(!w)return;if(typeof window>"u"||typeof ResizeObserver>"u"){v(w.getBoundingClientRect().height);return}let I=null;const E=A=>{if(typeof window>"u"){v(A);return}I!==null&&window.cancelAnimationFrame(I),I=window.requestAnimationFrame(()=>{v(A)})},T=new ResizeObserver(A=>{const j=A[0];j&&E(j.contentRect.height)});return T.observe(w),E(w.getBoundingClientRect().height),()=>{I!==null&&(window.cancelAnimationFrame(I),I=null),T.disconnect()}},[S,t,d,y,a])}function kG(){const e=re(o=>o.setImagePreviewOpen),[t,n]=p.useState({open:!1,title:"",content:""}),r=p.useCallback(o=>{(o.image||o.mermaid)&&(n(o),e(!0))},[e]),s=p.useCallback(o=>{n(i=>({...i,open:o})),e(o)},[e]);return{popupContent:t,handleShowPopup:r,handlePopupChange:s}}const MG=Fs(()=>mt(()=>import("./ToolOutputDialog-DdMIfrnK.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),IG=({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:s,turnGroupingContext:o,isInActiveTurn:i=!1,activeStreamingPhase:a=null,animateUserOnMount:l=!1,onUserAnimationConsumed:d})=>{const{isMobile:f,isTablet:u,hasTouchInput:h}=Dn(),m=f||u,{currentTheme:g}=vr(),x=p.useRef(null);js("ui.chat_message.render"),i&&js("ui.chat_message.render.streaming");const[b,S]=p.useState(!1),v=p.useMemo(()=>Ud(e.info),[e.info]).isUser,C=e.info.sessionID,{headerAgentName:w,headerProviderID:I,headerModelName:E,headerVariant:T}=SG({message:e,previousMessage:t,isUser:v,sessionId:C,isInActiveTurn:i,turnGroupingContext:o}),A=p.useMemo(()=>{const _e=Au(e.parts);return v?ug(_e):_e},[v,e.parts]),j=p.useMemo(()=>{const _e=e.info.time;return typeof _e?.completed=="number"?_e.completed:null},[e.info.time]),k=p.useMemo(()=>{const _e=e.info.time;return typeof _e?.created=="number"?_e.created:null},[e.info.time]),_=p.useMemo(()=>v?!0:!!(j&&j>0),[v,j]),M=p.useMemo(()=>{const _e=e.info.finish;return typeof _e=="string"?_e:void 0},[e.info]),L=p.useMemo(()=>ag(A,{includeReasoning:!0}),[A]),O=p.useMemo(()=>{const _e=new Set;for(const Fe of o?.activityParts??[])_e.add(Fe.id);return _e},[o?.activityParts]),N=p.useMemo(()=>v?L:c9(L,O,e.info.id),[O,v,e.info.id,L]),D=v&&N.some(a9),W=p.useMemo(()=>v?[]:N.filter(_e=>_e.type==="text"),[N,v]),z=p.useMemo(()=>v?[]:L.filter(_e=>_e.type==="tool"),[v,L]),{popupContent:X,handleShowPopup:F,handlePopupChange:U}=kG(),P=p.useMemo(()=>{if(!v)return;const _e=A.find(Ze=>Ze.type==="agent");if(!_e)return;const Fe=_e,ht=typeof Fe.name=="string"?Fe.name:void 0;if(!ht)return;const ge=Fe.source&&typeof Fe.source.value=="string"&&Fe.source.value.trim().length>0?Fe.source.value:`@${ht}`;return{name:ht,token:ge}},[v,A]),q=v&&N.length===0,B=!_&&typeof M!="string",ee=p.useMemo(()=>v?!1:W.length===0||z.length===0?B:!0,[W.length,z.length,B,v]),G=g?.metadata.variant,K=p.useMemo(()=>G?G==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[G]),se=p.useMemo(()=>n?Ud(n.info):null,[n]),le=!!o,oe=o?.isLastAssistantInTurn??!1,ue=p.useMemo(()=>!v&&S9(n),[v,n]),ye=p.useMemo(()=>v?!1:le?!oe:se?!se.isUser&&se.role==="assistant":!1,[le,oe,v,se]),we=p.useMemo(()=>_?"completed":i?a??"streaming":"completed",[a,i,_]);CG({message:e,isUser:v,sessionId:C,streamPhase:we,assistantTextParts:W,shouldCoordinateRendering:ee,animationHandlers:s,messageContainerRef:x}),p.useEffect(()=>{!v||!l||d?.(e.info.id)},[l,v,e.info.id,d]);const Me=p.useMemo(()=>{if(!v)return r9(e.info)},[v,e.info]),He=Me?.text,Ae=Me?.variant,Ge=p.useMemo(()=>dK({isUser:v,displayParts:N,assistantErrorText:He}),[He,N,v]),et=Ge.length>0,Xe=p.useMemo(()=>v?!1:!fK(N,He),[He,N,v]),te=p.useCallback(async()=>{let _e;if(v)_e=await yr(Ge);else{const{renderMarkdownSync:Fe}=await mt(async()=>{const{renderMarkdownSync:ht}=await import("./markdownCore-DczkEluO.js").then(ge=>ge.m);return{renderMarkdownSync:ht}},__vite__mapDeps([21,8,22,23,24]));_e=await $_(Ge,Fe(Ge))}return _e.ok?(v&&(S(!0),setTimeout(()=>S(!1),2e3)),!0):!1},[v,Ge]);if(q||Xe)return null;const Q="pt-0",me="var(--radius-xl)",Se={sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:v,isMessageCompleted:_,messageFinish:M,messageCreatedAt:k??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:F,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:te,copiedMessage:b,agentMention:P,errorMessage:He,errorVariant:Ae,isLatestMessage:!n};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:R("group w-full",v?f?"pt-2":"pt-4":Q,v?f?"pb-0":"pb-2":ye||ue?"pb-0":"pb-2"),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:x,children:c.jsx("div",{className:"chat-message-column relative",children:v?N.length===0?null:c.jsx(sg,{forceAnimation:!0,skipAnimation:!l,ignoreContextDisabled:!0,respectReducedMotion:!0,children:c.jsx("div",{className:R("relative flex justify-end",f?void 0:"group/user-shell"),children:c.jsxs("div",{className:"flex max-w-[85%] flex-col items-end",children:[D?c.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)",borderRadius:me,borderBottomRightRadius:"var(--radius-sm)"},className:R("shadow-none border border-primary/5",f?"px-3 py-2":"px-5 py-3",!f&&"pb-4"),children:c.jsx(jh,{...Se,userActionsMode:"external-content"})}):null,c.jsx(jh,{...Se,userActionsMode:"external-actions"})]})})}):c.jsx("div",{className:"relative",children:c.jsx(jh,{sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:v,isMessageCompleted:_,isLatestMessage:!n,messageFinish:M,messageCompletedAt:j??void 0,messageCreatedAt:k??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:F,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:te,copiedMessage:b,agentMention:P,turnGroupingContext:o,errorMessage:He,errorVariant:Ae,footerProviderID:I,footerModelName:E,footerAgentName:w,footerVariant:T,isDarkTheme:K})})})}),c.jsx(p.Suspense,{fallback:null,children:c.jsx(MG,{popup:X,onOpenChange:U,isMobile:f})})]})},EG=p.memo(IG,(e,t)=>I7({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&Dd(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&Dd(e.nextMessage?{info:e.nextMessage.info,parts:e.nextMessage.parts}:void 0,t.nextMessage?{info:t.nextMessage.info,parts:t.nextMessage.parts}:void 0)&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&E7(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,Ud(e.message.info).isUser)),qx={info:"bg-status-info/15 text-status-info",success:"bg-status-success/15 text-status-success",warning:"bg-status-warning/15 text-status-warning",error:"bg-status-error/15 text-status-error",neutral:"bg-interactive-hover text-muted-foreground"},_G=e=>typeof e=="string"&&e.length>0&&e in $w,jG=({action:e,variant:t,sessionId:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(""),u=H.useCallback(async b=>{if(!(!n||r)){s(!0);try{await qe().prompt(n,P5(e.command,b),"prompt")}finally{s(!1)}}},[n,r,e.command]),h=H.useCallback(async()=>{if(e.promptForArgs){l(!0),f("");return}await u(e.args)},[e,u]),m=H.useCallback(async()=>{if(!(!n||r||e.disabled)){if(e.confirm){i(!0);return}await h()}},[n,r,e,h]);if(!n)return null;const g=r||e.loading===!0,x=_G(e.icon)?c.jsx($,{name:e.icon,className:"size-3.5"}):null;return o?c.jsxs("div",{role:"alertdialog","aria-label":e.confirm,className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[c.jsx("span",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:e.confirm}),c.jsx(be,{type:"button",size:"xs",variant:"default",onClick:()=>{i(!1),h()},children:"Continue"}),c.jsx(be,{type:"button",size:"xs",variant:"ghost",onClick:()=>i(!1),children:"Cancel"})]}):a?c.jsxs("form",{className:"flex min-w-0 flex-wrap items-center gap-1.5",onSubmit:b=>{b.preventDefault(),l(!1),u(d)},children:[c.jsx("input",{autoFocus:!0,value:d,onChange:b=>f(b.target.value),placeholder:e.promptForArgs?.placeholder??"","aria-label":e.promptForArgs?.label??e.label,className:"h-6 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focus sm:w-40 sm:flex-none",onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),l(!1))}}),c.jsx(be,{type:"submit",size:"xs",variant:"default",disabled:r,children:"Run"}),c.jsx(be,{type:"button",size:"xs",variant:"ghost",onClick:()=>l(!1),children:"Cancel"})]}):c.jsxs(be,{size:"xs",variant:t,onClick:()=>{m()},disabled:g||e.disabled,"aria-label":e.label,children:[g?c.jsx("span",{"aria-hidden":"true",className:"size-3.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent"}):x,e.label]})},TG=({label:e,value:t,max:n})=>{const r=Math.min(Math.max(t,0),n),s=Math.round(r/n*100);return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:e??""}),c.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[s,"%"]})]}),c.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-interactive-hover",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":e??"Progress",children:c.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] duration-300",style:{width:`${s}%`}})})]})},AG=({body:e,messageId:t,text:n})=>{const[r,s]=H.useState(!1),o=typeof n=="string"&&n.trim().length>0;return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[o&&c.jsx(qo,{messageId:t,content:n,className:"text-sm text-foreground"}),e&&e!==n&&c.jsxs("div",{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>s(i=>!i),"aria-expanded":r,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:r?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Details"})]}),r&&c.jsx("pre",{className:"mt-1.5 max-h-64 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:c.jsx("code",{children:e})})]})]})},NG=({sessionId:e,messageId:t,customType:n,text:r,data:s,details:o,className:i})=>{const a=H.useMemo(()=>ab({customType:n,data:s,details:o,text:r}),[n,s,o,r]),l=a.kind==="ui"?a.descriptor.title:a.title,d=a.kind==="ui"?a.descriptor.actions:void 0,f=a.kind==="ui"?a.descriptor.component:void 0,u=()=>{if(!f)return c.jsx(AG,{body:a.kind==="fallback"?a.body:"",messageId:t,text:r});switch(f.component){case"markdown":return c.jsx(qo,{messageId:t,content:f.body,className:"text-sm"});case"kv":return c.jsx("dl",{className:"grid grid-cols-[minmax(6rem,auto)_1fr] gap-x-3 gap-y-1.5 text-sm",children:f.rows.map(h=>c.jsxs(H.Fragment,{children:[c.jsx("dt",{className:"truncate text-muted-foreground",children:h.label}),c.jsx("dd",{className:R("break-words",qx[h.tone??"neutral"]?.split(" ")[1]),children:h.value})]},`${h.label}:${h.value}`))});case"list":return c.jsx("ul",{className:"flex flex-col gap-1.5 text-sm",children:f.items.map(h=>c.jsxs("li",{className:"flex items-baseline gap-2",children:[c.jsx("span",{className:"size-1.5 shrink-0 translate-y-[-1px] rounded-full bg-interactive-hover"}),c.jsx("span",{className:"font-medium",children:h.label}),h.value&&c.jsx("span",{className:"text-muted-foreground",children:h.value})]},`${h.label}:${h.value}`))});case"table":return c.jsx("div",{className:"overflow-x-auto",children:c.jsxs("table",{className:"w-full border-collapse text-sm",children:[c.jsx("thead",{children:c.jsx("tr",{children:f.columns.map(h=>c.jsx("th",{className:"border-b px-2 py-1.5 text-left font-medium text-muted-foreground",children:h},h))})}),c.jsx("tbody",{children:f.rows.map((h,m)=>c.jsx("tr",{children:h.map((g,x)=>c.jsx("td",{className:"border-b px-2 py-1.5 break-words",children:g},x))},m))})]})});case"progress":{const h=f.max??100;return c.jsx(TG,{label:f.label,value:f.value,max:h>0?h:100})}case"badges":return c.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.items.map(h=>c.jsx("span",{className:R("rounded-full px-2 py-0.5 text-xs font-medium",qx[h.tone??"neutral"]),children:h.label},h.label))});case"code":return c.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed",children:c.jsx("code",{children:f.code})});default:return null}};return c.jsxs("div",{className:R("my-1 flex flex-col gap-2 rounded-xl border border-border/60 bg-card p-3 text-card-foreground shadow-sm",i),"data-extension-ui":t,children:[(l!==void 0||d!==void 0)&&c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l!==void 0&&c.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:c.jsx("span",{className:"text-xs font-medium tracking-wide text-muted-foreground uppercase",children:l})}),d!==void 0&&c.jsx("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:d.map(h=>c.jsx(jG,{action:h,variant:h.variant??"outline",sessionId:e},`${h.command}:${h.label}`))})]}),u()]})},LG=({messageId:e,customType:t,text:n,data:r,details:s,render:o,className:i})=>{const[a,l]=H.useState(!1),[d,f]=H.useState(!1),[u,h]=H.useState(!1),m=s!==void 0?s:r,g=m!=null,x=typeof n=="string"&&n.trim().length>0,b=t||"extension",S=Array.isArray(o?.message)&&o.message.length>0?o.message:void 0,y=Array.isArray(o?.messageExpanded)&&o.messageExpanded.length>0?o.messageExpanded:void 0,v=d&&y?y:S,C=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:{color:"var(--tools-icon)"},children:c.jsx($,{name:"plug-2",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0"),style:ei,children:"Extension"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:b,children:b})]});return c.jsxs("div",{className:R("py-1",i),"data-extension-ui":e,children:[g&&!S?c.jsxs("button",{type:"button",onClick:()=>l(w=>!w),"aria-expanded":a,"aria-label":a?`Hide ${b} details`:`Show ${b} details`,className:"group/extension-note flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2 text-left",children:[C,c.jsx($,{name:"arrow-right-s","aria-hidden":"true",className:R("size-3.5 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] duration-150 group-hover/extension-note:opacity-100 group-focus-visible/extension-note:opacity-100",a&&"rotate-90 opacity-100")})]}):c.jsx("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:C}),g&&a&&!S&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx($d,{data:m})})]}),v&&c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code","data-extension-message-render":"true",children:v.map((w,I)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed",children:c.jsx(qt,{text:w})},I))}),S&&y&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>f(w=>!w),"aria-expanded":d,className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:d?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:d?"Show less":"Show more"})]}),S&&(x||g)&&c.jsxs("div",{children:[c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>h(w=>!w),"aria-expanded":u,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:u?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Raw message"})]}),u&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(qo,{messageId:e,content:n,variant:"assistant"})}),g&&c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx($d,{data:m})})]})]}),!S&&x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(qo,{messageId:e,content:n,variant:"assistant"})})]})},Wx=12,Kx={info:{label:"Notice",icon:"information"},warning:{label:"Warning",icon:"alert"},error:{label:"Error",icon:"error-warning"}},RG=({messageId:e,level:t,message:n,className:r})=>{const[s,o]=H.useState(!1),i=Kx[t]??Kx.info,a=typeof n=="string"&&n.trim().length>0?n:"Extension notification",l=a.split(`
212
- `),d=H.useMemo(()=>DN(a),[a]),f=he(S=>S.currentSessionDirectory),u=re(S=>S.isMobile),h=d.filter(S=>Ap(S)==="external"||!u&&!!f),m=l.length>Wx,g=!m||s?l:l.slice(0,Wx),x=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:{color:"var(--tools-icon)"},b=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:ei;return c.jsxs("div",{className:R("py-1",r),"data-extension-notice":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:x,children:c.jsx($,{name:i.icon,className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0"),style:b,children:i.label}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:"Extension notice",children:"Extension"})]}),c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code","data-extension-notice-body":"true",children:g.map((S,y)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed w-max min-w-full",children:c.jsx(qt,{text:S})},y))}),h.length>0&&c.jsx("div",{className:"flex min-w-0 flex-wrap gap-1",children:h.map(S=>c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>HN(Ap(S),S,f??""),title:S,className:"h-5 min-w-0 max-w-full px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:c.jsxs("span",{className:"truncate",children:["Open ",LN(S)]})},S))}),m&&c.jsxs(be,{type:"button",variant:"ghost",size:"xs",onClick:()=>o(S=>!S),"aria-expanded":s,"aria-label":s?"Show less of the extension notice":"Show more of the extension notice",className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:s?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:s?"Show less":"Show more"})]})]})},PG=e=>{if(e.kind==="recorded"){const{details:s}=e,o=typeof s.exitCode=="number"?s.exitCode:void 0;return{command:s.command,output:s.output,running:!1,status:s.cancelled?{text:"Cancelled",tone:"muted"}:o!==void 0&&o!==0?{text:`Exit code ${o}`,tone:"error"}:null,excludeFromContext:s.excludeFromContext===!0,truncated:s.truncated===!0,fullOutputPath:s.fullOutputPath}}const{execution:t}=e,n=typeof t.exitCode=="number"?t.exitCode:void 0,r=t.phase==="completed"||t.phase==="cancelled";return{command:t.command,output:t.output??"",running:t.phase==="running",status:t.phase==="running"?{text:"Running",tone:"muted"}:t.phase==="failed"?{text:"Failed",tone:"error"}:t.phase==="cancelled"?{text:"Cancelled",tone:"muted"}:n!==void 0&&n!==0?{text:`Exit code ${n}`,tone:"error"}:null,excludeFromContext:t.excludeFromContext===!0,truncated:t.truncated===!0,fullOutputPath:t.fullOutputPath,note:t.phase==="failed"?t.error:r?"Added to the conversation when the current response ends.":void 0}},DG=8,OG=({messageId:e,sessionId:t,state:n,className:r})=>{const s=PG(n),[o,i]=H.useState(!1),a=!!s.fullOutputPath&&xt()&&Yr(),l=H.useRef(null),d=H.useRef(!0),f=H.useCallback(()=>{const h=l.current;h&&(d.current=h.scrollHeight-h.scrollTop-h.clientHeight<=DG)},[]);H.useLayoutEffect(()=>{const h=l.current;!h||!d.current||(h.scrollTop=h.scrollHeight)},[s.output]);const u=H.useCallback(()=>{!t||o||(i(!0),Aw(t).catch(h=>{Ce.error(h instanceof Error&&h.message?h.message:"Failed to stop the command")}).finally(()=>i(!1)))},[t,o]);return c.jsxs("div",{className:R("py-1",r),"data-bash-execution":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:b7,children:c.jsx($,{name:"terminal-box",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Gr,"shrink-0 font-normal"),style:{color:"var(--tools-description)"},children:"Shell"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate text-foreground"),title:s.command,children:s.command}),s.status?s.status.tone==="error"?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-1.5 typography-micro font-medium text-[var(--status-error)]",children:s.status.text}):c.jsx("span",{className:"shrink-0 typography-micro",style:{color:"var(--tools-description)"},children:s.status.text}):null,s.truncated?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] px-1.5 typography-micro font-medium text-[var(--status-warning)]",children:"Output truncated"}):null,s.excludeFromContext?c.jsx("span",{className:"shrink-0 rounded border border-[var(--status-info-border)] bg-[var(--status-info-background)] px-1.5 typography-micro font-medium text-[var(--status-info)]",children:"Not sent to the model"}):null,s.running&&t?c.jsx(be,{type:"button",variant:"ghost",size:"xs",onClick:u,disabled:o,"aria-label":"Stop the shell command",className:"ml-auto h-5 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:"Stop"}):null]}),s.truncated?c.jsx("p",{className:"mt-1 typography-micro text-muted-foreground text-pretty",children:a?c.jsxs(c.Fragment,{children:["Earlier output was cut; the full output is in ",c.jsx("span",{className:"font-mono break-all select-text text-foreground",children:s.fullOutputPath})]}):"Earlier output was discarded. Only the last 50 KB is kept."}):null,s.output.length>0?c.jsx("pre",{ref:l,onScroll:f,className:"my-1 max-h-80 overflow-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-code leading-relaxed","data-no-drawer-swipe":"true",children:s.output}):null,s.note?c.jsx("p",{className:"typography-micro text-pretty",style:{color:n.kind==="live"&&n.execution.phase==="failed"?"var(--status-error)":"var(--tools-description)"},children:s.note}):null]})},fg="pichamber.notice",HG=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},Gx=new WeakMap,Zx=(e,t)=>{const n=Gx.get(e);if(n&&n.sessionId===t)return n.entry;const r=FG(e,t);return Gx.set(e,{sessionId:t,entry:r}),r},FG=(e,t)=>({info:{id:`notice:${e.id}`,sessionID:t,role:"extension",customType:fg,text:e.message,noticeLevel:e.level,time:{created:e.createdAt,completed:e.createdAt}},parts:[]}),BG=(e,t,n)=>{if(!n||t.length===0)return e;const r=[...t].sort((i,a)=>i.createdAt-a.createdAt),s=[];let o=0;for(const i of e){const a=HG(i);for(;o<r.length&&(a===void 0||r[o].createdAt<=a);)s.push(Zx(r[o],n)),o+=1;s.push(i)}for(;o<r.length;)s.push(Zx(r[o],n)),o+=1;return s},hg=p.memo(({message:e,previousMessage:t,nextMessage:n,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f})=>{const u=e.info;if(u.role==="extension"&&u.customType===fg){const h=u.noticeLevel,m=h==="warning"||h==="error"?h:"info";return c.jsx("div",{className:"chat-message-column",children:c.jsx(RG,{messageId:e.info.id,level:m,message:typeof u.text=="string"?u.text:""})})}if(u.role==="extension"&&u.customType===Kl){const h=u.bashExecution,m=u.details;if(h||m&&typeof m.command=="string"&&typeof m.output=="string")return c.jsx("div",{className:"chat-message-column",children:c.jsx(OG,{messageId:e.info.id,sessionId:u.sessionID,state:h?{kind:"live",execution:h}:{kind:"recorded",details:m}})})}if(u.role==="extension"){const h=ab({customType:u.customType,data:u.data,details:u.details,text:typeof u.text=="string"?u.text:void 0});return c.jsx("div",{className:"chat-message-column",children:h.kind==="ui"?c.jsx(NG,{sessionId:u.sessionID,messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details}):c.jsx(LG,{messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details,render:u.render})})}return c.jsx(EG,{message:e,previousMessage:t,nextMessage:n,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o})},(e,t)=>{const n=e.turnGroupingContext,r=t.turnGroupingContext;return I7(e.message,t.message)&&Dd(e.previousMessage,t.previousMessage)&&Dd(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&E7(n,r,e.message.info.id,Ds(e.message)==="user")&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animationHandlers?.onChunk===t.animationHandlers?.onChunk&&e.animationHandlers?.onComplete===t.animationHandlers?.onComplete&&e.animationHandlers?.onStreamingCandidate===t.animationHandlers?.onStreamingCandidate&&e.animationHandlers?.onAnimationStart===t.animationHandlers?.onAnimationStart&&e.animationHandlers?.onReservationCancelled===t.animationHandlers?.onReservationCancelled&&e.animationHandlers?.onAnimatedHeightChange===t.animationHandlers?.onAnimatedHeightChange});hg.displayName="MessageRow";const C9=p.memo(({turn:e,isLastTurn:t,nextEntryFirstMessage:n,sessionIsWorking:r,sessionAwaitingRecovery:s=!1,awaitingPromptEcho:o=!1,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=p.useMemo(()=>{const _=[e.userMessage,...e.assistantMessages],M=new Map;return _.forEach((L,O)=>{M.set(L.info.id,O)}),{ordered:_,lookup:M}},[e.assistantMessages,e.userMessage]),g=p.useMemo(()=>qN({activeStreamingMessageId:u,assistantMessages:e.assistantMessages}),[u,e.assistantMessages]),x=e.assistantMessages,b=p.useMemo(()=>{const _=new Map;return x.forEach((M,L)=>{_.set(M.info.id,L)}),_},[x]),S=p.useMemo(()=>Ch(e,g),[e,g]),y=Ch(e,u),v=t&&s,C=p.useMemo(()=>S&&g?g:x[0]?.info.id,[g,S,x]),w=e.activityParts,I=e.activitySegments,E=p.useMemo(()=>{const _=new Map;for(const M of w){const L=_.get(M.messageId)??[];L.push(M),_.set(M.messageId,L)}return _},[w]),T=p.useMemo(()=>{const _=e.userMessage.info.time?.created,M=e.userMessage.info,L=M?.model?.variant??M?.variant,O=typeof L=="string"&&L.trim().length>0?L:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:w,activityGroupSegments:I,headerMessageId:e.headerMessageId,hasTools:e.hasTools,hasReasoning:e.hasReasoning,diffStats:e.diffStats,changedFiles:e.changedFiles,userMessageCreatedAt:typeof _=="number"?_:void 0,userMessageVariant:O}},[e.changedFiles,e.diffStats,e.hasReasoning,e.hasTools,e.headerMessageId,e.summaryText,e.turnId,e.userMessage.info,w,I]),A=p.useCallback(_=>{const L=Ds(_)==="user",O=m.lookup.get(_.info.id),N=b.get(_.info.id)??-1,D=N>=0,W=N===0,z=N===x.length-1,F=!!C&&_.info.id===C||W||z,U=E.get(_.info.id)??[],P=L?void 0:D?W?e.userMessage:void 0:typeof O=="number"&&O>0?m.ordered[O-1]:void 0,q=D&&z?n:void 0,B=D?{turnId:e.turnId,activityOwnerMessageId:C,isFirstAssistantInTurn:W,isLastAssistantInTurn:z,isLatestTurn:t,isWorking:ZN({messageId:_.info.id,activeStreamingMessageId:u,isRetrying:qz(_),isAwaitingRecovery:v&&z}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,...F?{summaryBody:T.summaryBody,activityParts:T.activityParts,activityGroupSegments:T.activityGroupSegments,headerMessageId:T.headerMessageId,diffStats:T.diffStats,changedFiles:T.changedFiles,userMessageCreatedAt:T.userMessageCreatedAt,userMessageVariant:T.userMessageVariant}:{activityParts:U}}:void 0;return c.jsx(hg,{message:_,previousMessage:P,nextMessage:q,turnGroupingContext:B,isInActiveTurn:!!g&&_.info.id===g,activeStreamingPhase:_.info.id===g?h:null,animateUserOnMount:d(_),onUserAnimationConsumed:f,onContentChange:i,animationHandlers:a(_.info.id),scrollToBottom:l},_.info.id)},[a,t,n,m.lookup,m.ordered,i,l,e.hasReasoning,e.hasTools,e.turnId,e.userMessage,T,g,u,h,x,b,C,E,v,d,f]),j=!Ch(e,u),k=GN({isLastTurn:t,sessionIsWorking:r,turnIsInActiveStream:e.stream.isStreaming&&y,activeStreamingMessageId:u,isSteering:e.isSteering,awaitingPromptEcho:o});return c.jsx(FK,{turn:e,renderMessage:A,deferEarlierAssistantMessages:j,showWorkingStatus:k,isAwaitingRecovery:v&&!k,activeStreamingMessageId:u,activeStreamingPhase:h,onActivityContentChange:i})});C9.displayName="TurnBlock";const k9=p.memo(({message:e,previousMessage:t,nextMessage:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,shouldAnimateUserMessage:i,onUserAnimationConsumed:a,activeStreamingMessageId:l,activeStreamingPhase:d})=>c.jsx(hg,{message:e,previousMessage:t,nextMessage:n,isInActiveTurn:!!l&&e.info.id===l,activeStreamingPhase:e.info.id===l?d:null,animateUserOnMount:i(e),onUserAnimationConsumed:a,onContentChange:r,animationHandlers:s(e.info.id),scrollToBottom:o}));k9.displayName="UngroupedMessageRow";const VG=new Set(["task"]),$G=e=>typeof e=="string"&&VG.has(e.toLowerCase()),zG=e=>{const t=e.state?.time?.end;if(typeof t=="number")return t;const n=e.time?.end;return typeof n=="number"?n:void 0},Yx=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},UG=e=>{const t=e.info.finish;return typeof t=="string"?t:void 0},qG=e=>e.info.summary===!0,WG=(e,t,n,r)=>({id:n.id??`${t}-part-${r}-${n.type}`,turnId:e,messageId:t,part:n,partIndex:r,endedAt:zG(n)}),KG=e=>{const t=[];let n=!1,r=!1;e.assistantMessages.forEach(g=>{g.parts.forEach(x=>{if(x.type==="tool"){n=!0;return}x.type==="reasoning"&&Yx(x)&&(r=!0)})});const s=new Map,o=[],i=e.summarySourceMessageId?e.assistantMessages.findIndex(g=>g.info.id===e.summarySourceMessageId):-1,a=i>=0&&e.summarySourcePartId?e.assistantMessages[i]?.parts.findIndex((g,x)=>(g.id??`${e.assistantMessages[i]?.info.id}-part-${x}-${g.type}`)===e.summarySourcePartId)??-1:-1,l=e.assistantMessages.some(g=>g.parts.some(x=>x.type==="tool"||x.type==="reasoning")),d=new Map;let f=null;e.assistantMessages.forEach((g,x)=>{const b=UG(g),S=g.parts.some(v=>v.type==="tool"),y=qG(g);g.parts.forEach((v,C)=>{const w=v.type==="tool",I=v.type==="reasoning"||v.type==="text"?Yx(v):void 0,E=v.id??`${g.info.id}-part-${C}-${v.type}`,T=w?v.tool:void 0,A=w&&$G(T);if(A){const O=E;s.has(O)||(s.set(O,g.info.id),o.push(O)),f=O}const j=v.type==="text"&&typeof I=="string"&&(b==="stop"||typeof b!="string")&&e.summarySourceMessageId===g.info.id&&e.summarySourcePartId===E,k=i>=0&&(x<i||x===i&&a>=0&&C<a);let _=null;if(w?_="tool":v.type==="reasoning"?I&&(_="reasoning"):e.showTextJustificationActivity&&v.type==="text"&&I&&(y||!j&&(S||typeof b=="string"&&b!=="stop"||l||k))&&(_="justification"),!_)return;const M={...WG(e.turnId,g.info.id,v,C),kind:_};if(t.push(M),_==="tool"&&A)return;const L=d.get(f)??[];L.push(M),d.set(f,L)})});const u=[],h=g=>{if(g.length===0)return;const x=new Map;g.forEach(S=>{x.set(S.messageId,(x.get(S.messageId)??0)+1)});let b;for(const S of e.assistantMessages)(x.get(S.info.id)??0)>0&&!b&&(b=S.info.id);return b};return[null,...o].forEach(g=>{const x=d.get(g)??[];if(x.length===0)return;const b=g===null?h(x):s.get(g);b&&u.push({id:`${e.turnId}:${b}:${g??"start"}`,anchorMessageId:b,afterToolPartId:g,parts:x})}),{activityParts:t,activitySegments:u,hasTools:n,hasReasoning:r}},GG=e=>{const t=new Map,n=new Map,r=new Map,s=new Set;e.forEach(a=>{t.set(a.turnId,a);const l=a.assistantMessages[0]?.info.id,d=a.assistantMessages[a.assistantMessages.length-1]?.info.id;n.set(a.userMessageId,a.turnId),s.add(a.userMessageId),r.set(a.userMessageId,{turnId:a.turnId,messageId:a.userMessageId,userMessageId:a.userMessageId,isUserMessage:!0,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId}),a.assistantMessageIds.forEach(f=>{n.set(f,a.turnId),s.add(f),r.set(f,{turnId:a.turnId,messageId:f,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!0,isFirstAssistantInTurn:f===l,isLastAssistantInTurn:f===d,headerMessageId:a.headerMessageId})}),(a.notices??[]).forEach(f=>{n.set(f.info.id,a.turnId),s.add(f.info.id),r.set(f.info.id,{turnId:a.turnId,messageId:f.info.id,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId})})});const o=e.length>0?e[e.length-1]:null,i=new Set;return o&&(i.add(o.userMessageId),o.assistantMessageIds.forEach(a=>{i.add(a)}),(o.notices??[]).forEach(a=>{i.add(a.info.id)})),{turns:e,indexes:{turnById:t,messageToTurnId:n,messageMetaById:r},lastTurnId:o?.turnId??null,lastTurnMessageIds:i,ungroupedMessageIds:new Set}},ZG=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},YG=e=>e.info.summary===!0,Xx=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!YG(r)&&!(t&&r.info.finish!=="stop"))for(let s=r.parts.length-1;s>=0;s-=1){const o=r.parts[s];if(!o||o.type!=="text")continue;const i=ZG(o);if(i)return{text:i,sourceMessageId:r.info.id,sourcePartId:o.id??`${r.info.id}-part-${s}-text`}}}},XG=e=>Xx(e,!0)??Xx(e,!1)??{},JG=e=>{const n=e.info.summary?.diffs;if(!Array.isArray(n)||n.length===0)return;let r=0,s=0,o=0;if(n.forEach(i=>{if(!i)return;const a=typeof i.additions=="number"?i.additions:0,l=typeof i.deletions=="number"?i.deletions:0;(a!==0||l!==0)&&(o+=1),r+=a,s+=l}),o!==0)return{additions:r,deletions:s,files:o}},hm=[],Yi=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},M9=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},I9=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},QG=e=>{const t=e.info.time?.completed;return typeof t=="number"?t:void 0},eZ=e=>{const t=e.info?.summary?.body;return typeof t!="string"?void 0:t.trim().length>0?t:void 0},E9=e=>{const t=e.info;return t.role==="extension"&&t.customType===fg},tZ=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},Ah=(e,t)=>{const n=Yi(e);return{messageId:e.info.id,role:n,parentMessageId:M9(e),message:e,order:t}},nZ=(e,t)=>{const n=I9(e);let r,s=!1;t.forEach(i=>{const a=QG(i);typeof a=="number"?r=Math.max(r??0,a):s=!0});const o=typeof n=="number"&&typeof r=="number"&&r>=n?r-n:void 0;return{isStreaming:s,isRetrying:t.length>1,startedAt:n,completedAt:r,durationMs:o}},rZ={previousProjection:null,showTextJustificationActivity:!1,mergeHiddenUserTurns:void 0},sZ=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},oZ=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&sZ(e.assistantMessages,t.assistantMessages),Jx=(e,t)=>{e.summary=XG(e.assistantMessages),e.summaryText=e.summary.text??eZ(e.userMessage),e.diffStats=JG(e.userMessage),e.changedFiles=void 0;const n=KG({turnId:e.turnId,assistantMessages:e.assistantMessages,summarySourceMessageId:e.summary.sourceMessageId,summarySourcePartId:e.summary.sourcePartId,showTextJustificationActivity:t.showTextJustificationActivity});return e.activityParts=n.activityParts,e.activitySegments=n.activitySegments,e.hasTools=n.hasTools,e.hasReasoning=n.hasReasoning,e.stream=nZ(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},iZ=e=>{let t=!1;const n=[...e];for(let r=1;r<e.length;r+=1){const s=n[r-1],o=n[r],i=o.startedAt;if(!s.stream.isStreaming||typeof i!="number")continue;const a=s.startedAt,l=typeof a=="number"&&i>=a?i-a:void 0;n[r-1]={...s,stream:{...s.stream,isStreaming:!1,completedAt:i,durationMs:l,settledReason:"steered"},completedAt:i,durationMs:l},n[r]=o.isSteering?o:{...o,isSteering:!0},t=!0}return t?n:e},aZ=(e,t)=>{const n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(i=>Jx(i,t));let r=n.turns.length===e.length,s=!1;const o=e.map((i,a)=>{const l=n.indexes.turnById.get(i.turnId);return l&&oZ(l,i)?(s=!0,n.turns[a]!==l&&(r=!1),l):(r=!1,Jx(i,t))});return r&&s?n.turns:o},cZ=(e,t,n)=>{if(n.size===0&&e.every(a=>a.notices.length===0))return e;const r=new Map;e.forEach(a=>r.set(a.turnId,a));const s=new Map;t.forEach(a=>{if(!E9(a))return;const l=n.get(a.info.id);if(!l)return;const d=r.get(l);if(!d)return;if(d.completedAt!==void 0){const u=I9(a);if(u===void 0||u>d.completedAt)return}const f=s.get(l);f?f.push(a):s.set(l,[a])});let o=!1;const i=e.map(a=>{const l=s.get(a.turnId),d=a.notices??hm;return l?tZ(d,l)?a:(o=!0,{...a,notices:l}):d.length===0?a:(o=!0,{...a,notices:hm})});return o?i:e},_9=(e,t)=>{const n={...rZ,...t},r=[],s=new Map,o=new Set,i=n.mergeHiddenUserTurns;e.forEach((h,m)=>{if(Yi(h)!=="user")return;const x=r[r.length-1];if(i&&x&&S9(h)){s.set(h.info.id,x),x.messages.push(Ah(h,m)),o.add(h.info.id);return}const S={turnId:h.info.id,isSteering:!1,userMessageId:h.info.id,userMessage:h,notices:hm,headerMessageId:void 0,messages:[Ah(h,m)],assistantMessageIds:[],assistantMessages:[],activityParts:[],activitySegments:[],summary:{},summaryText:void 0,hasTools:!1,hasReasoning:!1,diffStats:void 0,changedFiles:void 0,stream:{isStreaming:!1,isRetrying:!1}};r.push(S),s.set(S.userMessageId,S),o.add(h.info.id)}),e.forEach((h,m)=>{if(Yi(h)!=="assistant")return;const x=M9(h),b=x?s.get(x):void 0;b&&(b.assistantMessages.push(h),b.assistantMessageIds.push(h.info.id),b.messages.push(Ah(h,m)),b.headerMessageId||(b.headerMessageId=h.info.id),o.add(h.info.id))});const a=new Map;{let h=null;e.forEach(m=>{if(Yi(m)==="user"){h=s.get(m.info.id)??null;return}E9(m)&&h&&a.set(m.info.id,h.turnId)})}const l=iZ(aZ(r,n)),d=cZ(l,e,a);d.forEach(h=>{h.notices.length!==0&&h.notices.forEach(m=>o.add(m.info.id))});const f=GG(d),u=new Set;return e.forEach(h=>{Yi(h)!=="assistant"&&(o.has(h.info.id)||u.add(h.info.id))}),{...f,ungroupedMessageIds:u}},lZ=30,dZ=4,Lr=new Map,Qx=new WeakMap;let e5=1;const uZ=()=>dn()?dZ:lZ,Nh=e=>{const t=Qx.get(e);if(t!==void 0)return t;const n=e5;return e5+=1,Qx.set(e,n),n},fZ=e=>e.map(t=>{const n=Nh(t.info),r=Nh(t.parts),s=t.parts.map(o=>Nh(o)).join(",");return`${n}:${r}:${s}`}).join(";"),hZ=(e,t,n,r)=>{const s=t.length>0?t[t.length-1]:void 0,o=s?.info?.id??"",i=s?.parts?.length??0;return[e,t.length,o,i,fZ(t),n?"1":"0",r].join("|")},pZ=e=>{const t=Lr.get(e);return t&&(Lr.delete(e),Lr.set(e,t)),t},mZ=(e,t)=>{Lr.delete(e);const n=uZ();for(;Lr.size>=n;){const r=Lr.keys().next().value;if(typeof r!="string")break;Lr.delete(r)}Lr.set(e,t)},gZ=(e,t)=>{const n=p.useRef(null),r=p.useRef([]),s=p.useRef(void 0),o=p.useRef(t.sessionKey),i=p.useRef(t.showTextJustificationActivity);(o.current!==t.sessionKey||i.current!==t.showTextJustificationActivity)&&(o.current=t.sessionKey,i.current=t.showTextJustificationActivity,n.current=null,r.current=[],s.current=void 0),p.useEffect(()=>{n.current=null,r.current=[],s.current=void 0},[t.sessionKey,t.showTextJustificationActivity]);const a=p.useMemo(()=>{const f=t.sessionKey??"",u=hZ(f,e,t.showTextJustificationActivity,"merge"),h=pZ(u);return h?(n.current=h,h):yl("ui.turns.projection_ms",()=>{const m=_9(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:!0});return n.current=m,mZ(u,m),m})},[e,t.showTextJustificationActivity,t.sessionKey]),l=p.useMemo(()=>{const f=a.turns.length<=1?[]:a.turns.slice(0,-1),u=r.current;if(u.length===f.length){let h=!0;for(let m=0;m<f.length;m+=1)if(u[m]!==f[m]){h=!1;break}if(h)return u}return r.current=f,f},[a.turns]),d=p.useMemo(()=>{const f=a.turns.length===0?void 0:a.turns[a.turns.length-1];return s.current===f?s.current:(s.current=f,f)},[a.turns]);return{projection:a,staticTurns:l,streamingTurn:d}},yZ=1.5,vZ=({hasMoreBefore:e,beforeCursor:t,resolveScrollContainer:n,loadOlder:r,onBeforeLoad:s,onLoadError:o})=>{p.useEffect(()=>{if(!e||!t)return;const i=n();if(!i)return;let a=!1,l,d=!0;const f=()=>{if(a||!e)return;const u=i.scrollTop<i.clientHeight*yZ,h=i.scrollHeight<=i.clientHeight+1;!u&&!h||(a=!0,s(),r().then(m=>{d&&(a=!1,m&&(l=window.setTimeout(f,0)))}).catch(()=>{d&&(a=!1,o())}))};return i.addEventListener("scroll",f,{passive:!0}),f(),()=>{d=!1,l!==void 0&&window.clearTimeout(l),i.removeEventListener("scroll",f)}},[t,e,r,s,o,n])},t5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},n5=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},xZ=(e,t,n)=>{if(!t||!n)return e;const r={name:"SessionCompaction",message:n.message,data:{...n}},s=n.completedAt??n.startedAt;let o=-1;for(let f=e.length-1;f>=0;f-=1){const u=n5(e[f]);if(!(s!==void 0&&u!==void 0&&u>s)&&t5(e[f])==="user"){o=f;break}}if(o<0)return e;let i=-1;for(let f=o+1;f<e.length;f+=1){const u=n5(e[f]);if(s!==void 0&&u!==void 0&&u>s)break;t5(e[f])==="assistant"&&(i=f)}if(i>=0)return e.map((f,u)=>u===i?{...f,info:{...f.info,error:r}}:f);const a=s??0,l={info:{id:`synthetic_compaction_notice_${t}`,sessionID:t,role:"assistant",parentID:e[o].info.id,time:{created:a,completed:a},finish:"stop",error:r},parts:[]},d=e.slice();return d.splice(o+1,0,l),d},r5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},bZ=(e,t)=>{if(!t.sessionId)return e;const n={name:"SessionRetry",message:t.message,data:{message:t.message}};let r=-1;for(let d=e.length-1;d>=0;d-=1)if(r5(e[d])==="user"){r=d;break}if(r<0)return e;let s=-1;for(let d=e.length-1;d>r;d-=1)if(r5(e[d])==="assistant"){s=d;break}if(s>=0)return e.map((d,f)=>f!==s?d:{...d,info:{...d.info,error:n}});const o=typeof t.confirmedAt=="number"?t.confirmedAt:t.fallbackTimestamp,a={info:{id:`synthetic_retry_notice_${t.sessionId}`,sessionID:t.sessionId,role:"assistant",parentID:e[r].info.id,time:{created:o,completed:o},finish:"stop",error:n},parts:[]},l=e.slice();return l.splice(r+1,0,a),l},s5=new WeakMap,wZ=(e,t)=>{const n=s5.get(e);if(n&&n.sessionId===t)return n.entry;const r={info:{id:`bash:${e.id}`,sessionID:t,role:"extension",customType:Kl,bashExecution:e,time:{created:e.startedAt,...e.completedAt?{completed:e.completedAt}:{}}},parts:[]};return s5.set(e,{sessionId:t,entry:r}),r},SZ=(e,t,n)=>!n||t.length===0?e:[...e,...t.map(r=>wZ(r,n))],o5=[],CZ=({staticTurns:e,messages:t,ungroupedMessageIds:n,lastTurnId:r,tailUserMessageId:s})=>{const o=e.map(h=>({kind:"turn",key:`turn:${h.turnId}`,turn:h,isLastTurn:h.turnId===r}));if(n.size===0)return{entries:o,trailing:o5};const i=new Map;o.forEach(h=>{i.set(h.turn.userMessage.info.id,h)});const a=t[t.length-1],l=!s&&a&&n.has(a.info.id)?a.info.id:void 0,d=[],f=[];let u=!1;return t.forEach((h,m)=>{if(s&&h.info.id===s){u=!0;return}const g=i.get(h.info.id);if(g){d.push(g);return}!n.has(h.info.id)||h.info.id===l||(u?f:d).push({kind:"ungrouped",key:`msg:${h.info.id}`,message:h,previousMessage:m>0?t[m-1]:void 0,nextMessage:m<t.length-1?t[m+1]:void 0})}),{entries:d,trailing:f.length>0?f:o5}},j9=e=>e.parts.some(t=>t?.type==="compaction"),kZ=e=>{if(!j9(e))return e;let t=!1;const n=e.parts.map(o=>o?.type!=="compaction"?o:(t=!0,{type:"text",text:"/compact"})),s=e.info.clientRole!=="user";return!t&&!s?e:{...e,info:s?{...e.info,clientRole:"user"}:e.info,parts:t?n:e.parts}},MZ=e=>{const t=Au(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},i5=new WeakMap,T9=e=>{const t=i5.get(e);if(t)return t;const n=MZ(e),r=kZ(n),s=bK(r.parts),o=s===r.parts?r:{...r,parts:s};return i5.set(e,o),o},a5=(e,t,n)=>e.info.id!==t||e.parts===n?e:T9({...e,parts:n}),IZ=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.id!==s.id||r.type!==s.type||r.type!=="text"&&r!==s)return!1}return!0},c5=(e,t)=>{if(e.messages.length===0)return e.messages;const n=new Map(t.map(o=>[o.info.id,o]));let r=!1;const s=e.messages.map(o=>{const i=n.get(o.messageId);return!i||i===o.message?o:(r=!0,{...o,message:i})});return r?s:e.messages},EZ=(e,t)=>{const n=t.activeStreamingMessageId;if(!n)return e;if(e.kind==="ungrouped"){const g=a5(e.message,n,t.liveParts);return g===e.message?e:{...e,message:g}}let r=!1;const s=e.turn.assistantMessages.map(g=>{const x=a5(g,n,t.liveParts);return x!==g&&(r=!0),x});if(!r)return e;const o=e.turn.assistantMessages.find(g=>g.info.id===n),i=s.find(g=>g.info.id===n);if(!!(o&&i&&IZ(o.parts,i.parts)))return{...e,turn:{...e.turn,assistantMessages:s,messages:c5(e.turn,s)}};const l=new Map(s.map(g=>[g.info.id,g])),f=[...e.turn.messages.length>0?e.turn.messages.slice().sort((g,x)=>g.order-x.order).map(g=>l.get(g.messageId)??g.message):[e.turn.userMessage,...s],...e.turn.notices],h=_9(f,{showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:t.mergeHiddenUserTurns}).turns[0],m=h?h.notices.length>0||e.turn.notices.length>0?{...h,notices:e.turn.notices}:h:{...e.turn,assistantMessages:s,assistantMessageIds:s.map(g=>g.info.id),messages:c5(e.turn,s)};return{...e,turn:m}},l5=e=>!!(e&&e.clientHeight>0),_Z=5,jZ=[],TZ=new Set,AZ=16,NZ=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r]),LZ=320,RZ=8,PZ=16,DZ=()=>dn()?PZ:RZ,OZ=30,HZ=180,FZ=5,BZ=120,VZ=1200,$Z=80,zZ=160,d5=1500,UZ=1.5,qZ=90,WZ=(e,t)=>{if(e.length===0||t.length<=e.length||e[e.length-1]?.key!==t[t.length-1]?.key)return!1;const n=e[0]?.key;return t.findIndex(s=>s.key===n)>0},gs=new Map,KZ=32,mo=new Map,u5=e=>mo.get(e)??0,GZ=(e,t)=>{if(mo.size>=KZ&&!mo.has(e)){const n=mo.keys().next().value;typeof n=="string"&&mo.delete(n)}mo.set(e,t)},ZZ=(e,t)=>{const n=gs.get(e);if(n){if(NZ(n.keys,t))return n.items;gs.delete(e)}},YZ=(e,t,n)=>{if(!(!n||t.length===0))for(gs.delete(e),gs.set(e,{keys:t.slice(),items:n.takeSnapshot()});gs.size>AZ;){const r=gs.keys().next().value;if(typeof r!="string")break;gs.delete(r)}},fl=e=>{const t=p.useRef(e);return p.useEffect(()=>{t.current=e},[e]),p.useCallback((...n)=>t.current(...n),[])},Nu=p.memo(({entry:e,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,sessionIsWorking:s,sessionAwaitingRecovery:o=!1,awaitingPromptEcho:i=!1,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>(js("ui.message_list_entry.render"),e.kind==="ungrouped"?c.jsx(k9,{message:e.message,previousMessage:e.previousMessage,nextMessage:e.nextMessage,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f}):e.kind==="history-gate"?c.jsx($z,{foldedCount:e.turns.length,onLoadOlder:()=>u?.(e.turns.length),onLoadAll:()=>h?.(e.turns.length)}):c.jsx(C9,{turn:e.turn,isLastTurn:e.isLastTurn,nextEntryFirstMessage:e.nextEntryFirstMessage,sessionIsWorking:s,sessionAwaitingRecovery:o,awaitingPromptEcho:i,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r})));Nu.displayName="MessageListEntry";const A9=p.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:s,virtualizerKey:o,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>{const m=t==="tanstack",g=p.useRef(!1),x=p.useRef(0),b=p.useRef(null),S=m&&dn();p.useEffect(()=>{if(!S)return;const D=r?.current;if(!D)return;const W=()=>{g.current=!0},z=()=>{g.current=!1},X=()=>{x.current=performance.now()};return D.addEventListener("touchstart",W,{passive:!0}),D.addEventListener("touchend",z,{passive:!0}),D.addEventListener("touchcancel",z,{passive:!0}),D.addEventListener("scroll",X,{passive:!0}),()=>{D.removeEventListener("touchstart",W),D.removeEventListener("touchend",z),D.removeEventListener("touchcancel",z),D.removeEventListener("scroll",X)}},[S,r]);const y=p.useCallback(()=>g.current||performance.now()-x.current<zZ,[]),v=p.useCallback(()=>{const D=r?.current;return D?D.scrollTop<D.clientHeight*UZ:!0},[r]),[C,w]=p.useState(e);let I=C;e!==C?S&&WZ(C,e)&&y()&&!v()&&(b.current===null||performance.now()-b.current<d5)?b.current===null&&(b.current=performance.now()):(b.current=null,w(e),I=e):b.current!==null&&(b.current=null);const[,E]=p.useReducer(D=>D+1,0);p.useEffect(()=>{if(!S)return;const D=window.setInterval(()=>{if(b.current===null)return;const W=performance.now()-b.current>=d5;(!y()||v()||W)&&E()},qZ);return()=>window.clearInterval(D)},[S,y,v]);const T=p.useRef(I);T.current=I;const[A]=p.useState(()=>m?ZZ(o,e.map(D=>D.key)):void 0),j=p.useRef(null),k=p.useRef(LZ),[_,M]=p.useState(null);p.useLayoutEffect(()=>{if(!m){M(F=>F===null?F:null);return}let D,W=0;const z=()=>{const F=r?.current??null;return l5(F)?(M(U=>U===F?U:F),!0):!1};if(z())return;const X=r?.current;return X?(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(X)):typeof window<"u"&&(W=window.requestAnimationFrame(()=>{if(z())return;const F=r?.current;F&&(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(F))})),()=>{W&&window.cancelAnimationFrame(W),D?.disconnect()}},[m,r,o]);const L=m&&l5(_),O=X5({count:I.length,enabled:L,getScrollElement:()=>_,estimateSize:D=>T.current[D]?.kind==="history-gate"?Dz:k.current,overscan:DZ(),scrollToFn:(D,W,z)=>{const X=j.current;X&&(X.style.height=`${z.getTotalSize()}px`),B8(D,W,z)},getItemKey:D=>T.current[D]?.key??`index:${D}`,anchorTo:"end",initialOffset:()=>Number.MAX_SAFE_INTEGER,initialMeasurementsCache:A});O.shouldAdjustScrollPositionOnItemSizeChange=(D,W,z)=>{if(z.isAtEnd($Z))return!1;const X=z.range?.startIndex;return X!==void 0&&D.index<X},p.useEffect(()=>{if(!m)return;const D=O.itemSizeCache;if(D.size>=FZ){let W=0;for(const z of D.values())W+=z;k.current=Math.min(VZ,Math.max(BZ,Math.round(W/D.size)))}}),p.useEffect(()=>{if(L)return s?.(O),()=>{YZ(o,T.current.map(D=>D.key),O),s?.(null)}},[L,s,O,o]);const N=p.useCallback(D=>c.jsx(Nu,{entry:D,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,sessionIsWorking:!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:null,activeStreamingPhase:null,onLoadOlderHistory:u,onLoadAllHistory:h},D.key),[a,h,u,i,f,l,d]);if(t==="none"||t==="tanstack"&&!L)return c.jsx("div",{ref:n,className:"relative w-full",children:I.map(D=>c.jsx("div",{"data-turn-entry":D.key,children:N(D)},D.key))});if(t==="tanstack"){const D=O.getVirtualItems(),W=D[0]?.start??0;return c.jsx("div",{ref:j,className:"relative w-full",style:{height:O.getTotalSize()},children:c.jsx("div",{style:{paddingTop:`${W}px`},children:D.map(z=>{const X=I[z.index];return X?c.jsx("div",{"data-index":z.index,ref:O.measureElement,"data-turn-entry":X.key,children:N(X)},X.key):null})})})}return null});A9.displayName="StaticHistoryList";const N9=({entry:e,sessionId:t,directory:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a=!1,awaitingPromptEcho:l=!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=r_(t,u??"",n),g=p.useMemo(()=>EZ(e,{activeStreamingMessageId:u,liveParts:m,showTextJustificationActivity:!0,mergeHiddenUserTurns:!0}),[u,e,m]);return c.jsx(Nu,{entry:g,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a,awaitingPromptEcho:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})};N9.displayName="StreamingTailContent";const L9=p.forwardRef(({sessionKey:e,messages:t,sessionIsWorking:n=!1,sessionAwaitingRecovery:r=!1,awaitingPromptEcho:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,retryOverlay:a=null,compactionOverlay:l=null,onMessageContentChange:d,getAnimationHandlers:f,scrollToBottom:u,scrollRef:h,directory:m},g)=>{_C("react.message_list_render"),js("ui.message_list.render");const{hasMoreBefore:x,beforeCursor:b,loadOlder:S}=m_(e),y=Ew(e),v=o_(e),[C,w]=p.useState(()=>u5(e)),I=p.useRef(null),E=p.useRef(null),T=p.useCallback(()=>{const ie=h?.current;if(!ie)return null;const ke=ie.getBoundingClientRect(),ve=Array.from(ie.querySelectorAll("[data-message-id]")).find(xe=>xe.getBoundingClientRect().bottom>ke.top+1);return{top:ie.scrollTop,height:ie.scrollHeight,anchor:ve?.dataset.messageId?{messageId:ve.dataset.messageId,offsetTop:ve.getBoundingClientRect().top-ke.top}:null}},[h]),A=p.useCallback(ie=>{w(ke=>{const ve=typeof ie=="function"?ie(ke):ie;return GZ(e,ve),ve})},[e]),j=p.useCallback(ie=>{I.current=T(),A(ke=>Bz(ke,ie))},[T,A]),k=p.useCallback(ie=>{I.current=T(),A(ke=>ke+ie)},[T,A]),_=p.useCallback((ie,ke,ve)=>{const xe=ke.findIndex(je=>je.turnId===ie);xe<0||(E.current=ie,A(je=>Math.max(je,Fz(xe,ve))))},[A]);p.useLayoutEffect(()=>{w(u5(e)),E.current=null},[e]);const M=p.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),L=fl(f),O=fl(()=>{u?.()}),N=p.useMemo(()=>yl("ui.message_list.base_display_ms",()=>{const ie=new Set,ke=new Map,ve=[];for(const ce of t){const J=ce.info?.id;typeof J=="string"&&ke.set(J,ce)}for(let ce=0;ce<t.length;ce+=1){const J=t[ce],ne=J.info?.id;if(typeof ne=="string"){if(ie.has(ne))continue;ie.add(ne)}ve.push(T9(typeof ne=="string"?ke.get(ne)??J:J))}const xe=[],je=new Set;for(let ce=0;ce<ve.length;ce+=1){const J=ve[ce],ne=Zz(J,je);(j9(J)||J.parts.some(De=>De.type==="text"&&Wz(De).trim()==="/compact"))&&je.add(J.info.id);const fe=xe.length>0?xe[xe.length-1]:void 0;if(Yz(fe)){const De=Jz(ne);if(De.hide){xe[xe.length-1]=Qz(fe,De.taskSessionId);continue}}if(g7(fe)){const De=y7(ne,Kz(fe));if(De.hide){xe[xe.length-1]=eU(fe,De.details);continue}}xe.push(ne)}return xe}),[t]),D=p.useRef(null),W=p.useCallback(()=>h?.current?h.current:typeof document>"u"?null:document.querySelector('[data-scrollbar="chat"]'),[h]),z=p.useCallback(()=>{I.current=T()},[T]),X=p.useCallback(()=>{I.current=null},[]);vZ({hasMoreBefore:x,beforeCursor:b,resolveScrollContainer:W,loadOlder:S,onBeforeLoad:z,onLoadError:X});const F=p.useMemo(()=>yl("ui.message_list.retry_overlay_ms",()=>{const ie=bZ(N,{sessionId:a?.sessionId??null,message:a?.message??"Quota limit reached. Retrying automatically.",confirmedAt:a?.confirmedAt,fallbackTimestamp:a?.fallbackTimestamp??0}),ke=xZ(ie,l?.sessionId??null,l?.compaction??null),ve=BG(ke,y,e);return SZ(ve,v,e)}),[N,l,a,v,y,e]),{projection:U,staticTurns:P,streamingTurn:q}=gZ(F,{sessionKey:e,showTextJustificationActivity:!0}),B=U.ungroupedMessageIds.size>0,ee=B?F:jZ,G=B?U.ungroupedMessageIds:TZ,K=q?.userMessage.info.id,{entries:se,trailing:le}=p.useMemo(()=>yl("ui.message_list.render_entries_ms",()=>CZ({staticTurns:P,messages:ee,ungroupedMessageIds:G,lastTurnId:U.lastTurnId,tailUserMessageId:K})),[U.lastTurnId,ee,G,P,K]),oe=p.useMemo(()=>{if(q)return{kind:"turn",key:`turn:${q.turnId}`,turn:q,isLastTurn:q.turnId===U.lastTurnId};if(U.ungroupedMessageIds.size===0)return;const ie=F[F.length-1];if(!(!ie||!U.ungroupedMessageIds.has(ie.info.id)))return{kind:"ungrouped",key:`msg:${ie.info.id}`,message:ie,previousMessage:F.length>1?F[F.length-2]:void 0,nextMessage:void 0}},[F,U.lastTurnId,U.ungroupedMessageIds,q]);oe&&js("ui.message_list.render.streaming");const ue=oe?oe.kind==="turn"?oe.turn.userMessage:oe.message:void 0,ye=p.useMemo(()=>{const ie=se.map((ce,J)=>{if(ce.kind!=="turn")return ce;const ne=J<se.length-1?(()=>{const fe=se[J+1];return fe&&fe.kind==="turn"?fe.turn.userMessage:fe?.kind==="ungrouped"?fe.message:void 0})():ue;return ne?{...ce,nextEntryFirstMessage:ne}:ce});let ke=0;for(const ce of ie)ce.kind==="turn"&&(ke+=1);let ve=-1;const xe=[],je=[];for(const ce of ie){if(ce.kind!=="turn"){je.push(ce);continue}if(ve+=1,Hz(ve,ke,C)){xe.push(ce.turn);continue}je.push(ce)}return xe.length===0?je:[{kind:"history-gate",key:"history-gate",turns:xe},...je]},[C,se,ue]);p.useLayoutEffect(()=>{const ie=I.current;if(ie){I.current=null;const je=h?.current;if(je){const ce=ie.anchor?.messageId?je.querySelector(`[data-message-id="${ie.anchor.messageId}"]`):null;if(ce&&ie.anchor){const J=je.getBoundingClientRect(),ne=ce.getBoundingClientRect().top-J.top-ie.anchor.offsetTop;ne!==0&&(je.scrollTop+=ne)}else{const J=je.scrollHeight-ie.height;J>0?je.scrollTop=ie.top+J:je.scrollTop=ie.top}}}const ke=E.current;if(!ke)return;E.current=null,W()?.querySelector(`[data-turn-id="${ke}"]`)?.scrollIntoView({block:"start"})},[ye,W,h]);const we=dn()||ye.length>=_Z,Me=we?"tanstack":"none",He=p.useRef(null),Ae=p.useCallback(ie=>{He.current=ie},[]),Ge=p.useMemo(()=>{const ie=oe?[...ye,oe]:ye;return le.length>0?[...ie,...le]:ie},[ye,oe,le]),et=fl(ie=>{d(ie)}),Xe=fl(ie=>{d(ie)}),te=p.useMemo(()=>t.filter(ie=>Ds(ie)==="user").map(ie=>ie.info.id),[t]);{const ie=M.current;ie.sessionKey!==e&&(ie.sessionKey=e,ie.previousOrder=te,ie.animatedIds=new Set);const ke=ie.previousOrder;if(te.length>ke.length&&ke.every((xe,je)=>te[je]===xe)&&wE(e))for(let xe=ke.length;xe<te.length;xe+=1){const je=te[xe];if(je&&!ie.animatedIds.has(je)){if(!SE(e))break;ie.animatedIds.add(je)}}ie.previousOrder=te}const Q=p.useCallback(ie=>Ds(ie)!=="user"?!1:M.current.animatedIds.has(ie.info.id),[]),me=p.useCallback(ie=>{M.current.animatedIds.delete(ie)},[]),Se=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{if(ke.kind==="ungrouped"){ie.set(ke.message.info.id,ve);return}if(ke.kind==="history-gate"){ke.turns.forEach(xe=>{ie.set(xe.userMessage.info.id,ve),xe.assistantMessages.forEach(je=>{ie.set(je.info.id,ve)})});return}ie.set(ke.turn.userMessage.info.id,ve),ke.turn.assistantMessages.forEach(xe=>{ie.set(xe.info.id,ve)})}),ie},[Ge]),_e=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{ke.kind==="turn"&&ie.set(ke.turn.turnId,ve),ke.kind==="history-gate"&&ke.turns.forEach(xe=>{ie.set(xe.turnId,ve)})}),ie},[Ge]),Fe=p.useCallback(ie=>{const ke=W();return ke?ke.querySelector(`[data-message-id="${ie}"]`):null},[W]),ht=p.useCallback(ie=>{if(ie<0||ie>=ye.length||!we)return!1;const ke=He.current;return ke?(ke.scrollToIndex(ie,{align:"start",behavior:"auto"}),!0):!1},[ye.length,we]),ge=p.useCallback((ie,ke="auto")=>{const ve=W();if(!ve)return!1;const xe=Fe(ie);if(!xe)return!1;const je=ve.getBoundingClientRect(),ne=xe.getBoundingClientRect().top-je.top+ve.scrollTop-50;return ve.scrollTo({top:ne,behavior:ke}),!0},[Fe,W]),Ze=p.useCallback((ie,ke,ve)=>{if(typeof window>"u")return!1;let xe=0;const je=()=>{oK(ie,ke),!ge(ke,ve)&&(xe+=1,xe<60&&window.requestAnimationFrame(je))};return window.requestAnimationFrame(je),!0},[ge]);return p.useEffect(()=>{if(!g)return;const ie={scrollToTurnId:(ve,xe)=>{const je=ye.find(Ue=>Ue.kind==="history-gate");if(je?.kind==="history-gate"){const Ue=ye.reduce((st,Ee)=>Ee.kind==="turn"?st+1:st,0);_(ve,je.turns,je.turns.length+Ue)}const ce=xe?.behavior??"auto",J=_e.get(ve);if(J===void 0)return!1;const ne=W();if(!ne)return!1;const fe=ne.querySelector(`[data-turn-id="${ve}"]`);return fe?(fe.scrollIntoView({behavior:ce,block:"start"}),!0):oe!==void 0&&J>=ye.length?!1:ht(J)},scrollToMessageId:(ve,xe)=>{const je=xe?.behavior??"auto",ce=Se.get(ve);if(ce===void 0)return!1;const J=Ge[ce];if(J?.kind==="history-gate"){const De=J.turns.find(Ue=>Ue.userMessage.info.id===ve||Ue.assistantMessages.some(st=>st.info.id===ve));if(De){const Ue=ye.reduce((st,Ee)=>Ee.kind==="turn"?st+1:st,0);_(De.turnId,J.turns,J.turns.length+Ue)}}if(ge(ve,je))return!0;oe!==void 0&&ce>=ye.length||ht(ce);const fe=U.indexes.messageToTurnId.get(ve);return fe?Ze(fe,ve,je):!1},holdViewportAnchor:ve=>{const xe=W();if(!xe||typeof window>"u")return;let je=0,ce=0,J=!1;const ne=()=>{J=!0,xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne)};xe.addEventListener("touchstart",ne,{passive:!0}),xe.addEventListener("wheel",ne,{passive:!0});const fe=()=>{if(J)return;const De=Fe(ve.messageId);if(De){const Ue=De.getBoundingClientRect().top-xe.getBoundingClientRect().top-ve.offsetTop;Math.abs(Ue)>.5?(xe.scrollTop+=Ue,ce=0):ce+=1}if(je+=1,ce>=OZ||je>=HZ){xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne);return}window.requestAnimationFrame(fe)};window.requestAnimationFrame(fe)},isHistoryVirtualized:()=>we,captureViewportAnchor:()=>{const ve=W();if(!ve)return null;const xe=ve.getBoundingClientRect(),ce=Array.from(ve.querySelectorAll("[data-message-id]")).find(ne=>ne.getBoundingClientRect().bottom>xe.top+1);if(!ce)return null;const J=ce.dataset.messageId;return J?{messageId:J,offsetTop:ce.getBoundingClientRect().top-xe.top}:null},restoreViewportAnchor:ve=>{const xe=W();if(!xe||!Se.has(ve.messageId))return!1;const je=()=>{const ce=Fe(ve.messageId);if(!ce)return!1;const J=xe.getBoundingClientRect(),fe=ce.getBoundingClientRect().top-J.top-ve.offsetTop;return fe!==0&&(xe.scrollTop+=fe),!0};if(!je()){const ce=Se.get(ve.messageId);if(typeof ce=="number"&&ce<ye.length)return ht(ce)}return je()},scrollToBottom:()=>{if(we&&ye.length>0&&He.current){He.current.scrollToEnd();return}const ve=W();ve&&(ve.scrollTop=ve.scrollHeight+4096)}};if(typeof g=="function")return g(ie),()=>{g(null)};const ke=g;return ke.current=ie,()=>{ke.current=null}},[Ge,Fe,ye,Se,U.indexes.messageToTurnId,W,_,Ze,ht,ge,we,oe,_e,g]),c.jsx("div",{children:c.jsx(Px,{disabled:!1,children:c.jsxs("div",{className:"relative w-full",children:[c.jsx(Px,{disabled:we,children:c.jsx(A9,{entries:ye,engine:Me,contentRef:D,scrollRef:h,registerTanstackVirtualizer:Ae,virtualizerKey:e,onMessageContentChange:et,getAnimationHandlers:L,scrollToBottom:O,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me,onLoadOlderHistory:j,onLoadAllHistory:k},e)}),oe?c.jsx(N9,{entry:oe,sessionId:e??null,directory:m,onMessageContentChange:Xe,getAnimationHandlers:L,scrollToBottom:O,sessionIsWorking:n,sessionAwaitingRecovery:r,awaitingPromptEcho:s,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me,activeStreamingMessageId:o,activeStreamingPhase:i}):null,le.map(ie=>c.jsx(Nu,{entry:ie,onMessageContentChange:Xe,getAnimationHandlers:L,scrollToBottom:O,sessionIsWorking:n,shouldAnimateUserMessage:Q,onUserAnimationConsumed:me},ie.key))]})})})});L9.displayName="MessageList";const XZ=p.memo(L9),JZ=({visible:e,onClick:t})=>c.jsx("div",{className:R("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 transition-all duration-150",e?"opacity-100 translate-y-0 scale-100 pointer-events-auto":"opacity-0 translate-y-2 scale-95 pointer-events-none"),children:c.jsx(be,{variant:"outline",size:"sm",onClick:t,className:"size-8 rounded-full [corner-shape:round] p-0 shadow-none bg-background/95 hover:bg-interactive-hover","aria-label":"Scroll to bottom",children:c.jsx($,{name:"arrow-down",className:"h-4 w-4"})})}),QZ=p.memo(JZ),eY=.1,tY=40,nY=2,f5=1500,h5=2,R9=350,rY=300,sY=600,oY=8e3,Xi=()=>typeof performance<"u"?performance.now():Date.now(),iY=(e,t)=>{if(e)return tY;const n=t?.clientHeight??0;return n<=0?96:Math.max(48,n*eY)},P9=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Ai=e=>e.scrollHeight-e.clientHeight>1,p5=(e,t)=>P9(e)<=iY(t,e),aY=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case"ArrowUp":case"PageUp":case"Home":return!0;default:return!1}},cY=(e,t)=>{if(!(t instanceof Element))return null;const n=t.closest("[data-scrollable]");return!n||n===e||!(n instanceof HTMLElement)?null:n},m5=(e,t)=>{const n=cY(e,t);return n?n.scrollTop>0:!1},lY=100,dY=48,uY=.1,fY=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=Math.max(dY,e.clientHeight*uY),hY=(e,t)=>{if(e.length===0)return;let n=0,r=e.length-1,s=0;for(;n<=r;){const o=n+r>>1,i=e[o]?.top;if(i===void 0)break;if(i<=t){s=o,n=o+1;continue}r=o-1}return e[s]?.id},pY=e=>{const t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,s=e.MutationObserver??globalThis.MutationObserver;let o,i,a,l,d,f,u=!0;const h=new Map;let m=[];const g=()=>{l===void 0&&(l=t(()=>{l=void 0,b()}))},x=()=>{const T=o;if(!T){m=[],u=!1;return}const A=T.getBoundingClientRect().top;m=[...h].map(([j,k])=>({id:j,top:k.getBoundingClientRect().top-A+T.scrollTop})),m.sort((j,k)=>j.top-k.top),u=!1},b=()=>{const T=o;if(!T)return;u&&x();const A=fY(T)?m[m.length-1]?.id:hY(m,T.scrollTop+lY);!A||A===f||(f=A,e.onActive(A))},S=()=>{const T=o;if(T){if(clearTimeout(d),d=void 0,i?.disconnect(),i=void 0,r){i=new r(()=>{clearTimeout(d),d=setTimeout(()=>{u=!0,g()},100)}),i.observe(T);for(const A of h.values())i.observe(A)}if(a?.disconnect(),a=void 0,s){a=new s(()=>{u=!0,g()});const A={subtree:!0,childList:!0};r||(A.characterData=!0,A.characterDataOldValue=!1),a.observe(T,A)}u=!0,g()}},y=T=>{o!==T&&(o=T,f=void 0,S())},v=(T,A)=>{const j=h.get(A);j&&j!==T&&i?.unobserve(j),h.set(A,T),i&&i.observe(T),u=!0,g()},C=T=>{const A=h.get(T);A&&(i?.unobserve(A),h.delete(T),u=!0,g())},w=()=>{u=!0,g()},I=()=>{for(const T of h.values())i?.unobserve(T);h.clear(),m=[],f=void 0,u=!0};return{setContainer:y,register:v,unregister:C,onScroll:g,markDirty:w,clear:I,destroy:()=>{l!==void 0&&n(l),l=void 0,clearTimeout(d),d=void 0,I(),i?.disconnect(),a?.disconnect(),i=void 0,a=void 0,o=void 0},getActiveId:()=>f}};function mY(e,t){p.useEffect(()=>{if(!t)return;const n=e;if(!n)return;let r=null;const s=pY({onActive:u=>{u!==r&&(r=u,t(u))}});s.setContainer(n);const o=new Map,i=u=>{const h=u.dataset.turnId;return h?(o.set(h,u),s.register(u,h),!0):!1},a=u=>{const h=u.dataset.turnId;return!h||o.get(h)!==u?!1:(o.delete(h),s.unregister(h),!0)},l=u=>{if(!(u instanceof HTMLElement))return[];const h=[];return u.matches("[data-turn-id]")&&h.push(u),u.querySelectorAll("[data-turn-id]").forEach(m=>h.push(m)),h};n.querySelectorAll("[data-turn-id]").forEach(i),s.markDirty();const d=new MutationObserver(u=>{let h=!1;u.forEach(m=>{m.removedNodes.forEach(g=>{l(g).forEach(x=>{a(x)&&(h=!0)})}),m.addedNodes.forEach(g=>{l(g).forEach(x=>{i(x)&&(h=!0)})})}),h&&s.markDirty()});d.observe(n,{subtree:!0,childList:!0});const f=()=>s.onScroll();return n.addEventListener("scroll",f,{passive:!0}),()=>{n.removeEventListener("scroll",f),d.disconnect(),s.destroy()}},[e,t])}function gY({containerEl:e,handleScrollEvent:t,releaseFromUserIntent:n,scrollRef:r,stateRef:s,canScroll:o,scrollToBottomNow:i,updateOverflowAndButton:a,keyboardAnimRef:l,animationGuardUntilRef:d,lastScrollTopRef:f}){p.useEffect(()=>{const u=e;if(!u)return;f.current=u.scrollTop;const h=v=>{v.deltaY>=0||m5(u,v.target)||n()};let m=null;const g=v=>{const C=v.touches.item(0);m=C?C.clientY:null},x=v=>{const C=v.touches.item(0);if(!C){m=null;return}const w=m;m=C.clientY,!(w===null||C.clientY-w<=nY)&&(m5(u,v.target)||n())},b=()=>{m=null},S=v=>{aY(v)&&n()},y=v=>{const C=v.target;C instanceof Element&&C.closest("[data-overlay-scrollbar-thumb]")&&n()};return u.addEventListener("scroll",t,{passive:!0}),u.addEventListener("wheel",h,{passive:!0}),u.addEventListener("touchstart",g,{passive:!0}),u.addEventListener("touchmove",x,{passive:!0}),u.addEventListener("touchend",b,{passive:!0}),u.addEventListener("touchcancel",b,{passive:!0}),u.addEventListener("keydown",S),typeof window<"u"&&window.addEventListener("pointerdown",y,!0),()=>{u.removeEventListener("scroll",t),u.removeEventListener("wheel",h),u.removeEventListener("touchstart",g),u.removeEventListener("touchmove",x),u.removeEventListener("touchend",b),u.removeEventListener("touchcancel",b),u.removeEventListener("keydown",S),typeof window<"u"&&window.removeEventListener("pointerdown",y,!0)}},[e,t,f,n]),p.useEffect(()=>{if(typeof window>"u")return;const u=m=>{const g=m.detail;g&&(l.current=!0,d.current=Xi()+g.durationMs+R9)},h=()=>{l.current=!1;const m=r.current;if(!m){a();return}s.current==="following"&&o(m)&&i("auto"),a()};return window.addEventListener("oc:keyboard-anim",u),window.addEventListener("oc:keyboard-settled",h),()=>{window.removeEventListener("oc:keyboard-anim",u),window.removeEventListener("oc:keyboard-settled",h),l.current=!1}},[d,o,l,r,i,s,a])}const yY=({currentSessionId:e,currentSessionKey:t,sessionMessageCount:n,latestTailEntryId:r=null,sessionIsWorking:s,isMobile:o,onActiveTurnChange:i})=>{const a=p.useRef(null),[l,d]=p.useState(null),f=p.useRef(null),[u,h]=p.useState("following"),[m,g]=p.useState(!1),[x,b]=p.useState(!1),[S,y]=p.useState(!1),v=p.useRef("following"),C=p.useRef(o);C.current=o;const w=p.useRef(s);w.current=s;const I=p.useRef(!1),E=p.useRef(null),T=p.useRef(t);T.current=t;const A=p.useRef(null),j=p.useRef(null),k=p.useRef(null),_=p.useRef(0),M=p.useRef(!1),L=p.useRef(0),O=p.useRef(!1),N=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useRef(null);p.useLayoutEffect(()=>{a.current!==f.current&&(f.current=a.current,d(a.current))});const X=p.useCallback(()=>w.current||I.current,[]),F=p.useCallback(Q=>{v.current!==Q&&(v.current=Q,h(Q))},[]),U=p.useCallback(Q=>{j.current={top:Math.max(0,Q.scrollHeight-Q.clientHeight),time:Xi()},k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{j.current=null,k.current=null},f5)},[]),P=p.useCallback(Q=>{const me=j.current;return me?Xi()-me.time>f5?(j.current=null,!1):Math.abs(Q.scrollTop-me.top)<h5:!1},[]),q=p.useCallback(()=>Xi()<_.current,[]),B=p.useCallback(()=>{O.current=!1,N.current&&(clearTimeout(N.current),N.current=null),D.current&&(clearTimeout(D.current),D.current=null)},[]),ee=p.useCallback(()=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,B()},sY)},[B]),G=p.useCallback(()=>{const Q=a.current;Q&&(O.current=!0,W.current=Q.scrollHeight,ee(),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,B()},oY))},[ee,B]),K=p.useCallback(()=>{const Q=a.current;if(!Q){g(!1),b(!1);return}const me=Ai(Q);if(g(me),!me){b(!1);return}const Se=v.current==="released"&&!p5(Q,C.current);b(Se)},[]),se=p.useCallback(Q=>{const me=a.current;if(!me)return;U(me);const Se=me.scrollHeight+4096;if(Q==="smooth"){me.scrollTo({top:Se,behavior:Q});return}me.scrollTop=Se},[U]),le=p.useCallback((Q,me="auto")=>{const Se=a.current;!Q&&!X()||(Q&&v.current!=="following"&&F("following"),Se&&(!Q&&v.current!=="following"||se(Q?me:"auto")))},[X,se,F]),oe=p.useCallback(()=>{const Q=a.current;if(Q){if(!Ai(Q)){F("following");return}v.current!=="released"&&(F("released"),K())}},[F,K]),ue=p.useCallback((Q="instant")=>{le(!0,Q==="smooth"?"smooth":"auto")},[le]),ye=p.useCallback(()=>{le(!0)},[le]),we=p.useCallback(()=>{F("released"),K()},[F,K]),Me=p.useCallback(()=>{B(),oe()},[B,oe]),He=p.useCallback(async()=>{const Q=T.current;return Q?a.current?(z.current=null,F("following"),le(!0),G(),K(),!1):(z.current=Q,F("following"),!1):!1},[G,le,F,K]);p.useEffect(()=>{!e||!t||t===A.current||(A.current=t,ks.getInstance().recordSessionStart(e),j.current=null,z.current&&z.current!==t&&(z.current=null))},[e,t]),p.useEffect(()=>{if(I.current=!1,E.current&&(clearTimeout(E.current),E.current=null),s){v.current==="following"&&le(!0);return}I.current=!0,E.current=setTimeout(()=>{I.current=!1,E.current=null},rY)},[s,le]),p.useEffect(()=>{y(u==="following"&&s)},[u,s]),p.useLayoutEffect(()=>{l&&z.current&&z.current===t&&He()},[l,t,He]);const Ae=p.useCallback(()=>{const Q=a.current;if(!Q)return;const me=L.current;L.current=Q.scrollTop;const Se=Q.scrollTop>me+.5;if(K(),!Ai(Q)){F("following");return}if(p5(Q,C.current)){const _e=P9(Q)<=h5;(Se||v.current==="following"||_e)&&F("following");return}if(v.current==="following"&&(P(Q)||q())){le(!1);return}Me()},[q,P,Me,le,F,K]);gY({containerEl:l,handleScrollEvent:Ae,releaseFromUserIntent:Me,scrollRef:a,stateRef:v,canScroll:Ai,scrollToBottomNow:se,updateOverflowAndButton:K,keyboardAnimRef:M,animationGuardUntilRef:_,lastScrollTopRef:L}),p.useEffect(()=>{const Q=l;if(!Q||typeof ResizeObserver>"u")return;const me=new ResizeObserver(()=>{if(M.current){K();return}const _e=a.current;if(_e&&!Ai(_e)){F("following"),K();return}if(K(),O.current&&_e){const Fe=_e.scrollHeight>W.current+1;W.current=_e.scrollHeight,le(!0),Fe&&ee();return}X()&&v.current==="following"&&le(!1)});me.observe(Q);const Se=Q.firstElementChild;return Se instanceof Element&&me.observe(Se),()=>me.disconnect()},[ee,l,X,le,F,K]),p.useEffect(()=>{K()},[n,K]);const Ge=p.useRef(null);p.useEffect(()=>{const Q=Ge.current;Ge.current={key:t,count:n,tailId:r},!(!Q||!t||Q.key!==t||!(n>Q.count||r!==null&&r!==Q.tailId))&&(w.current||v.current!=="following"||(le(!0),G()))},[G,t,r,le,n]);const et=p.useCallback(Q=>{if(Q==="animation"&&(_.current=Xi()+R9),K(),O.current){le(!0),ee();return}v.current==="following"&&le(!1)},[ee,le,K]),Xe=p.useRef(new Map),te=p.useCallback(Q=>{const me=Xe.current.get(Q);if(me)return me;const Se=()=>{v.current==="following"&&le(!1)},_e={onChunk:Se,onComplete:()=>{K()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:Se,onReservationCancelled:()=>{}};return Xe.current.set(Q,_e),_e},[le,K]);return p.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),E.current&&(clearTimeout(E.current),E.current=null),B()},[B]),mY(l,i),{scrollRef:a,state:u,isPinned:u==="following",isOverflowing:m,isFollowingProgrammatically:S,showScrollButton:x,notifyContentChange:et,getAnimationHandlers:te,goToBottom:ue,scrollToBottomOnSend:ye,releaseAutoFollow:we,restoreSnapshot:He}},pg=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},mg=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},g5=e=>{if(!e)return null;const t=pg(e),n=typeof e.info?.id=="string"?e.info.id:"",r=mg(e)??"";return`${n}::${t}::${r}`},vY=e=>({turnIds:[...e.turnIds],turnMessageStartIndexes:[...e.turnMessageStartIndexes],turnIndexById:new Map(e.turnIndexById),messageToTurnId:new Map(e.messageToTurnId),messageToTurnIndex:new Map(e.messageToTurnIndex),turnCount:e.turnCount}),xY=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let f=-1;for(let u=0;u<n.length;u+=1)if(t[u]!==n[u]){if(f!==-1)return null;f=u}return f===-1?e:f!==n.length-1?null:g5(t[f])===g5(n[f])?e:null}if(n.length!==t.length+1)return null;for(let f=0;f<t.length;f+=1)if(t[f]!==n[f])return null;const r=n[n.length-1];if(!r)return null;const s=pg(r),o=r.info.id,i=vY(e);if(s==="user"){const f=i.turnIds.length;return i.turnIds.push(o),i.turnMessageStartIndexes.push(n.length-1),i.turnIndexById.set(o,f),i.messageToTurnId.set(o,o),i.messageToTurnIndex.set(o,f),i.turnCount=i.turnIds.length,i}if(s!=="assistant"){const f=i.turnIds.length-1;if(f<0)return null;const u=i.turnIds[f];return u?(i.messageToTurnId.set(o,u),i.messageToTurnIndex.set(o,f),i):null}const a=mg(r);if(!a)return i;const l=i.turnIndexById.get(a);if(typeof l!="number"||l<0)return null;const d=i.turnIds[l];return d?(i.messageToTurnId.set(o,d),i.messageToTurnIndex.set(o,l),i):null},bY=e=>{const t=[],n=[],r=new Map,s=new Map,o=new Map,i=new Map;let a=-1;return e.forEach((l,d)=>{const f=pg(l),u=l.info.id;if(f==="user"){a=t.length,t.push(u),n.push(d),r.set(u,a),i.set(u,a),s.set(u,u),o.set(u,a);return}if(f!=="assistant"){if(a>=0){const x=t[a];x&&(s.set(u,x),o.set(u,a))}return}const h=mg(l);if(!h)return;const m=i.get(h);if(typeof m!="number"||m<0)return;const g=t[m];g&&(s.set(u,g),o.set(u,m))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:s,messageToTurnIndex:o,turnCount:t.length}},wY=30,SY=1200,CY=1.5,kY=e=>Math.max(SY,e*CY),MY=4,IY=30,EY=250,_Y=2e3,jY=2500,go=new Map,TY=()=>dn()?MY:wY,AY=e=>dn()?e.length<=IY:!0,y5=(e,t)=>{if(go.delete(e),!AY(t.messages))return;const n=TY();for(;go.size>=n;){const r=go.keys().next().value;if(typeof r!="string")break;go.delete(r)}go.set(e,t)},NY=e=>!e.sessionId||!e.isPinned||!e.canLoadEarlier||e.isLoadingOlder||e.pendingRevealWork?!1:e.scrollHeight<=e.clientHeight+1,v5=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),LY=20,RY=4,x5=(e,t)=>{const n=e.style.overflow;if(e.style.overflow="hidden",e.scrollTop=t,e.scrollHeight,e.style.overflow=n,e.scrollTop=t,typeof window>"u")return;let r=!1,s=0;const o=()=>{r=!0};e.addEventListener("touchstart",o,{passive:!0,once:!0});const i=()=>{r||(e.scrollTop<t-RY&&(e.scrollTop=t),s+=1,s<LY?window.requestAnimationFrame(i):e.removeEventListener("touchstart",o))};window.requestAnimationFrame(i)},b5=(e,t,n)=>!e||!t||t===e?!1:n.some(r=>r.info.id===e);function PY({sessionKey:e,timelineIdentityRef:t,scrollRef:n,messageListRef:r,renderedMessages:s,isPinnedRef:o,goToBottom:i,captureViewportAnchor:a,restoreViewportAnchor:l}){const d=p.useRef(null),f=p.useRef(null);return p.useLayoutEffect(()=>{d.current=null,f.current=null},[e]),p.useLayoutEffect(()=>{const u=n.current;if(!u)return;let h=d.current;const m=f.current,g=s[0]?.info?.id??null,x=s[s.length-1]?.info?.id??null,b=m?v5({previousOldestId:m.oldestId,previousNewestId:m.newestId,currentOldestId:g,currentNewestId:x})||b5(m.oldestId,g,s):!1;h&&h.identity!==t.current&&(d.current=null,h=null);const S=h?v5({previousOldestId:h.oldestId,previousNewestId:h.newestId,currentOldestId:g,currentNewestId:x})||b5(h.oldestId,g,s):!1,y=b||S,v=!!(h&&(b||S)),C=()=>{f.current={oldestId:g,newestId:x,scrollHeight:u.scrollHeight}},w=()=>{const E=d.current;E&&(d.current={...E,height:u.scrollHeight,top:u.scrollTop,anchor:a(),oldestId:g,newestId:x})};if(o.current){y?(d.current=null,i("instant")):h&&w(),C();return}const I=r.current?.isHistoryVirtualized()??!1;if(h&&v){if(d.current=null,I){!h.historyVirtualized&&h.anchor&&l(h.anchor),C();return}const E=u.scrollHeight-h.height,T=()=>E<=0?!1:(u.scrollTop=h.top+E,!0);if(dn()&&E>0){x5(u,h.top+E),C();return}h.anchor&&l(h.anchor)||T()}else if(b&&m&&!I){const E=u.scrollHeight-m.scrollHeight;if(E>0){const T=u.scrollTop+E;dn()?x5(u,T):u.scrollTop=T}}else h&&w();C()},[a,r,s,n,l,i,o,t]),{prePrependScrollRef:d}}const DY=({sessionId:e,sessionKey:t,messages:n,historyMeta:r,scrollRef:s,messageListRef:o,loadMoreMessages:i,goToBottom:a,releaseAutoFollow:l,isPinned:d,showScrollButton:f})=>{const u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useMemo(()=>{const te=t??"";m.current!==t&&(m.current=t,u.current=null,h.current=null);const Q=te?go.get(te):void 0;if(Q&&Q.messages===n)return y5(te,Q),u.current=Q.model,h.current=n,Q.model;const Se=xY(u.current,h.current,n)??bY(n);return u.current=Se,h.current=n,te&&n.length>0&&y5(te,{messages:n,model:Se}),Se},[n,t]),[x,b]=p.useState(!1),[S,y]=p.useState(!1),[v,C]=p.useState(null),w=p.useRef(g),I=p.useRef(d),E=p.useRef(x),T=p.useRef(S),A=p.useRef(e),j=p.useRef({key:t});j.current.key!==t&&(j.current={key:t});const k=p.useRef(n),_=p.useRef(r),M=p.useRef(null),L=p.useRef([]),O=p.useRef(null),N=p.useRef(null),D=p.useRef(!1),W=p.useRef(null),z=p.useMemo(()=>{const te=Ey().HISTORICAL_MESSAGES,Q=!1,me=r?!r.complete:n.length>=te,Se=!!r?.loading;return{hasBufferedTurns:Q,hasMoreAboveTurns:me,historyLoading:Se,canLoadEarlier:me}},[r,n.length]),X=p.useRef(z);w.current=g,I.current=d,E.current=x,T.current=S,X.current=z,A.current=e,k.current=n,_.current=r;const F=p.useCallback(()=>{D.current=!0,W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null)},[]),U=p.useCallback(()=>{if(typeof window>"u"){D.current=!1;return}W.current!==null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{W.current=null,D.current=!1},_Y)},[]);p.useLayoutEffect(()=>{if(M.current===t)return;W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),D.current=!1,M.current=t;const te=O.current;te&&te.identity!==j.current&&(O.current=null,te.resolve(!1)),b(!1),y(!1),N.current=null,C(null)},[t]),p.useLayoutEffect(()=>{if(!d)return;const te=g.turnIds[g.turnIds.length-1];te&&C(Q=>Q===te?Q:te)},[d,g.turnIds]);const P=p.useCallback(()=>{const te=L.current;te.length!==0&&(L.current=[],te.forEach(Q=>Q()))},[]),q=p.useCallback(()=>new Promise(te=>{if(typeof window>"u"){te();return}let Q=!1;const me=()=>{Q||(Q=!0,window.clearTimeout(Se),te())};L.current.push(me);const Se=window.setTimeout(me,EY)}),[]),B=p.useCallback(te=>{const Q=O.current;Q&&(O.current=null,Q.resolve(te))},[]),ee=p.useCallback(()=>{const te=O.current;if(!te)return;if(te.identity!==j.current){B(!1);return}if(te.kind==="turn"?o.current?.scrollToTurnId(te.id,{behavior:te.behavior})??!1:o.current?.scrollToMessageId(te.id,{behavior:te.behavior})??!1){te.turnId&&(N.current={turnId:te.turnId,expiresAt:Date.now()+jY},C(te.turnId)),B(!0);return}typeof(te.kind==="turn"?w.current.turnIndexById.get(te.id):w.current.messageToTurnIndex.get(te.id))=="number"&&B(!1)},[o,B]);p.useEffect(()=>()=>{W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),P(),B(!1)},[P,B]);const G=n;p.useLayoutEffect(()=>{P(),ee()},[ee,G,P]);const K=p.useCallback(()=>o.current?.captureViewportAnchor()??null,[o]),se=p.useCallback(te=>o.current?.restoreViewportAnchor(te)??!1,[o]),{prePrependScrollRef:le}=PY({sessionKey:t,timelineIdentityRef:j,scrollRef:s,messageListRef:o,renderedMessages:G,isPinnedRef:I,goToBottom:a,captureViewportAnchor:K,restoreViewportAnchor:se}),oe=p.useCallback(async()=>!1,[]),ue=p.useCallback(async te=>{if(!A.current||!j.current.key||E.current||!X.current.hasMoreAboveTurns)return!1;const Q=A.current,me=j.current;if(!Q||!me.key)return!1;const Se=()=>{le.current?.identity===me&&(le.current=null)},_e=s.current,Fe=k.current,ht=Fe.length,ge=Fe[0]?.info?.id??null,Ze=_.current?.limit??Ey().HISTORICAL_MESSAGES;te.preserveViewport&&_e&&(le.current={identity:me,height:_e.scrollHeight,top:_e.scrollTop,anchor:K(),historyVirtualized:o.current?.isHistoryVirtualized()??!1,oldestId:ge,newestId:Fe[Fe.length-1]?.info?.id??null}),F(),b(!0);try{let Be=ht,ie=ge,ke=Ze;const ve=w.current.turnCount;for(;;){if(await i(Q,"up"),j.current!==me||(await q(),j.current!==me))return Se(),!1;const xe=k.current,je=xe.length,ce=xe[0]?.info?.id??null,J=_.current?.limit??ke,ne=je>Be||typeof ie=="string"&&typeof ce=="string"&&ie!==ce||J>ke;if(w.current.turnCount-ve>0)return!0;if(!ne)return Se(),!1;if(!X.current.hasMoreAboveTurns)return!0;Be=je,ie=ce,ke=J}}catch(Be){throw Se(),Be}finally{j.current===me&&(b(!1),U())}},[F,K,i,o,le,s,U,q]),ye=p.useCallback(async te=>{const Q=j.current;F(),te?.userInitiated&&l();try{await ue({preserveViewport:!0})}finally{j.current===Q&&U()}},[F,ue,l,U]),we=p.useCallback(()=>{if(dn())return;const te=s.current;te&&(I.current||te.scrollTop>=kY(te.clientHeight)||X.current.canLoadEarlier&&(E.current||T.current||ye({userInitiated:!0})))},[ye,s]),Me=p.useCallback(()=>{if(dn()||D.current)return;const te=s.current;te&&NY({sessionId:A.current,isPinned:I.current,canLoadEarlier:X.current.canLoadEarlier,isLoadingOlder:E.current,pendingRevealWork:T.current,scrollHeight:te.scrollHeight,clientHeight:te.clientHeight})&&ye()},[ye,s]);p.useEffect(()=>{if(typeof window>"u")return;const te=window.requestAnimationFrame(()=>{Me()});return()=>window.cancelAnimationFrame(te)},[z.canLoadEarlier,x,d,Me,S,G.length,t]),p.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const te=s.current;if(!te)return;let Q=null;const me=()=>{Q===null&&(Q=window.requestAnimationFrame(()=>{Q=null,Me()}))},Se=new ResizeObserver(me);Se.observe(te);const _e=te.firstElementChild;return _e instanceof Element&&Se.observe(_e),me(),()=>{Q!==null&&window.cancelAnimationFrame(Q),Se.disconnect()}},[Me,s,t]);const He=p.useCallback(async(te,Q)=>{if(!te||!A.current||!j.current.key)return!1;const me=j.current;l(),y(!0);try{return j.current!==me||typeof w.current.turnIndexById.get(te)!="number"?!1:!!await new Promise(Fe=>{O.current={identity:me,kind:"turn",id:te,behavior:Q?.behavior??"auto",turnId:te,resolve:Fe},ee()})}finally{j.current===me&&y(!1)}},[ee,l]),Ae=p.useCallback(async(te,Q)=>{if(!te||!A.current||!j.current.key)return!1;const me=j.current;l(),y(!0);try{if(j.current!==me)return!1;const Se=w.current.messageToTurnId.get(te);return typeof w.current.messageToTurnIndex.get(te)!="number"?!1:!!await new Promise(ht=>{O.current={identity:me,kind:"message",id:te,behavior:Q?.behavior??"auto",turnId:Se??null,resolve:ht},ee()})}finally{j.current===me&&y(!1)}},[ee,l]),Ge=p.useCallback(async()=>{y(!1),b(!1),a("smooth")},[a]),et=p.useCallback(async()=>{y(!1),b(!1),a("instant")},[a]),Xe=p.useCallback(te=>{const Q=N.current;if(Q){if(te!==Q.turnId&&Date.now()<Q.expiresAt)return;N.current=null}C(te)},[]);return{turnIds:g.turnIds,turnStart:0,renderedMessages:G,historySignals:z,isLoadingOlder:x,pendingRevealWork:S,activeTurnId:v,showScrollToBottom:f&&!S,turnWindowModel:g,loadEarlier:ye,revealBufferedTurns:oe,resumeToBottom:Ge,resumeToBottomInstant:et,scrollToTurn:He,scrollToMessage:Ae,handleHistoryScroll:we,captureViewportAnchor:K,restoreViewportAnchor:se,handleActiveTurnChange:Xe}};function pm(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
213
- `)}function D9(e,t=80){const r=pm(e).replace(/\n/g," ");return r.length>t?`${r.slice(0,t)}…`:r}const OY=({open:e,onOpenChange:t,onScrollToMessage:n,onScrollByTurnOffset:r,onResumeToLatest:s,canLoadEarlier:o=!1,isLoadingEarlier:i=!1,onLoadEarlier:a,onRevert:l,onFork:d})=>{const{isMobile:f}=Dn(),u=he(q=>q.currentSessionId),[h,m]=p.useState(0);p.useEffect(()=>{if(!u){m(0);return}const q=()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");m(B().getState().reducer.bySession.get(u)?.sessionTreeRevision??0)}catch{m(0)}};q();try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");return B().subscribe(q,`session:${u}`)}catch{return}},[u]);const[g,x]=p.useState(new Map),b=p.useRef(null);p.useEffect(()=>{if(!e||!u)return;b.current!==u&&(b.current=u,x(new Map));let q=!1;return(async()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store"),ee=await B().tree(u);if(q)return;const G=new Map,K=se=>{se.label&&G.set(se.entryId,se.label);for(const le of se.children)K(le)};for(const se of ee.nodes)K(se);x(G)}catch{}})(),()=>{q=!0}},[u,e,h]);const[S,y]=p.useState(!1);p.useEffect(()=>{if(!u){y(!1);return}const q=()=>{try{const{getPiSessionStore:B}=require("@/apps/pi-session-store"),ee=B().getState().reducer.bySession.get(u);y(ee?.lifecycle==="busy"||ee?.lifecycle==="retry")}catch{y(!1)}};q();try{const{getPiSessionStore:B}=require("@/apps/pi-session-store");return B().subscribe(q,`session:${u}`)}catch{return}},[u]);const v=fu(u??""),[C,w]=p.useState(""),[I,E]=p.useState(0),T=p.useRef([]),A=p.useRef(null),j=p.useRef(null),k=p.useRef(!1),_=p.useRef(e),M=p.useCallback(q=>new Date(q).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),[]),L=p.useCallback(q=>new Date(q).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),[]),O=p.useMemo(()=>v.filter(q=>q.info.role==="user").map(q=>({message:q})),[v]),N=p.useMemo(()=>{const q=C.trim();if(!q)return O;const B=q.toLowerCase();return O.filter(({message:ee})=>pm(ee.parts).toLowerCase().includes(B))},[O,C]);p.useEffect(()=>{k.current||E(C.trim()?0:Math.max(0,N.length-1))},[N,C]),p.useEffect(()=>{T.current=T.current.slice(0,N.length)},[N.length]),p.useEffect(()=>{k.current||T.current[I]?.scrollIntoView({block:"nearest"})},[I]),p.useEffect(()=>{!k.current||j.current||i||(k.current=!1)},[N.length,i]),p.useLayoutEffect(()=>{const q=_.current;if(_.current=e,!e||q||k.current||C.trim())return;const B=A.current;B&&(B.scrollTop=B.scrollHeight)},[e,C]),p.useLayoutEffect(()=>{const q=j.current,B=A.current;if(!q||!B||i)return;j.current=null;const ee=T.current.find(K=>K?.dataset.timelineMessageId===q.messageId);if(!ee)return;const G=ee.getBoundingClientRect().top-B.getBoundingClientRect().top;B.scrollTop+=G-q.top},[N.length,i]);const D=p.useCallback(()=>{const q=A.current;if(q){const B=q.getBoundingClientRect().top,ee=T.current.find(G=>G?G.getBoundingClientRect().bottom>=B:!1);ee?.dataset.timelineMessageId&&(j.current={messageId:ee.dataset.timelineMessageId,top:ee.getBoundingClientRect().top-B})}k.current=!0,a?.()},[a]),W=p.useCallback(async q=>{await n?.(q)!==!1&&t(!1)},[t,n]),z=p.useCallback(q=>{const B=N.length;if(B!==0){if(q.key==="ArrowDown"){q.preventDefault(),E(ee=>(ee+1)%B);return}if(q.key==="ArrowUp"){q.preventDefault(),E(ee=>(ee-1+B)%B);return}if(q.key==="Enter"){q.preventDefault();const ee=(I%B+B)%B,G=N[ee];G&&W(G.message.info.id)}}},[N,W,I]),X=p.useCallback(async()=>{const q=N.length;if(q===0||!l||S)return;const B=(I%q+q)%q,ee=N[B];if(ee)try{await l(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to revert")}},[N,S,l,t,I]),F=p.useCallback(async()=>{const q=N.length;if(q===0||!d||S)return;const B=(I%q+q)%q,ee=N[B];if(ee)try{await d(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to fork")}},[N,S,d,t,I]),U=p.useCallback(q=>{const B=N.length;if(B!==0){if(q.key==="ArrowDown"){q.preventDefault(),E(ee=>(ee+1)%B);return}if(q.key==="ArrowUp"){q.preventDefault(),E(ee=>(ee-1+B)%B);return}if(q.key==="Enter"){q.preventDefault();const ee=(I%B+B)%B,G=N[ee];G&&W(G.message.info.id)}}},[N,W,I]);if(p.useEffect(()=>{if(!e||f)return;const q=window.setTimeout(()=>A.current?.focus(),100);return()=>window.clearTimeout(q)},[e,f]),!u)return null;const P=N[(I%Math.max(1,N.length)+Math.max(1,N.length))%Math.max(1,N.length)]?.message??null;return c.jsx(gu,{open:e,onOpenChange:t,children:c.jsxs(yu,{className:R("flex flex-col",f?"max-w-full max-h-[85vh] rounded-t-2xl mt-auto":"max-w-2xl max-h-[70vh]"),children:[c.jsxs(vu,{children:[c.jsxs(xu,{className:"flex items-center gap-2",children:[c.jsx($,{name:"time",className:"h-5 w-5"}),"Conversation timeline"]}),c.jsx(o1,{children:f?"Tap a message, then Revert or Fork":"Arrow keys to move • Enter to jump"})]}),!f&&c.jsxs("div",{className:"relative mt-2",children:[c.jsx($,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(Uo,{placeholder:"Search messages...",value:C,onChange:q=>w(q.target.value),onKeyDown:z,className:"pl-9 w-full"})]}),o&&a&&c.jsx("div",{className:"flex justify-center py-1",children:c.jsxs(be,{type:"button",variant:"link",size:"sm",onClick:D,disabled:i,className:"h-auto px-1 py-0 text-muted-foreground hover:text-foreground",children:[i&&c.jsx($,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx("div",{ref:A,tabIndex:0,onKeyDown:U,className:"flex-1 overflow-y-auto outline-none focus-visible:ring-1 focus-visible:ring-ring rounded","aria-label":"Message list",children:N.length===0?c.jsx("div",{className:"text-center text-muted-foreground py-8",children:C?"No messages found":"No messages in this session yet"}):N.map(({message:q},B)=>{const ee=D9(q.parts),G=q.info.time?.created??0,K=M(G),se=N[B-1],le=se?M(se.message.info.time?.created??0):null,oe=K!==le,ue=L(G),ye=B===I,we=g.get(q.info.id),Me=C.trim()?FY(pm(q.parts),C):null;return c.jsxs(p.Fragment,{children:[oe&&c.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm",children:[c.jsx("div",{className:"h-px flex-1 bg-border/60"}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:K}),c.jsx("div",{className:"h-px flex-1 bg-border/60"})]}),c.jsxs("div",{ref:He=>{T.current[B]=He},"data-timeline-message-id":q.info.id,className:R("group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",ye&&"bg-interactive-selection text-interactive-selection-foreground"),onClick:()=>{W(q.info.id)},onMouseEnter:()=>E(B),children:[c.jsx("span",{className:R("typography-meta w-16 flex-shrink-0 text-right tabular-nums",ye?"text-interactive-selection-foreground/70":"text-muted-foreground"),children:ue}),we&&c.jsx("span",{className:"max-w-40 shrink-0 truncate rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro text-muted-foreground",children:we}),c.jsxs("p",{className:R("flex-1 min-w-0 typography-small truncate",ye?"text-interactive-selection-foreground":"text-foreground"),children:[Me??(ee||"[No text content]"),!Me&&ee&&ee.length>=80&&"…"]})]})]},q.info.id)})}),P&&c.jsxs("div",{className:R("flex gap-2 mt-3",f?"flex-col":"flex-row"),children:[c.jsxs(be,{type:"button",variant:f?"default":"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{X()},children:[c.jsx($,{name:"history",className:"h-4 w-4"}),"Revert"]}),c.jsxs(be,{type:"button",variant:"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{F()},children:[c.jsx($,{name:"git-branch",className:"h-4 w-4"}),"Fork"]})]})]})})},HY=e=>e.open?c.jsx(OY,{...e}):null;function FY(e,t,n=30){const r=e.toLowerCase(),s=t.toLowerCase(),o=r.indexOf(s);if(o===-1)return null;const i=Math.max(0,o-n),a=Math.min(e.length,o+t.length+n);return`${i>0?"…":""}${e.slice(i,a).replace(/\n/g," ")}${a<e.length?"…":""}`}const BY=e=>{const t=e.startsWith("#")?e.slice(1):e;if(!t)return null;const n=t.match(/^turn-(.+)$/);if(n?.[1])return{kind:"turn",id:n[1]};const r=t.match(/^message-(.+)$/);return r?.[1]?{kind:"message",id:r[1]}:null},VY=(e,t,n)=>{if(n===0)return{kind:"noop"};if(e.length===0)return{kind:"noop"};const r=t?e.indexOf(t):e.length-1,o=(r>=0?r:e.length-1)+n;if(o>=e.length)return{kind:"resume"};const i=Math.max(0,o),a=e[i];return a?{kind:"turn",turnId:a}:{kind:"noop"}},hl=e=>{if(typeof window>"u")return;const t=e?`#${e}`:"",n=`${window.location.pathname}${window.location.search}${t}`;window.history.replaceState(window.history.state,"",n)},$Y=({sessionId:e,turnIds:t,activeTurnId:n,scrollToTurn:r,scrollToMessage:s,resumeToBottom:o})=>{const i=p.useRef(t),a=p.useRef(n);p.useEffect(()=>{i.current=t},[t]),p.useEffect(()=>{a.current=n},[n]);const l=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&hl(`turn-${h}`),r(h,{behavior:m?.behavior})):!1,[r]),d=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&hl(`message-${h}`),s(h,{behavior:m?.behavior})):!1,[s]),f=p.useCallback(async(h,m)=>{const g=i.current,x=VY(g,a.current,h);if(x.kind==="noop")return h===0;if(x.kind==="resume"){if(m?.resumePastEnd===!1){const b=g[g.length-1];return b?l(b,{behavior:"auto"}):!1}return hl(null),o(),!0}return l(x.turnId,{behavior:"auto"})},[o,l]),u=p.useCallback(()=>{hl(null),o()},[o]);return p.useEffect(()=>{if(!e||typeof window>"u")return;const h=()=>{const m=BY(window.location.hash);if(m){if(m.kind==="turn"){l(m.id,{behavior:"auto",updateHash:!1});return}d(m.id,{behavior:"auto",updateHash:!1})}};return h(),window.addEventListener("hashchange",h),()=>{window.removeEventListener("hashchange",h)}},[e,d,l,t.length]),{scrollToTurnId:l,scrollToMessageId:d,scrollByTurnOffset:f,resumeToLatest:u}},zY=[],UY={type:"idle"},w5="pichamber:chat-force-scroll-bottom",qY="Quota limit reached. Retrying automatically.",WY={overflowAnchor:"none",overscrollBehavior:"contain",overscrollBehaviorY:"contain","--scroll-shadow-top-size":"16px"},O9=e=>e?"relative":"relative z-10",Lh=(e,t=!1)=>R(O9(t),"flex flex-col gap-2 bg-background",e?"flex-1 min-h-0":"shrink-0"),KY=["a[href]","button","input","select","textarea",'[contenteditable="true"]','[role="button"]','[role="combobox"]','[role="dialog"]','[role="listbox"]','[role="menu"]','[role="menuitem"]','[role="option"]','[role="textbox"]',"[data-radix-popper-content-wrapper]"].join(","),GY=e=>e instanceof HTMLElement,gg=e=>GY(e)?!!e.closest(KY):!1,ZY=(e,t)=>typeof document>"u"||!e||e===document.body||e===document.documentElement||gg(e)?!0:!t?.contains(e),YY=()=>{const{isCommandPaletteOpen:e,isHelpDialogOpen:t,isImagePreviewOpen:n,isSessionSwitcherOpen:r,isSettingsDialogOpen:s}=re.getState();return e||t||n||r||s},XY=(e,t)=>{if(!t)return e;const n=e.indexOf(t);return n===-1?e:c.jsxs(c.Fragment,{children:[e.slice(0,n),c.jsx("span",{className:"font-medium",children:t}),e.slice(n+t.length)]})},S5=()=>{const e=he(n=>n.newSessionDraft.selectedProjectId??null),t=lt(p.useCallback(n=>jL({selectedProjectId:e,activeProjectId:n.activeProjectId,projects:n.projects}),[e]));return c.jsxs("div",{className:"oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center",children:[c.jsx("h1",{className:"text-balance text-3xl font-normal tracking-tight text-foreground",children:XY(t?`What are we working on in ${t}?`:"What are we working on?",t)}),c.jsx(w4,{onInsert:n=>{n.ref.type==="text"?Ye.getState().requestStarterTextInsert(n.insertText):Ye.getState().requestStarterInsert(n.promptName)},className:"oc-draft-starters mt-8 max-w-md"})]})},H9=p.memo(()=>{const e=he(l=>l.currentSessionId),t=he(p.useCallback(l=>e?l.sessionAbortFlags?.get(e)??null:null,[e])),{activeModel:n,working:r}=u9(),s=qb(e??""),o=We(l=>l.providers),i=p.useMemo(()=>{if(!n)return null;const l=o.length>0?o.find(d=>d.id===n.providerId):void 0;return j1(l,n.modelId)||null},[n,o]),a=!!(t&&!t.acknowledged);return c.jsx(J3,{isWorking:r.isWorking,statusText:r.statusText,isGenericStatus:r.isGenericStatus,isWaitingForPermission:r.isWaitingForPermission,wasAborted:a||r.wasAborted,abortActive:a||r.abortActive,retryInfo:r.retryInfo,showAssistantStatus:!0,showTodos:!1,modelName:i,providerId:n?.providerId??null,turnStartedAt:s})});H9.displayName="StatusRowContainer";const JY=160,Rh=28,QY=12,Ni=6,eX=8,Li=30,Ri=12,C5=18,tX=80,pl=4,nX=10,rX=14,sX=20,on=54,k5=4,oX=8,M5=2,iX=160,aX=(e,t)=>e.map(n=>{const r=t.get(n)??[];return{turnId:n,preview:D9(r,JY)}}),cX=[1,.6,.35,.15],lX=(e,t,n)=>{const r=n?rX:nX;if(t===null)return r;const s=Math.abs(e-t),o=cX[s]??0;return Math.round(r+(sX-r)*o)};function dX({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:s,isLoadingOlder:o,onLoadEarlier:i}){const a=re(J=>J.isPromptNavigatorPanelOpen),l=re(J=>J.setPromptNavigatorPanelOpen),d=p.useRef(null),f=p.useRef(null),[u,h]=p.useState(null),[m,g]=p.useState(0),[x,b]=p.useState(!1),[S,y]=p.useState(Ni);p.useEffect(()=>{const J=f.current?.parentElement;if(!J||typeof ResizeObserver>"u")return;const ne=()=>{const Ue=J.querySelector(".chat-message-column");if(!Ue){b(!1),y(Ni);return}const st=J.getBoundingClientRect(),Ee=Ue.getBoundingClientRect(),Ke=st.right-Ee.right-eX-Rh;if(Ke<=Ni){y(Ni);const _t=st.right-Ni-Rh;b(Ee.right>_t);return}y(Ke),b(!1)};ne();const fe=new ResizeObserver(ne);fe.observe(J);const De=J.querySelector(".chat-message-column");return De&&fe.observe(De),()=>fe.disconnect()},[e.length]);const v=p.useMemo(()=>aX(e,t),[t,e]),C=Math.min(v.length,Li),w=Math.max(0,v.length-C),I=Math.min(m,w),E=I+C,T=I>0,A=E<v.length,j="[No text content]",k="Current prompt",_="Load more prompts",M=p.useMemo(()=>n?v.findIndex(J=>J.turnId===n):-1,[n,v]),L=p.useRef(I);L.current=I;const O=p.useRef(v.length);O.current=v.length;const N=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useCallback(J=>{g(ne=>{const fe=O.current,De=Math.min(fe,Li),Ue=Math.max(0,fe-De),st=Math.min(ne,Ue);return J<st?J:J>=st+De?Math.min(Ue,J-De+1):st})},[]),X=p.useRef(v[0]?.turnId),F=p.useRef(v.length);p.useLayoutEffect(()=>{const J=X.current,ne=F.current,fe=v.length-ne;fe>0&&ne>0&&J&&v[0]?.turnId!==J&&(g(De=>De+fe),h(De=>De===null?null:De+fe)),X.current=v[0]?.turnId,F.current=v.length},[v]),p.useEffect(()=>{if(u!==null)return;const J=M>=0?M:v.length-1;g(()=>{const ne=O.current,fe=Math.min(ne,Li),De=Math.max(0,ne-fe);return Math.max(0,Math.min(De,J-Math.floor(fe/2)))})},[M,u,v.length]);const U=p.useCallback(J=>{const ne=d.current;if(!ne)return null;const fe=ne.getBoundingClientRect(),De=Math.floor((J-fe.top)/Ri),Ue=Math.min(O.current,Li);return Ue===0?null:Math.max(0,Math.min(Ue-1,De))},[]),P=p.useCallback(()=>{W.current=0,D.current!==null&&(window.clearInterval(D.current),D.current=null)},[]),q=p.useCallback(()=>{const J=W.current;if(J===0){P();return}const ne=O.current,fe=Math.min(ne,Li),De=Math.max(0,ne-fe),Ue=Math.min(L.current,De),st=Math.max(0,Math.min(De,Ue+J));if(st===Ue){P();return}L.current=st,g(st);const Ee=N.current;if(Ee!==null){const Ke=U(Ee);Ke!==null&&h(Math.min(ne-1,st+Ke))}},[U,P]),B=p.useCallback(J=>{const ne=d.current;if(!ne)return;const fe=ne.getBoundingClientRect(),De=J-fe.top;let Ue=0;if(De<=C5&&T?Ue=-1:De>=fe.height-C5&&A&&(Ue=1),W.current=Ue,Ue===0){P();return}D.current===null&&(D.current=window.setInterval(q,tX))},[q,T,A,P]);p.useEffect(()=>()=>{D.current!==null&&window.clearInterval(D.current)},[]);const ee=p.useRef(null),G=p.useCallback(()=>{ee.current!==null&&(window.clearTimeout(ee.current),ee.current=null)},[]),K=p.useCallback(()=>{G(),ee.current=window.setTimeout(()=>{ee.current=null,h(null)},iX)},[G]);p.useEffect(()=>()=>{ee.current!==null&&window.clearTimeout(ee.current)},[]);const se=p.useCallback(J=>{G(),N.current=J.clientY;const ne=U(J.clientY);ne!==null&&h(Math.min(O.current-1,L.current+ne)),B(J.clientY)},[G,U,B]),le=p.useCallback(()=>{N.current=null,P(),K()},[K,P]),oe=p.useCallback(()=>{l(!1)},[l]),ue=p.useCallback(J=>{if(J===null)return;const ne=v[J];ne&&(r(ne.turnId),P(),h(null),oe(),d.current?.blur())},[oe,r,v,P]),ye=p.useCallback(J=>{const ne=U(J.clientY);ne!==null&&ue(Math.min(v.length-1,L.current+ne))},[ue,v.length,U]);p.useEffect(()=>{if(!a)return;const J=d.current;!J||J===document.activeElement||(J.focus(),h(ne=>{if(ne!==null)return ne;const fe=M>=0?M:v.length-1;return z(fe),fe}))},[M,z,a,v.length]),p.useEffect(()=>()=>{l(!1)},[l]);const we=p.useCallback(J=>{if(v.length===0)return;const ne=u??(M>=0?M:v.length-1),fe=De=>{const Ue=Math.max(0,Math.min(v.length-1,De));z(Ue),h(Ue)};if(J.key==="ArrowUp"||J.key==="ArrowDown"){J.preventDefault(),fe(ne+(J.key==="ArrowUp"?-1:1));return}if(J.key==="Home"){J.preventDefault(),fe(0);return}if(J.key==="End"){J.preventDefault(),fe(v.length-1);return}if(J.key==="Enter"||J.key===" "){J.preventDefault(),ue(ne);return}J.key==="Escape"&&(J.preventDefault(),h(null),oe(),d.current?.blur())},[M,oe,z,ue,u,v]),Me=p.useCallback(()=>{P(),h(null),oe()},[oe,P]),He=p.useRef(null),Ae=p.useRef(u);Ae.current=u;const Ge=u!==null,et=p.useRef(0);p.useEffect(()=>{const J=He.current;if(!J)return;const ne=fe=>{fe.preventDefault(),fe.stopPropagation(),et.current+=fe.deltaY;const De=Math.trunc(et.current/on);if(De===0)return;et.current-=De*on;const Ue=Ae.current;if(Ue===null)return;const st=Math.max(0,Math.min(O.current-1,Ue+De));st!==Ue&&(z(st),h(st))};return J.addEventListener("wheel",ne,{passive:!1}),()=>J.removeEventListener("wheel",ne)},[z,Ge]);const Xe=u!==null?v[u]:void 0,te=Math.min(v.length,oX),Q=te*on,me=v.length*on-Q,Se=J=>Math.max(0,Math.min(me,J)),_e=p.useRef(null);let Fe=0;if(u===null)_e.current=null;else if(_e.current===null)Fe=Se(u*on-(Q-on)/2),_e.current=Fe;else{let J=_e.current;const ne=(u-M5)*on,fe=(u+1+M5)*on-Q;J>ne?J=ne:J<fe&&(J=fe),Fe=Se(J),_e.current=Fe}const ht=Math.floor(Fe/on),ge=Math.max(0,ht-pl),Ze=Math.min(v.length,ht+te+pl),Be=Fe>0,ie=Fe<me,ke=Be||ie?`linear-gradient(to bottom, ${Be?"transparent, black 10%":"black"}, ${ie?"black 90%, transparent":"black"})`:void 0,ve=Math.max(0,I-pl),xe=Math.min(v.length,E+pl),je=v.slice(ve,xe),ce=T||A?`linear-gradient(to bottom, ${T?"transparent, black 14%":"black"}, ${A?"black 86%, transparent":"black"})`:void 0;return v.length===0?null:c.jsx("nav",{ref:f,"aria-label":"Prompt navigation",className:"pointer-events-none absolute top-1/2 z-20 -translate-y-1/2",style:{right:`${S}px`},children:c.jsxs("div",{className:"pointer-events-auto flex flex-col items-end",children:[s?c.jsx("button",{type:"button",tabIndex:-1,className:R("-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full","text-[var(--surface-mutedForeground)] transition-colors","hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]",o?"cursor-wait opacity-70":void 0),"aria-label":_,title:_,disabled:o,onClick:J=>{J.stopPropagation(),o||i()},children:o?c.jsx($,{name:"loader-4",className:"size-3.5 animate-spin"}):c.jsx($,{name:"arrow-up-s",className:"size-3.5"})}):null,c.jsxs("div",{ref:d,role:"listbox",tabIndex:-1,"aria-activedescendant":Xe?`prompt-rail-tick-${Xe.turnId}`:void 0,className:"relative cursor-pointer outline-none",style:{width:`${x?QY:Rh}px`,height:`${C*Ri}px`},onMouseMove:se,onMouseLeave:le,onClick:ye,onKeyDown:we,onBlur:Me,children:[c.jsx("div",{className:"absolute inset-0 overflow-hidden",style:ce?{maskImage:ce,WebkitMaskImage:ce}:void 0,children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-300 ease-out",style:{transform:`translateY(-${I*Ri}px)`},children:je.map((J,ne)=>{const fe=ve+ne,De=J.turnId===n,Ue=u===fe,st=lX(fe,u,De);return c.jsx("div",{id:`prompt-rail-tick-${J.turnId}`,role:"option","aria-selected":Ue,"aria-current":De?"true":void 0,"aria-label":J.preview.trim()||j,className:"pointer-events-none absolute right-1 flex items-center justify-end",style:{top:`${fe*Ri}px`,height:`${Ri}px`},children:c.jsx("span",{"aria-hidden":"true",className:R("block h-0.5 rounded-full transition-all duration-200 ease-out",De?"bg-[var(--surface-foreground)]":Ue?"bg-[var(--surface-foreground)]/80":"bg-[var(--surface-foreground)]/30"),style:{width:`${st}px`}})},J.turnId)})},v[0]?.turnId)}),Xe&&u!==null?c.jsx("div",{ref:He,className:R("pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2","w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl","border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md"),onMouseEnter:G,onMouseLeave:K,onMouseMove:J=>J.stopPropagation(),onClick:J=>J.stopPropagation(),children:c.jsx("div",{className:"relative overflow-hidden",style:{height:`${te*on}px`,maskImage:ke,WebkitMaskImage:ke},children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-200 ease-out",style:{height:`${v.length*on}px`,transform:`translateY(-${Fe}px)`},children:v.slice(ge,Ze).map((J,ne)=>{const fe=ge+ne,De=J.turnId===n,Ue=u===fe;return c.jsx("div",{role:"option","aria-selected":Ue,"aria-current":De?"true":void 0,title:De?k:void 0,className:"absolute inset-x-0 cursor-pointer px-1.5",style:{top:`${fe*on+k5}px`,height:`${on-k5*2}px`},onMouseMove:()=>{G(),Ae.current!==fe&&(z(fe),h(fe))},onClick:()=>ue(fe),children:c.jsx("div",{className:R("flex h-full items-center rounded-lg border px-2 transition-colors",De?"border-transparent bg-[var(--interactive-selection)]":Ue?"border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]":"border-[var(--interactive-border)]/40"),children:c.jsx("span",{className:R("min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta",De?"text-[var(--interactive-selectionForeground)]":"text-[var(--surface-mutedForeground)]"),children:J.preview.trim()||j})})},J.turnId)})})})}):null]})]})})}const F9=p.memo(({currentSessionId:e,currentSessionKey:t,isDesktopExpandedInput:n,isMobile:r,directory:s,scrollRef:o,messageListRef:i,pendingRevealWork:a,renderedMessages:l,isLoadingOlder:d,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,streamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,handleMessageContentChange:S,getAnimationHandlers:y,handleHistoryScroll:v,scrollToBottom:C,isProgrammaticFollowActive:w,showLoadOlderButton:I,onLoadOlder:E,turnIds:T,activeTurnId:A,onSelectTurn:j,showPromptNavigator:k,canLoadEarlierPrompts:_,isLoadingOlderPrompts:M,onLoadEarlierPrompts:L})=>{const O=p.useRef(new Map),N=p.useRef(new WeakMap),D=p.useRef(new Map),W=p.useRef(e);W.current!==e&&(W.current=e,D.current.clear());const z=p.useMemo(()=>{const P=new Map;for(let B=0;B<l.length;B+=1){const ee=l[B];if(ee.info.role!=="user")continue;if(g7(ee)){const K=Uz(l,B)??"",se=D.current.get(ee.info.id);if(se&&se.command===K)P.set(ee.info.id,se.parts);else{const le=[{type:"text",text:K?`$ ${K}`:"/shell"}];D.current.set(ee.info.id,{command:K,parts:le}),P.set(ee.info.id,le)}continue}if(xK(ee.parts))continue;let G=N.current.get(ee.parts);G||(G=ug(ee.parts),N.current.set(ee.parts,G)),G.length!==0&&P.set(ee.info.id,G)}const q=O.current;if(q.size===P.size){let B=!0;for(const[ee,G]of P)if(q.get(ee)!==G){B=!1;break}if(B)return q}return O.current=P,P},[l]),X=p.useMemo(()=>T.filter(P=>z.has(P)),[z,T]),F=p.useMemo(()=>{if(!A||z.has(A))return A;const P=T.indexOf(A);for(let q=P-1;q>=0;q-=1){const B=T[q];if(z.has(B))return B}return null},[A,z,T]),U=p.useCallback(P=>{P.defaultPrevented||gg(P.target)||typeof window<"u"&&window.getSelection()?.type==="Range"||o.current?.focus({preventScroll:!0})},[o]);return c.jsx("div",{className:R("relative min-h-0",n?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":n,children:c.jsxs("div",{className:"absolute inset-0",children:[c.jsx(Su,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:o,style:WY,observeMutations:!1,size:24,hideTopShadow:!1,tabIndex:0,onClick:U,onScroll:v,"data-scroll-shadow":"true","data-scrollbar":"chat",children:c.jsxs("div",{className:"relative z-0 min-h-full",children:[I&&c.jsx("div",{className:"flex justify-center pt-3 pb-1",children:c.jsxs(be,{variant:"secondary",size:"sm",onClick:E,disabled:d,children:[d&&c.jsx($,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx(XZ,{ref:i,sessionKey:e,disableStaging:a,messages:l,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,activeStreamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,onMessageContentChange:S,getAnimationHandlers:y,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:s},t),T.length===0&&f?c.jsx("div",{className:"mb-3",children:c.jsx(H9,{})}):T.length===0&&u?c.jsx("div",{className:"chat-message-column mb-3",children:c.jsx("span",{className:"typography-markdown leading-5 text-muted-foreground",role:"status","data-turn-reconnecting":"true",children:"Reconnecting · last seen working"})}):null,c.jsx("div",{className:"flex-shrink-0",style:{height:r?"calc(40px + var(--oc-safe-area-bottom, 0px))":"calc(10vh + var(--oc-safe-area-bottom, 0px))"},"aria-hidden":"true"})]})}),c.jsx(t3,{containerRef:o,suppressVisibility:w,userIntentOnly:!0,observeMutations:!1}),k&&X.length>=2?c.jsx(dX,{turnIds:X,previewsByTurnId:z,activeTurnId:F,onSelectTurn:j,canLoadEarlier:_,isLoadingOlder:M,onLoadEarlier:L}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.currentSessionKey===t.currentSessionKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.sessionAwaitingRecovery===t.sessionAwaitingRecovery&&e.awaitingPromptEcho===t.awaitingPromptEcho&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.compactionOverlay===t.compactionOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.scrollToBottom===t.scrollToBottom&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts);F9.displayName="ChatViewport";const uX={isWorking:!1,isAwaitingRecovery:!1},zQ=({active:e=!0,autoOpenDraft:t=!0})=>{const n=he(Ee=>Ee.currentSessionId),r=he(Ee=>Ee.currentSessionDirectory),s=he(Ee=>Ee.openNewSessionDraft),o=he(Ee=>Ee.newSessionDraft),i=he(Ee=>Ee.sendingNewSessionDraftId),a=Nw(o,n,i),l=W3(),d=c_(),f=r??d,u=n?JSON.stringify([Y(),f,n]):null,h=p.useCallback(Ee=>l.ensureSessionRenderable(Ee),[l]),m=p.useCallback(async()=>{},[]),g=re(Ee=>Ee.isExpandedInput),x=re(Ee=>Ee.isTimelineDialogOpen),b=re(Ee=>Ee.setTimelineDialogOpen),S=Iw(),y=l4(),v=u_(n??""),w=S==="ready"&&!y?v:null,I=w?"streaming":null,E=p_(n??""),T=jw(n??""),A=fu(n??""),j=W4(n),k=n?A:zY,_=Ew(n??""),M=l_(n??""),[L]=p.useState(PA);p.useEffect(()=>{if(!(!e||!u||!T||k.length===0))return L.schedule(u,k.length)},[e,u,L,T,k.length]);const O=du(n??"")??UY,N=uu(n??""),D=p.useMemo(()=>{if(!n)return uX;const Ee=O.type??"idle",Ke=k[k.length-1]?.info,_t=typeof Ke?.finish=="string"?Ke.finish:void 0,fn=!!(Ke&&Ke.role==="assistant"&&typeof Ke.time?.completed!="number"&&_t!=="stop"&&_t!=="error");return KN({connection:S,transportUncertain:y,authoritativeWorking:Ee==="busy"&&!N||Ee==="retry",hasPendingAssistant:fn,hasRetainedStream:!!v})},[S,n,v,N,k,O.type,y]),W=D.isWorking,z=D.isAwaitingRecovery,X=i_(n??""),F=W||X,U=f_(n??""),P=p.useMemo(()=>{if(!n||O.type!=="retry")return null;const Ee=typeof O.message=="string"?(O.message??"").trim():"";return{sessionId:n,message:Ee||qY,confirmedAt:O.confirmedAt}},[n,O]),q=s_(n??""),B=p.useMemo(()=>n&&q?{sessionId:n,compaction:q}:null,[q,n]),[ee,G]=p.useState(0),K=p.useRef(null);p.useEffect(()=>{if(!P||typeof P.confirmedAt=="number"){K.current=null,G(0);return}K.current!==P.sessionId&&(K.current=P.sessionId,G(Date.now()))},[P]);const se=p.useMemo(()=>P?{...P,fallbackTimestamp:ee}:null,[P,ee]),le=p.useMemo(()=>n?{limit:k.length,complete:M.complete||!M.cursor,loading:M.status==="loading"}:null,[n,M.complete,M.cursor,M.status,k.length]),{isMobile:oe}=Dn(),ue=Iu(),ye=!!o?.open,we=oe&&g,Me=oe||ue==="mini-chat",He=p.useRef(null);p.useEffect(()=>{vw().sessionId||t&&!n&&!ye&&s({automatic:!0})},[t,n,ye,s]);const Ae=p.useRef(()=>{}),Ge=p.useCallback(Ee=>{Ae.current(Ee)},[]),{scrollRef:et,notifyContentChange:Xe,getAnimationHandlers:te,goToBottom:Q,scrollToBottomOnSend:me,releaseAutoFollow:Se,restoreSnapshot:_e,isPinned:Fe,isFollowingProgrammatically:ht,showScrollButton:ge}=yY({currentSessionId:n,currentSessionKey:u,sessionMessageCount:E,latestTailEntryId:_.at(-1)?.id??null,sessionIsWorking:F,isMobile:oe,onActiveTurnChange:Ge}),Be=DY({sessionId:n,sessionKey:u,messages:k,historyMeta:le,scrollRef:et,messageListRef:He,loadMoreMessages:m,goToBottom:Q,releaseAutoFollow:Se,isPinned:Fe,showScrollButton:ge}),ie=p.useCallback(()=>{Q("instant")},[Q]),ke=dn()&&Be.historySignals.canLoadEarlier,ve=Be.loadEarlier,xe=p.useCallback(()=>{ve({userInitiated:!0})},[ve]);p.useEffect(()=>{Ae.current=Be.handleActiveTurnChange},[Be.handleActiveTurnChange]);const je=$Y({sessionId:n,turnIds:Be.turnIds,activeTurnId:Be.activeTurnId,scrollToTurn:Be.scrollToTurn,scrollToMessage:Be.scrollToMessage,resumeToBottom:Be.resumeToBottomInstant}),ce=p.useCallback(Ee=>{je.scrollToTurnId(Ee,{behavior:"smooth"})},[je]),J=Be.historySignals.canLoadEarlier,ne=!oe&&!we&&Be.turnIds.length>=2;p.useEffect(()=>{ne||re.getState().setPromptNavigatorPanelOpen(!1)},[ne]),p.useEffect(()=>{if(typeof window>"u"||!n)return;const Ee=Ke=>{const _t=Ke;_t.detail?.sessionId&&_t.detail.sessionId!==n||Q("instant")};return window.addEventListener(w5,Ee),()=>{window.removeEventListener(w5,Ee)}},[n,Q]),p.useEffect(()=>{if(typeof window>"u"||!n||we)return;const Ee=Ke=>{if(Ke.defaultPrevented||Ke.isComposing||Ke.key!=="ArrowUp"&&Ke.key!=="ArrowDown"||Ke.altKey||Ke.ctrlKey||Ke.metaKey||Ke.shiftKey)return;const{activeMainTab:_t}=re.getState();if(_t!=="chat"||YY())return;const fn=et.current;if(ZY(document.activeElement,fn)||gg(Ke.target))return;Ke.preventDefault();const Sn=Ke.key==="ArrowUp"?-1:1;je.scrollByTurnOffset(Sn,{resumePastEnd:!1})};return window.addEventListener("keydown",Ee),()=>{window.removeEventListener("keydown",Ee)}},[n,we,je,et]),p.useLayoutEffect(()=>{const Ee=et.current;if(!Ee)return;const Ke=()=>{Ee.style.setProperty("--chat-scroll-height",`${Ee.clientHeight}px`)};Ke();let _t=0;const fn=()=>{_t||(_t=requestAnimationFrame(()=>{_t=0,Ke()}))};if(typeof ResizeObserver>"u")return window.addEventListener("resize",fn),()=>{_t&&cancelAnimationFrame(_t),window.removeEventListener("resize",fn)};const Sn=new ResizeObserver(fn);return Sn.observe(Ee),()=>{_t&&cancelAnimationFrame(_t),Sn.disconnect()}},[n,we,et]);const fe=p.useRef(null),Ue=!!n&&(!!n&&!T||M.status==="loading"),st=p.useCallback(()=>{!e||!n||l.ensureSessionRenderable(n)},[e,n,l]);return p.useEffect(()=>{if(!e||!n||fe.current===u)return;const Ee=typeof window<"u"&&window.location.hash.length>0;if(fe.current=u,Ee){Se();return}const Ke=()=>{_e()};typeof window>"u"?Ke():window.requestAnimationFrame(Ke)},[e,n,u,Se,_e]),p.useEffect(()=>{!e||!n||T||h(n)},[e,n,h,T]),!n&&!ye?t?c.jsx("div",{className:"flex h-full flex-col bg-background"}):c.jsx("div",{className:"flex flex-col h-full bg-background",children:c.jsx(Pz,{isNewSession:!0})}):!n&&ye?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(S5,{}):null,c.jsx("div",{className:R("relative z-10 flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsx(_i,{scrollToBottom:me})})]}):n?Ue?M.status==="error"?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center px-6",children:c.jsxs("div",{className:"max-w-sm text-center",children:[c.jsx("div",{className:"mx-auto mb-3 flex size-9 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--status-error)_10%,transparent)] text-[var(--status-error)]",children:c.jsx($,{name:"error-warning",className:"size-4"})}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:M.errorCode==="SESSION_IN_USE"?"Session is open elsewhere":"Session could not be loaded"}),c.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:M.errorCode==="SESSION_IN_USE"?"Another PiChamber instance is using this session. Close it there, then try again.":"Check the connection and try loading this session again."}),c.jsx(be,{variant:"outline",size:"sm",className:"mt-4",onClick:st,children:"Try again"})]})}),c.jsx("div",{className:Lh(!1),children:c.jsx(_i,{scrollToBottom:me})})]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:R("relative min-h-0 flex items-center justify-center",we?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":we,children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx(c1,{width:120,height:120,isAnimated:!0}),a?c.jsx("p",{role:"status",className:"typography-meta animate-pulse text-muted-foreground",children:"Creating session…"}):null]})}),c.jsx("div",{className:Lh(we),children:c.jsx(_i,{scrollToBottom:me})})]}):k.length===0&&_.length===0&&!W&&!z?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(S5,{}):null,c.jsx("div",{className:R(O9(j),"flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsxs("div",{className:"flex w-full min-w-0 flex-col gap-2",children:[c.jsx(zv,{sessionId:n}),c.jsx(Uv,{sessionId:n}),c.jsx(Yv,{sessionId:n,children:c.jsx(_i,{scrollToBottom:me})})]})}),c.jsx(Jv,{sessionId:n},n)]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex min-w-0 flex-1 flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx(F9,{currentSessionId:n,currentSessionKey:u??n,isDesktopExpandedInput:we,isMobile:oe,directory:f,scrollRef:et,messageListRef:He,pendingRevealWork:Be.pendingRevealWork,renderedMessages:Be.renderedMessages,isLoadingOlder:Be.isLoadingOlder,sessionIsWorking:W,sessionAwaitingRecovery:z,awaitingPromptEcho:U,streamingMessageId:w,activeStreamingPhase:I,retryOverlay:se,compactionOverlay:B,handleMessageContentChange:Xe,getAnimationHandlers:te,handleHistoryScroll:Be.handleHistoryScroll,scrollToBottom:ie,isProgrammaticFollowActive:ht,showLoadOlderButton:ke,onLoadOlder:xe,turnIds:Be.turnIds,activeTurnId:Be.activeTurnId,onSelectTurn:ce,showPromptNavigator:ne,canLoadEarlierPrompts:J,isLoadingOlderPrompts:Be.isLoadingOlder,onLoadEarlierPrompts:xe}),c.jsxs("div",{className:Lh(we,j),children:[!we&&k.length>0&&c.jsx(QZ,{visible:Be.showScrollToBottom,onClick:je.resumeToLatest}),c.jsx(q$,{sessionId:n}),c.jsx(zv,{sessionId:n}),c.jsx(Uv,{sessionId:n}),c.jsx(Yv,{sessionId:n,children:c.jsx(_i,{scrollToBottom:me})})]}),c.jsx(Jv,{sessionId:n},n),c.jsx(HY,{open:x,onOpenChange:b,onScrollToMessage:Be.scrollToMessage,onScrollByTurnOffset:je.scrollByTurnOffset,onResumeToLatest:ie,canLoadEarlier:Be.historySignals.canLoadEarlier,isLoadingEarlier:Be.isLoadingOlder,onLoadEarlier:xe,onRevert:async Ee=>{if(!n)return;const Ke=Ee.includes(":")?Ee.split(":")[0]??Ee:Ee;await he.getState().revertToMessage(n,Ke)},onFork:async Ee=>{if(!n)return;const Ke=Ee.includes(":")?Ee.split(":")[0]??Ee:Ee;await he.getState().forkFromMessage(n,Ke)}})]}):null},fX=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),hX=e=>e>=90?"critical":e>=75?"warn":"safe",UQ=({percentage:e,size:t=18,stroke:n=3,className:r})=>{const s=fX(e),o=hX(e),i=o==="critical"?"var(--status-error)":o==="warn"?"var(--status-warning)":"var(--status-success)",a=(t-n)/2,l=2*Math.PI*a;return c.jsxs("svg",{viewBox:`0 0 ${t} ${t}`,className:r??"size-[18px] -rotate-90",role:"progressbar","aria-valuenow":Math.round(s),"aria-valuemin":0,"aria-valuemax":100,children:[c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:"var(--interactive-border)",strokeWidth:n}),c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:i,strokeWidth:n,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:l*(1-s/100),className:"transition-[stroke-dashoffset,stroke] duration-300"})]})},pX=()=>{const e=re(n=>n.uiFont),t=re(n=>n.monoFont);return{uiFont:e,monoFont:t}},qQ=p.memo(function({visible:t}){const[n,r]=p.useState(!1);if(H.useEffect(()=>{if(!t)return;let o=!1;lr("desktop_get_current_window_state").then(a=>{o||r(!!a?.maximized)}).catch(()=>{});const i=a=>{const l=a.detail;r(!!l?.maximized)};return window.addEventListener("pichamber:window-maximized-changed",i),()=>{o=!0,window.removeEventListener("pichamber:window-maximized-changed",i)}},[t]),!t)return null;const s="app-region-no-drag inline-flex h-12 w-11 items-center justify-center text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary";return c.jsxs("div",{className:"app-region-no-drag ml-1 flex h-12 shrink-0 items-center","aria-label":"Window controls",children:[c.jsx("button",{type:"button",className:s,onClick:()=>{lr("desktop_minimize_current_window")},title:"Minimize window","aria-label":"Minimize window",children:c.jsx($,{name:"subtract",className:"h-4 w-4"})}),c.jsx("button",{type:"button",className:s,onClick:()=>{lr("desktop_toggle_current_window_maximized").then(o=>r(!!o?.maximized)).catch(()=>{})},title:n?"Restore window":"Maximize window","aria-label":n?"Restore window":"Maximize window",children:c.jsx($,{name:n?"fullscreen-exit":"checkbox-blank",className:"h-3.5 w-3.5"})}),c.jsx("button",{type:"button",className:R(s,"hover:bg-status-error hover:text-status-error-foreground"),onClick:()=>{lr("desktop_close_current_window")},title:"Close window","aria-label":"Close window",children:c.jsx($,{name:"close",className:"h-4 w-4"})})]})}),I5=new Set,Ph=new Map,mX=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace("%40","@").replace("%2F","/")}/files/${e.filePrefix}-latin-${t}-normal.woff2`,gX=(e,t)=>{const n=`${e.family}:${t}`;if(I5.has(n))return Promise.resolve();const r=Ph.get(n);if(r)return r;if(typeof document>"u"||typeof FontFace>"u"||!document.fonts)return Promise.resolve();const s=new FontFace(e.family,`url(${mX(e,t)}) format('woff2')`,{style:"normal",weight:String(t),display:"swap"});document.fonts.add(s);const o=s.load().then(()=>{I5.add(n)}).catch(i=>{document.fonts.delete(s),console.warn(`Failed to load font: ${e.family} ${t}`,i)}).finally(()=>{Ph.delete(n)});return Ph.set(n,o),o},B9=e=>e?Promise.all(e.weights.map(t=>gX(e,t))).then(()=>{}):Promise.resolve(),yX=e=>B9(Fh[e]?.source),vX=e=>B9(Bh[e]?.source);function WQ(){const{uiFont:e,monoFont:t}=pX();p.useEffect(()=>{if(typeof document>"u")return;const n=document.documentElement,r=Fh[e]?.stack??Fh[jC].stack,s=Bh[t]?.stack??Bh[TC].stack;yX(e),vX(t),n.style.setProperty("--font-sans",r),n.style.setProperty("--font-heading",r),n.style.setProperty("--font-family-sans",r),n.style.setProperty("--font-mono",s),n.style.setProperty("--font-family-mono",s),n.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=r)},[e,t])}export{kJ as $,Ua as A,be as B,p1 as C,VJ as D,CJ as E,QN as F,mu as G,aJ as H,$ as I,GE as J,n1 as K,tQ as L,pX as M,yX as N,We as O,c1 as P,l4 as Q,rQ as R,iT as S,GX as T,ZX as U,hp as V,$N as W,BE as X,WQ as Y,yy as Z,XX as _,lt as a,Fa as a$,RJ as a0,AJ as a1,NJ as a2,LJ as a3,wA as a4,KJ as a5,MJ as a6,IJ as a7,dJ as a8,pu as a9,Ta as aA,vu as aB,Ej as aC,cn as aD,TJ as aE,KX as aF,WX as aG,vw as aH,ze as aI,zX as aJ,DJ as aK,OJ as aL,LN as aM,HN as aN,ON as aO,Yn as aP,Wa as aQ,wt as aR,St as aS,Ct as aT,sA as aU,oA as aV,iA as aW,aA as aX,zQ as aY,dQ as aZ,uQ as a_,sJ as aa,xJ as ab,oJ as ac,lJ as ad,cJ as ae,qX as af,Ma as ag,yr as ah,CE as ai,Gm as aj,R_ as ak,O_ as al,gw as am,UX as an,nJ as ao,Xm as ap,Dr as aq,Dw as ar,Dn as as,O2 as at,d1 as au,gu as av,yu as aw,xu as ax,o1 as ay,Cu as az,Pm as b,qQ as b$,Ba as b0,Va as b1,Uo as b2,TD as b3,_1 as b4,Wo as b5,JR as b6,jD as b7,Nb as b8,n_ as b9,eJ as bA,UJ as bB,qJ as bC,Dj as bD,VO as bE,ku as bF,k$ as bG,WJ as bH,pQ as bI,b3 as bJ,$X as bK,TV as bL,zO as bM,un as bN,Zn as bO,u3 as bP,BX as bQ,Ga as bR,UO as bS,Vj as bT,vr as bU,gT as bV,za as bW,iJ as bX,AX as bY,W3 as bZ,NX as b_,fu as ba,Lt as bb,UQ as bc,_J as bd,pN as be,EJ as bf,fN as bg,jJ as bh,cd as bi,vt as bj,XI as bk,ep as bl,sL as bm,Vm as bn,FX as bo,Mw as bp,OX as bq,i1 as br,Pj as bs,Oj as bt,hV as bu,ur as bv,zJ as bw,eR as bx,tR as by,No as bz,Ca as c,V$ as c$,Or as c0,zl as c1,fk as c2,Hr as c3,HX as c4,RX as c5,Ye as c6,fQ as c7,zj as c8,$j as c9,mT as cA,mJ as cB,I1 as cC,Em as cD,Xd as cE,Ht as cF,D6 as cG,mb as cH,lQ as cI,IH as cJ,EH as cK,xR as cL,tG as cM,i$ as cN,qb as cO,PX as cP,_7 as cQ,PJ as cR,Ow as cS,pr as cT,DO as cU,U1 as cV,_w as cW,Ud as cX,Bd as cY,Fs as cZ,qf as c_,Gj as ca,by as cb,Sy as cc,wy as cd,wJ as ce,Cy as cf,ky as cg,SJ as ch,XT as ci,iQ as cj,aQ as ck,fh as cl,cQ as cm,Ll as cn,Zw as co,gJ as cp,ET as cq,F2 as cr,B2 as cs,Df as ct,yJ as cu,vJ as cv,$Q as cw,HT as cx,lT as cy,cT as cz,FM as d,sQ as d$,BJ as d0,FJ as d1,eL as d2,JN as d3,oH as d4,d4 as d5,iH as d6,aH as d7,cH as d8,lH as d9,Xq as dA,sg as dB,VQ as dC,$K as dD,tW as dE,PQ as dF,Su as dG,R3 as dH,L3 as dI,cP as dJ,fJ as dK,hJ as dL,pJ as dM,xU as dN,QJ as dO,AQ as dP,NQ as dQ,CQ as dR,bQ as dS,wQ as dT,SQ as dU,yQ as dV,yW as dW,IQ as dX,EQ as dY,_Q as dZ,MQ as d_,oQ as da,XJ as db,YJ as dc,ZJ as dd,JJ as de,rH as df,fX as dg,hX as dh,Qm as di,To as dj,iL as dk,DR as dl,kQ as dm,ZU as dn,ux as dp,bJ as dq,UT as dr,WT as ds,ZO as dt,Wt as du,HJ as dv,Mu as dw,bU as dx,uh as dy,Za as dz,Mp as e,t4 as e0,Fj as e1,Bj as e2,t3 as e3,OO as e4,HO as e5,FO as e6,qO as e7,WO as e8,rL as e9,$J as eA,GJ as eB,eQ as eC,LQ as ea,xQ as eb,TQ as ec,jQ as ed,dr as ee,uJ as ef,RQ as eg,mQ as eh,gQ as ei,DQ as ej,vW as ek,_x as el,IW as em,OQ as en,HQ as eo,FQ as ep,BQ as eq,CW as er,tq as es,Z7 as et,vQ as eu,_9 as ev,nQ as ew,LX as ex,VX as ey,rJ as ez,YX as f,qe as g,he as h,JX as i,$M as j,QX as k,Ls as l,hQ as m,M$ as n,ja as o,DX as p,C$ as q,r1 as r,Xj as s,Ce as t,tu as u,n3 as v,tJ as w,zo as x,Xn as y,qa as z};