@pi-chamber/web 1.0.5 → 1.0.6-rc.2

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 (539) hide show
  1. package/dist/assets/{DiagramView-CrKjR8CR.js → DiagramView-BdDt1SI7.js} +1 -1
  2. package/dist/assets/DiffView-Dk3VIX9E.js +18 -0
  3. package/dist/assets/FileSaveConflictDialog-DpyPjMH1.js +3 -0
  4. package/dist/assets/{FilesView-BRR3N7UA.js → FilesView-CumrwioK.js} +3 -3
  5. package/dist/assets/{GitHubDetailScaffold-C1UHuETI.js → GitHubDetailScaffold-CW2ZqU0Y.js} +3 -3
  6. package/dist/assets/{GitHubLinkPicker-B0O3Vapu.js → GitHubLinkPicker-BjJNQ7Ap.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-DvQDU--z.js → GitHubListPrimitives-BcB-cCTs.js} +1 -1
  8. package/dist/assets/{GitView-wAscrRhO.js → GitView-BoCaX5AO.js} +4 -4
  9. package/dist/assets/{IssuesSurface-mh50UUQ8.js → IssuesSurface-CDZENHrE.js} +3 -3
  10. package/dist/assets/{JsonTreeView-BfErTllU.js → JsonTreeView-DpCgOUXg.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-SXAK4uOu.js → MarkdownRendererImpl-BkT5TUWF.js} +2 -2
  12. package/dist/assets/{PatchDiff-CHr79sJ6.js → PatchDiff-Dcr3EQgA.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-CGpKcLro.js → PierreDiffViewer-o_Edh6ny.js} +3 -3
  14. package/dist/assets/PullRequestsSurface-eSXl6sef.js +2 -0
  15. package/dist/assets/{SessionSwitcherContent-DEAw6v12.js → SessionSwitcherContent-Dm30bfpn.js} +1 -1
  16. package/dist/assets/SessionSwitcherDropdown-CFj9VWSa.js +2 -0
  17. package/dist/assets/SessionUnreadDot-CHlK2awX.js +1 -0
  18. package/dist/assets/SettingsView-CcHRUyev.js +6 -0
  19. package/dist/assets/{SettingsWindow-BiY5FmhZ.js → SettingsWindow-BMzUErrM.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-BMITjK4e.js → StickyHorizontalScrollbar-p7EbL2-E.js} +2 -2
  21. package/dist/assets/{ToolOutputDialog-B3RRLhR3.js → ToolOutputDialog-QC8IoeBH.js} +4 -4
  22. package/dist/assets/{ToolPartDiffPreview-D9m_vrht.js → ToolPartDiffPreview-BigGwtul.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-B8lhZGLu.js → VirtualizedFileDiff-DvLCd7Qq.js} +4 -4
  24. package/dist/assets/{Virtualizer-DP6HbEeC.js → Virtualizer-DNJrJKVb.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-gegrE2dq.js → appThemeRegistry-Ca8eGRB9.js} +1 -1
  26. package/dist/assets/{collapsible-9MJx4VhA.js → collapsible-0yfy07W2.js} +1 -1
  27. package/dist/assets/{computeVirtualFileMetrics-Bjhk2CQS.js → computeVirtualFileMetrics-aX6tjjqv.js} +2 -2
  28. package/dist/assets/{contextFileOpenGuard-CsF5Boky.js → contextFileOpenGuard-CZKJuHxf.js} +1 -1
  29. package/dist/assets/{document-attachments-BslE4Ns7.js → document-attachments-CZl9rK1z.js} +5 -5
  30. package/dist/assets/{gitStatusPredicates-B3Zxud6E.js → gitStatusPredicates-3i8CcYWJ.js} +1 -1
  31. package/dist/assets/{githubLink-CbGYxsIq.js → githubLink-BvevcNay.js} +5 -5
  32. package/dist/assets/index-BMdbHCFt.js +1 -0
  33. package/dist/assets/{index-D4n3TVp2.js → index-C2ISrmRR.js} +10 -10
  34. package/dist/assets/index-DgwThEwf.css +1 -0
  35. package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
  36. package/dist/assets/main-BM-b2y8p.js +2 -0
  37. package/dist/assets/main-BXZ561E3.js +137 -0
  38. package/dist/assets/{markdown-shiki.worker-DnvH1S1x.js → markdown-shiki.worker-BVA5NZBT.js} +5 -5
  39. package/dist/assets/markdownCore-DbS8DkKw.js +2 -0
  40. package/dist/assets/miniChat-DO3DW6kJ.js +2 -0
  41. package/dist/assets/mobile-BgWLkut6.js +2 -0
  42. package/dist/assets/{nativeFileSave-BJsGPh58.js → nativeFileSave-Bhafll_7.js} +1 -1
  43. package/dist/assets/nsis-LY0VT_u5.js +1 -0
  44. package/dist/assets/permissionStore-zIpxq9Pq.js +1 -0
  45. package/dist/assets/pi-session-focus-preference-ChYVctYk.js +9 -0
  46. package/dist/assets/{registerCustomTheme-DmolaWWZ.js → registerCustomTheme-C-h6lsYW.js} +1 -1
  47. package/dist/assets/{renderDiffWithHighlighter-BhMEWmHn.js → renderDiffWithHighlighter-xlvSvnTf.js} +1 -1
  48. package/dist/assets/renderElectronMiniChatApp-CgVqxKDm.js +2 -0
  49. package/dist/assets/{renderFileWithHighlighter-DUGluXlw.js → renderFileWithHighlighter-CCoYfC-t.js} +1 -1
  50. package/dist/assets/renderMobileApp-CoY1tsk5.js +11 -0
  51. package/dist/assets/ruby-BK5aLJev.js +1 -0
  52. package/dist/assets/runtimeEndpointReset-fozcAShH.js +62 -0
  53. package/dist/assets/runtimeSurface-CJN1oo_1.js +1 -0
  54. package/dist/assets/themeResolver-DrfmQi8i.js +1 -0
  55. package/dist/assets/useAppFontEffects-D_gtiA95.js +215 -0
  56. package/dist/assets/useFilesViewSearch-BUxcZj60.js +7 -0
  57. package/dist/assets/{useGitHubRemoteSearch-DYoLQ4ro.js → useGitHubRemoteSearch-CevR5iLf.js} +1 -1
  58. package/dist/assets/{useSwitcherItems-BS6E199F.js → useSwitcherItems-kaRkXggX.js} +1 -1
  59. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js +1 -0
  60. package/dist/assets/vendor-base-ui-C7vVMZTg.js +1 -0
  61. package/dist/assets/{vendor-beautiful-mermaid-DApbjBp2.js → vendor-beautiful-mermaid-b48gT2g0.js} +1 -1
  62. package/dist/assets/vendor-boot-CoTxysn6.js +65 -0
  63. package/dist/assets/{vendor-capacitor-app-BaupizkW.js → vendor-capacitor-app-NX6DULfp.js} +1 -1
  64. package/dist/assets/{vendor-capacitor-keyboard-9BVxykO7.js → vendor-capacitor-keyboard-DJD81I9f.js} +1 -1
  65. package/dist/assets/{vendor-capacitor-status-bar-BsrUwiaA.js → vendor-capacitor-status-bar-DV24OoQV.js} +1 -1
  66. package/dist/assets/vendor-codemirror-autocomplete-qsuH4Dh-.js +1 -0
  67. package/dist/assets/vendor-codemirror-lang-angular-ZHWyBf7j.js +1 -0
  68. package/dist/assets/vendor-codemirror-lang-cpp-pCTOmv-k.js +1 -0
  69. package/dist/assets/vendor-codemirror-lang-css-2bFuyM70.js +1 -0
  70. package/dist/assets/{vendor-codemirror-lang-go-Crwca_X7.js → vendor-codemirror-lang-go-DrG_c7D7.js} +2 -2
  71. package/dist/assets/vendor-codemirror-lang-html-BV8lrR8v.js +1 -0
  72. package/dist/assets/vendor-codemirror-lang-java-DrsvH6T2.js +1 -0
  73. package/dist/assets/vendor-codemirror-lang-javascript-Dkzl3s07.js +13 -0
  74. package/dist/assets/vendor-codemirror-lang-jinja-8Nn3bnoP.js +1 -0
  75. package/dist/assets/vendor-codemirror-lang-json-CsdmtHhi.js +1 -0
  76. package/dist/assets/vendor-codemirror-lang-less-DJuZ4cZe.js +1 -0
  77. package/dist/assets/vendor-codemirror-lang-liquid-D2RO-Pzr.js +1 -0
  78. package/dist/assets/vendor-codemirror-lang-markdown-C0Zu3b3n.js +1 -0
  79. package/dist/assets/vendor-codemirror-lang-php-CuDtt2Zj.js +1 -0
  80. package/dist/assets/vendor-codemirror-lang-python-Cv2exx_M.js +3 -0
  81. package/dist/assets/vendor-codemirror-lang-rust-C4TxJ6Rg.js +1 -0
  82. package/dist/assets/vendor-codemirror-lang-sass-BmtPz8kf.js +1 -0
  83. package/dist/assets/{vendor-codemirror-lang-sql-B0f-qCZo.js → vendor-codemirror-lang-sql-BF1ZaXqJ.js} +2 -2
  84. package/dist/assets/vendor-codemirror-lang-vue-DZgXrP2k.js +1 -0
  85. package/dist/assets/vendor-codemirror-lang-wast-DsnaGtL_.js +1 -0
  86. package/dist/assets/vendor-codemirror-lang-xml-D8DzzFat.js +1 -0
  87. package/dist/assets/vendor-codemirror-lang-yaml-D5hBv7m6.js +1 -0
  88. package/dist/assets/{vendor-codemirror-language-data-CqU7kHmg.js → vendor-codemirror-language-data-vn2RyN9T.js} +2 -2
  89. package/dist/assets/vendor-codemirror-search-BVCYIV0D.js +2 -0
  90. package/dist/assets/vendor-dompurify-BGCr_sdL.js +3 -0
  91. package/dist/assets/vendor-elkjs-D1S1RCAO.js +24 -0
  92. package/dist/assets/vendor-fuse.js-t_7AcMTv.js +1 -0
  93. package/dist/assets/{vendor-hast-util-to-html-BKBhbTDb.js → vendor-hast-util-to-html-O3stl53j.js} +1 -1
  94. package/dist/assets/{vendor-heic2any-pq-UTQQR.js → vendor-heic2any-sztndhZI.js} +1 -1
  95. package/dist/assets/vendor-lezer-cpp-vqXSn3lv.js +1 -0
  96. package/dist/assets/vendor-lezer-css-JnEzSyZR.js +1 -0
  97. package/dist/assets/{vendor-lezer-go-CHIhCNY6.js → vendor-lezer-go-dD2gQMIL.js} +1 -1
  98. package/dist/assets/{vendor-lezer-html-B3h0MOrG.js → vendor-lezer-html-Cr3U-1pu.js} +1 -1
  99. package/dist/assets/vendor-lezer-java-CRM0IMCo.js +1 -0
  100. package/dist/assets/vendor-lezer-javascript-B3s21DIS.js +1 -0
  101. package/dist/assets/{vendor-lezer-json-BP_UAzLL.js → vendor-lezer-json-DPFM6EBV.js} +1 -1
  102. package/dist/assets/vendor-lezer-lr-Bllrq8hY.js +1 -0
  103. package/dist/assets/vendor-lezer-markdown-6-3PLvXG.js +6 -0
  104. package/dist/assets/vendor-lezer-php-DOyzfHRl.js +1 -0
  105. package/dist/assets/{vendor-lezer-python-EJ4Im4y2.js → vendor-lezer-python-CdHdN5qt.js} +1 -1
  106. package/dist/assets/vendor-lezer-rust-CqnW8EMH.js +1 -0
  107. package/dist/assets/{vendor-lezer-sass-CMi6zfXI.js → vendor-lezer-sass-BbcF4y6A.js} +1 -1
  108. package/dist/assets/{vendor-lezer-xml-0MHMeZDp.js → vendor-lezer-xml-C31AyWoo.js} +1 -1
  109. package/dist/assets/{vendor-lezer-yaml-BE2EFjpA.js → vendor-lezer-yaml-Cv908yC2.js} +1 -1
  110. package/dist/assets/{vendor-lru_map-DOPmc7GU.js → vendor-lru_map-BbiDqlyL.js} +1 -1
  111. package/dist/assets/vendor-marked-Be78pDn1.js +59 -0
  112. package/dist/assets/{vendor-oniguruma-parser-C0D4_9rT.js → vendor-oniguruma-parser-BrbMHgHx.js} +1 -1
  113. package/dist/assets/vendor-oniguruma-to-es-DgwFOwdE.js +94 -0
  114. package/dist/assets/{vendor-pierre-theming-Dgp7B_O4.js → vendor-pierre-theming-BO6EPniU.js} +1 -1
  115. package/dist/assets/vendor-property-information-C40bX6nM.js +1 -0
  116. package/dist/assets/{vendor-qrcode-Dv4uniC1.js → vendor-qrcode-gzL9QFkg.js} +5 -5
  117. package/dist/assets/vendor-react-Bz1tRBxM.js +1 -0
  118. package/dist/assets/{vendor-react-drawio-Duu5LgQA.js → vendor-react-drawio-IYnLUY5N.js} +1 -1
  119. package/dist/assets/vendor-remend-DcBOpbSu.js +24 -0
  120. package/dist/assets/vendor-replit-codemirror-vim-Cwhyn_5f.js +6 -0
  121. package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
  122. package/dist/assets/vendor-shiki-BEwTOAFg.js +1 -0
  123. package/dist/assets/{vendor-shikijs-core-CGM_jqPK.js → vendor-shikijs-core-Ck_OPM_T.js} +1 -1
  124. package/dist/assets/{vendor-shikijs-engine-javascript-Cme4830A.js → vendor-shikijs-engine-javascript-DL394yyj.js} +1 -1
  125. package/dist/assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js +3 -0
  126. package/dist/assets/vendor-tailwind-merge-BKkUfl9q.js +1 -0
  127. package/dist/assets/vendor-workbox-window-BBnX5xw4.js +2 -0
  128. package/dist/assets/vendor-zumer-snapdom-SJzqoCHV.js +8 -0
  129. package/dist/assets/vendor-zustand-CXhN0IMY.js +6 -0
  130. package/dist/assets/{web-components-DzQ9ybbb.js → web-components-6ORYp3Iv.js} +1 -1
  131. package/dist/assets/worker-CKCfxIfO.js +153 -0
  132. package/dist/assets/workerFactory-DlGfNFqf.js +1 -0
  133. package/dist/assets/zig-BB16gwVL.js +1 -0
  134. package/dist/index.html +8 -8
  135. package/dist/mini-chat.html +7 -7
  136. package/dist/mobile.html +7 -7
  137. package/package.json +54 -53
  138. package/server/index.js +18 -1
  139. package/server/lib/client-auth/live-revocation.test.js +4 -0
  140. package/server/lib/fs/DOCUMENTATION.md +10 -0
  141. package/server/lib/fs/project-icon.js +243 -0
  142. package/server/lib/fs/project-icon.test.js +114 -0
  143. package/server/lib/fs/routes.js +35 -0
  144. package/server/lib/fs/routes.test.js +74 -0
  145. package/server/lib/git/DOCUMENTATION.md +2 -1
  146. package/server/lib/git/routes.js +11 -3
  147. package/server/lib/git/routes.test.js +80 -0
  148. package/server/lib/git/service.js +38 -3
  149. package/server/lib/git/service.test.js +93 -0
  150. package/server/lib/open-url/DOCUMENTATION.md +35 -0
  151. package/server/lib/open-url/browser-env.js +199 -0
  152. package/server/lib/open-url/browser-env.test.js +147 -0
  153. package/server/lib/open-url/browser-handler.mjs +154 -0
  154. package/server/lib/open-url/browser-handler.test.js +69 -0
  155. package/server/lib/open-url/intake.js +187 -0
  156. package/server/lib/open-url/intake.test.js +75 -0
  157. package/server/lib/pi/extension-protocol.js +149 -0
  158. package/server/lib/pi/extension-protocol.test.js +20 -1
  159. package/server/lib/pi/routes.js +195 -1
  160. package/server/lib/pi/routes.test.js +129 -0
  161. package/server/lib/pi/session-daemon/DOCUMENTATION.md +38 -10
  162. package/server/lib/pi/session-daemon/builtin-extensions.js +14 -4
  163. package/server/lib/pi/session-daemon/daemon-process.js +13 -0
  164. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +6 -1
  165. package/server/lib/pi/session-daemon/extension-bridge.js +40 -6
  166. package/server/lib/pi/session-daemon/extension-custom-host.js +1259 -0
  167. package/server/lib/pi/session-daemon/extension-custom-host.test.js +759 -0
  168. package/server/lib/pi/session-daemon/extension-keybindings.js +21 -0
  169. package/server/lib/pi/session-daemon/extension-keybindings.test.js +37 -0
  170. package/server/lib/pi/session-daemon/extension-message-render.js +7 -4
  171. package/server/lib/pi/session-daemon/extension-message-render.test.js +14 -2
  172. package/server/lib/pi/session-daemon/extension-tool-render.js +7 -0
  173. package/server/lib/pi/session-daemon/extension-tool-render.test.js +26 -0
  174. package/server/lib/pi/session-daemon/open-request.js +60 -0
  175. package/server/lib/pi/session-daemon/open-request.test.js +54 -0
  176. package/server/lib/pi/session-daemon/prompt-preflight.test.js +134 -0
  177. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +21 -4
  178. package/server/lib/pi/session-daemon/session-daemon-bash.e2e.test.js +225 -0
  179. package/server/lib/pi/session-daemon/session-daemon-directory-catalog.e2e.test.js +156 -0
  180. package/server/lib/pi/session-daemon/session-daemon-directory-catalog.test.js +381 -0
  181. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +11 -2
  182. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +30 -4
  183. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +20 -0
  184. package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +16 -4
  185. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +7 -2
  186. package/server/lib/pi/session-daemon/session-daemon.js +448 -49
  187. package/server/lib/pi/session-daemon/session-daemon.test.js +91 -4
  188. package/server/lib/pi/session-daemon/session-engine-router.js +9 -3
  189. package/server/lib/pi/session-daemon/session-engine-router.test.js +12 -2
  190. package/server/lib/pi/session-daemon/session-engines.js +7 -2
  191. package/server/lib/pi/session-daemon/session-jsonl.js +170 -75
  192. package/server/lib/pi/session-daemon/session-jsonl.test.js +106 -2
  193. package/server/lib/pi/session-daemon/supervisor.js +4 -0
  194. package/server/lib/pi/session-daemon/user-bash.js +326 -0
  195. package/server/lib/pi/session-daemon/user-bash.test.js +371 -0
  196. package/server/lib/preview/proxy-runtime.js +140 -45
  197. package/server/lib/preview/proxy-runtime.test.js +174 -3
  198. package/server/lib/preview/proxy-runtime.websocket.test.js +89 -0
  199. package/server/lib/relay/tunnel-host.js +1 -0
  200. package/server/lib/security/request-security.js +37 -0
  201. package/server/lib/security/request-security.test.js +54 -0
  202. package/server/lib/security/server-network-host.js +107 -0
  203. package/server/lib/security/server-network-host.test.js +70 -0
  204. package/server/lib/server-browser/DOCUMENTATION.md +243 -0
  205. package/server/lib/server-browser/browser-tab.js +524 -0
  206. package/server/lib/server-browser/chrome-executable.js +138 -0
  207. package/server/lib/server-browser/chrome-launch.js +138 -0
  208. package/server/lib/server-browser/dev-servers.js +288 -0
  209. package/server/lib/server-browser/dev-servers.test.js +152 -0
  210. package/server/lib/server-browser/downloads.js +75 -0
  211. package/server/lib/server-browser/frame-policy.js +183 -0
  212. package/server/lib/server-browser/frame-policy.test.js +98 -0
  213. package/server/lib/server-browser/network-guard.js +235 -0
  214. package/server/lib/server-browser/page-scripts.js +209 -0
  215. package/server/lib/server-browser/runtime.integration.test.js +474 -0
  216. package/server/lib/server-browser/runtime.js +300 -0
  217. package/server/lib/server-browser/runtime.test.js +50 -0
  218. package/server/lib/server-browser/server-browser.js +431 -0
  219. package/server/lib/server-browser/server-browser.test.js +975 -0
  220. package/server/lib/server-browser/tab-input.js +241 -0
  221. package/server/lib/server-browser/tab-prompts.js +125 -0
  222. package/server/lib/server-browser/tab-stream.js +252 -0
  223. package/server/lib/server-browser/uploads.js +98 -0
  224. package/server/lib/stt/runtime.js +4 -1
  225. package/server/lib/stt/runtime.test.js +43 -0
  226. package/server/lib/terminal/runtime.js +4 -1
  227. package/server/lib/terminal/runtime.test.js +41 -0
  228. package/server/lib/ui-auth/DOCUMENTATION.md +29 -1
  229. package/server/lib/ui-auth/ui-auth.js +1 -0
  230. package/server/lib/ui-auth/ui-auth.test.js +9 -1
  231. package/server/lib/workspace/host.js +20 -3
  232. package/dist/assets/DiffView-CSonR3pr.js +0 -18
  233. package/dist/assets/FileSaveConflictDialog-Cun0LIbj.js +0 -3
  234. package/dist/assets/PullRequestsSurface-CfaOpeZn.js +0 -2
  235. package/dist/assets/SessionSwitcherDropdown-BSutduo7.js +0 -2
  236. package/dist/assets/SessionUnreadDot-Dav_rix1.js +0 -1
  237. package/dist/assets/SettingsView-CQJkOPJh.js +0 -6
  238. package/dist/assets/abap-BdImnpbu.js +0 -1
  239. package/dist/assets/actionscript-3-CoDkCxhg.js +0 -1
  240. package/dist/assets/ada-bCR0ucgS.js +0 -1
  241. package/dist/assets/angular-html-CU67Zn6k.js +0 -1
  242. package/dist/assets/angular-ts-BwZT4LLn.js +0 -1
  243. package/dist/assets/apache-Pmp26Uib.js +0 -1
  244. package/dist/assets/apex-D8_7TLub.js +0 -1
  245. package/dist/assets/apl-dKokRX4l.js +0 -1
  246. package/dist/assets/applescript-Co6uUVPk.js +0 -1
  247. package/dist/assets/ara-BRHolxvo.js +0 -1
  248. package/dist/assets/asciidoc-Ve4PFQV2.js +0 -1
  249. package/dist/assets/asm-D_Q5rh1f.js +0 -1
  250. package/dist/assets/astro-CbQHKStN.js +0 -1
  251. package/dist/assets/awk-DMzUqQB5.js +0 -1
  252. package/dist/assets/ballerina-BFfxhgS-.js +0 -1
  253. package/dist/assets/bat-BkioyH1T.js +0 -1
  254. package/dist/assets/beancount-k_qm7-4y.js +0 -1
  255. package/dist/assets/berry-uYugtg8r.js +0 -1
  256. package/dist/assets/bibtex-CHM0blh-.js +0 -1
  257. package/dist/assets/bicep-Bmn6On1c.js +0 -1
  258. package/dist/assets/bird2-DPOp833l.js +0 -1
  259. package/dist/assets/blade-D4QpJJKB.js +0 -1
  260. package/dist/assets/bsl-BO_Y6i37.js +0 -1
  261. package/dist/assets/c-BIGW1oBm.js +0 -1
  262. package/dist/assets/c3-eo99z4R2.js +0 -1
  263. package/dist/assets/cadence-Bv_4Rxtq.js +0 -1
  264. package/dist/assets/cairo-KRGpt6FW.js +0 -1
  265. package/dist/assets/clarity-D53aC0YG.js +0 -1
  266. package/dist/assets/clojure-P80f7IUj.js +0 -1
  267. package/dist/assets/cmake-D1j8_8rp.js +0 -1
  268. package/dist/assets/cobol-nwyudZeR.js +0 -1
  269. package/dist/assets/codeowners-Bp6g37R7.js +0 -1
  270. package/dist/assets/codeql-DsOJ9woJ.js +0 -1
  271. package/dist/assets/coffee-Ch7k5sss.js +0 -1
  272. package/dist/assets/common-lisp-Cg-RD9OK.js +0 -1
  273. package/dist/assets/coq-DkFqJrB1.js +0 -1
  274. package/dist/assets/cpp-CofmeUqb.js +0 -1
  275. package/dist/assets/crystal-tKQVLTB8.js +0 -1
  276. package/dist/assets/csharp-COcwbKMJ.js +0 -1
  277. package/dist/assets/css-DPfMkruS.js +0 -1
  278. package/dist/assets/csv-fuZLfV_i.js +0 -1
  279. package/dist/assets/cue-D82EKSYY.js +0 -1
  280. package/dist/assets/cypher-COkxafJQ.js +0 -1
  281. package/dist/assets/d-85-TOEBH.js +0 -1
  282. package/dist/assets/dart-CF10PKvl.js +0 -1
  283. package/dist/assets/dax-CEL-wOlO.js +0 -1
  284. package/dist/assets/desktop-BmXAJ9_W.js +0 -1
  285. package/dist/assets/diff-D97Zzqfu.js +0 -1
  286. package/dist/assets/docker-BcOcwvcX.js +0 -1
  287. package/dist/assets/dotenv-Da5cRb03.js +0 -1
  288. package/dist/assets/dream-maker-BtqSS_iP.js +0 -1
  289. package/dist/assets/edge-BkV0erSs.js +0 -1
  290. package/dist/assets/elixir-CDX3lj18.js +0 -1
  291. package/dist/assets/elm-DbKCFpqz.js +0 -1
  292. package/dist/assets/emacs-lisp-C9XAeP06.js +0 -1
  293. package/dist/assets/erb-B12qg9BL.js +0 -1
  294. package/dist/assets/erlang-DsQrWhSR.js +0 -1
  295. package/dist/assets/fennel-BYunw83y.js +0 -1
  296. package/dist/assets/fish-BvzEVeQv.js +0 -1
  297. package/dist/assets/fluent-C4IJs8-o.js +0 -1
  298. package/dist/assets/fortran-fixed-form-CkoXwp7k.js +0 -1
  299. package/dist/assets/fortran-free-form-BxgE0vQu.js +0 -1
  300. package/dist/assets/fsharp-CXgrBDvD.js +0 -1
  301. package/dist/assets/gdresource-BOOCDP_w.js +0 -1
  302. package/dist/assets/gdscript-C5YyOfLZ.js +0 -1
  303. package/dist/assets/gdshader-DkwncUOv.js +0 -1
  304. package/dist/assets/genie-D0YGMca9.js +0 -1
  305. package/dist/assets/gherkin-DyxjwDmM.js +0 -1
  306. package/dist/assets/git-commit-F4YmCXRG.js +0 -1
  307. package/dist/assets/git-rebase-r7XF79zn.js +0 -1
  308. package/dist/assets/gleam-BspZqrRM.js +0 -1
  309. package/dist/assets/glimmer-js-Rg0-pVw9.js +0 -1
  310. package/dist/assets/glimmer-ts-U6CK756n.js +0 -1
  311. package/dist/assets/glsl-DplSGwfg.js +0 -1
  312. package/dist/assets/gn-n2N0HUVH.js +0 -1
  313. package/dist/assets/gnuplot-DdkO51Og.js +0 -1
  314. package/dist/assets/go-CxLEBnE3.js +0 -1
  315. package/dist/assets/graphql-ChdNCCLP.js +0 -1
  316. package/dist/assets/groovy-gcz8RCvz.js +0 -1
  317. package/dist/assets/hack-CaT9iCJl.js +0 -1
  318. package/dist/assets/haml-B8DHNrY2.js +0 -1
  319. package/dist/assets/handlebars-BL8al0AC.js +0 -1
  320. package/dist/assets/haskell-Df6bDoY_.js +0 -1
  321. package/dist/assets/haxe-CzTSHFRz.js +0 -1
  322. package/dist/assets/hcl-BWvSN4gD.js +0 -1
  323. package/dist/assets/hjson-D5-asLiD.js +0 -1
  324. package/dist/assets/hlsl-D3lLCCz7.js +0 -1
  325. package/dist/assets/html-GMplVEZG.js +0 -1
  326. package/dist/assets/html-derivative-BFtXZ54Q.js +0 -1
  327. package/dist/assets/http-jrhK8wxY.js +0 -1
  328. package/dist/assets/hurl-irOxFIW8.js +0 -1
  329. package/dist/assets/hxml-Bvhsp5Yf.js +0 -1
  330. package/dist/assets/hy-DFXneXwc.js +0 -1
  331. package/dist/assets/imba-DGztddWO.js +0 -1
  332. package/dist/assets/index-B0h6_x5N.js +0 -1
  333. package/dist/assets/index-BwoW_-vk.css +0 -1
  334. package/dist/assets/ini-BEwlwnbL.js +0 -1
  335. package/dist/assets/java-CylS5w8V.js +0 -1
  336. package/dist/assets/javascript-wDzz0qaB.js +0 -1
  337. package/dist/assets/jinja-4LBKfQ-Z.js +0 -1
  338. package/dist/assets/jison-wvAkD_A8.js +0 -1
  339. package/dist/assets/json-Cp-IABpG.js +0 -1
  340. package/dist/assets/json5-C9tS-k6U.js +0 -1
  341. package/dist/assets/jsonc-Des-eS-w.js +0 -1
  342. package/dist/assets/jsonl-DcaNXYhu.js +0 -1
  343. package/dist/assets/jsonnet-DFQXde-d.js +0 -1
  344. package/dist/assets/jssm-C2t-YnRu.js +0 -1
  345. package/dist/assets/jsx-g9-lgVsj.js +0 -1
  346. package/dist/assets/julia-CxzCAyBv.js +0 -1
  347. package/dist/assets/just-Cw27pwNe.js +0 -1
  348. package/dist/assets/kdl-DV7GczEv.js +0 -1
  349. package/dist/assets/kotlin-BdnUsdx6.js +0 -1
  350. package/dist/assets/kusto-DZf3V79B.js +0 -1
  351. package/dist/assets/latex-CWtU0Tv5.js +0 -1
  352. package/dist/assets/lean-BZvkOJ9d.js +0 -1
  353. package/dist/assets/less-B1dDrJ26.js +0 -1
  354. package/dist/assets/liquid-DYVedYrR.js +0 -1
  355. package/dist/assets/llvm-DjAJT7YJ.js +0 -1
  356. package/dist/assets/log-2UxHyX5q.js +0 -1
  357. package/dist/assets/logo-BtOb2qkB.js +0 -1
  358. package/dist/assets/lua-BaeVxFsk.js +0 -1
  359. package/dist/assets/luau-C-HG3fhB.js +0 -1
  360. package/dist/assets/main-C6i4ph9N.js +0 -2
  361. package/dist/assets/main-r5elIPBi.js +0 -136
  362. package/dist/assets/make-CHLpvVh8.js +0 -1
  363. package/dist/assets/markdown-Cvjx9yec.js +0 -1
  364. package/dist/assets/markdownCore-C2YQ3Z0q.js +0 -2
  365. package/dist/assets/marko-CnJfTvn9.js +0 -1
  366. package/dist/assets/matlab-D7o27uSR.js +0 -1
  367. package/dist/assets/mdc-BMNejdWA.js +0 -1
  368. package/dist/assets/mdx-Cmh6b_Ma.js +0 -1
  369. package/dist/assets/mermaid-mWjccvbQ.js +0 -1
  370. package/dist/assets/miniChat-d_GCHoIf.js +0 -2
  371. package/dist/assets/mipsasm-CKIfxQSi.js +0 -1
  372. package/dist/assets/mobile-BJ3tgyKd.js +0 -2
  373. package/dist/assets/mojo-rZm6bMo-.js +0 -1
  374. package/dist/assets/moonbit-_H4v1dQx.js +0 -1
  375. package/dist/assets/move-IF9eRakj.js +0 -1
  376. package/dist/assets/narrat-DRg8JJMk.js +0 -1
  377. package/dist/assets/nextflow-Zz6hmt5N.js +0 -1
  378. package/dist/assets/nextflow-groovy-BeH2EWoN.js +0 -1
  379. package/dist/assets/nginx-BpAMiNFr.js +0 -1
  380. package/dist/assets/nim-CVrawwO9.js +0 -1
  381. package/dist/assets/nix-CwoSXNpI.js +0 -1
  382. package/dist/assets/nsis-LdVXkNf5.js +0 -1
  383. package/dist/assets/nushell-Cz2AlsmD.js +0 -1
  384. package/dist/assets/objective-c-DXmwc3jG.js +0 -1
  385. package/dist/assets/objective-cpp-CLxacb5B.js +0 -1
  386. package/dist/assets/ocaml-C0hk2d4L.js +0 -1
  387. package/dist/assets/odin-BBf5iR-q.js +0 -1
  388. package/dist/assets/openscad-C4EeE6gA.js +0 -1
  389. package/dist/assets/pascal-D93ZcfNL.js +0 -1
  390. package/dist/assets/perl-C0TMdlhV.js +0 -1
  391. package/dist/assets/permissionStore-B9Hkrqny.js +0 -1
  392. package/dist/assets/php-Dhbhpdrm.js +0 -1
  393. package/dist/assets/pi-session-focus-preference-BFnGFuvP.js +0 -9
  394. package/dist/assets/pkl-u5AG7uiY.js +0 -1
  395. package/dist/assets/plsql-ChMvpjG-.js +0 -1
  396. package/dist/assets/po-BTJTHyun.js +0 -1
  397. package/dist/assets/polar-C0HS_06l.js +0 -1
  398. package/dist/assets/postcss-CXtECtnM.js +0 -1
  399. package/dist/assets/powerquery-CEu0bR-o.js +0 -1
  400. package/dist/assets/powershell-Dpen1YoG.js +0 -1
  401. package/dist/assets/prisma-Dd19v3D-.js +0 -1
  402. package/dist/assets/prolog-CbFg5uaA.js +0 -1
  403. package/dist/assets/proto-C7zT0LnQ.js +0 -1
  404. package/dist/assets/pug-CGlum2m_.js +0 -1
  405. package/dist/assets/puppet-BMWR74SV.js +0 -1
  406. package/dist/assets/purescript-CklMAg4u.js +0 -1
  407. package/dist/assets/python-B6aJPvgy.js +0 -1
  408. package/dist/assets/qml-3beO22l8.js +0 -1
  409. package/dist/assets/qmldir-C8lEn-DE.js +0 -1
  410. package/dist/assets/qss-IeuSbFQv.js +0 -1
  411. package/dist/assets/r-Dspwwk_N.js +0 -1
  412. package/dist/assets/racket-BqYA7rlc.js +0 -1
  413. package/dist/assets/raku-DXvB9xmW.js +0 -1
  414. package/dist/assets/razor-Uh8Bk_45.js +0 -1
  415. package/dist/assets/reg-C-SQnVFl.js +0 -1
  416. package/dist/assets/regexp-CDVJQ6XC.js +0 -1
  417. package/dist/assets/rel-C3B-1QV4.js +0 -1
  418. package/dist/assets/renderElectronMiniChatApp-Bap5OwgB.js +0 -2
  419. package/dist/assets/renderMobileApp-DJbslvby.js +0 -11
  420. package/dist/assets/riscv-BM1_JUlF.js +0 -1
  421. package/dist/assets/ron-D8l8udqQ.js +0 -1
  422. package/dist/assets/rosmsg-BJDFO7_C.js +0 -1
  423. package/dist/assets/rst-BrH8l1NY.js +0 -1
  424. package/dist/assets/ruby-B2Rjki9n.js +0 -1
  425. package/dist/assets/ruby-Dw2BHqvy.js +0 -1
  426. package/dist/assets/runtimeEndpointReset-D22U_Vjs.js +0 -62
  427. package/dist/assets/runtimeSurface-k1Eit61v.js +0 -1
  428. package/dist/assets/rust-B1yitclQ.js +0 -1
  429. package/dist/assets/sas-cz2c8ADy.js +0 -1
  430. package/dist/assets/sass-Cj5Yp3dK.js +0 -1
  431. package/dist/assets/scala-C151Ov-r.js +0 -1
  432. package/dist/assets/scheme-C98Dy4si.js +0 -1
  433. package/dist/assets/scss-OYdSNvt2.js +0 -1
  434. package/dist/assets/sdbl-DVxCFoDh.js +0 -1
  435. package/dist/assets/shaderlab-Dg9Lc6iA.js +0 -1
  436. package/dist/assets/shellscript-Yzrsuije.js +0 -1
  437. package/dist/assets/shellsession-BADoaaVG.js +0 -1
  438. package/dist/assets/smalltalk-BERRCDM3.js +0 -1
  439. package/dist/assets/solidity-rGO070M0.js +0 -1
  440. package/dist/assets/soy-Brmx7dQM.js +0 -1
  441. package/dist/assets/sparql-rVzFXLq3.js +0 -1
  442. package/dist/assets/splunk-BtCnVYZw.js +0 -1
  443. package/dist/assets/sql-BLtJtn59.js +0 -1
  444. package/dist/assets/ssh-config-_ykCGR6B.js +0 -1
  445. package/dist/assets/stata-BH5u7GGu.js +0 -1
  446. package/dist/assets/stylus-BEDo0Tqx.js +0 -1
  447. package/dist/assets/surrealql-Bq5Q-fJD.js +0 -1
  448. package/dist/assets/svelte-C_ipcX3V.js +0 -1
  449. package/dist/assets/swift-D82vCrfD.js +0 -1
  450. package/dist/assets/system-verilog-CnnmHF94.js +0 -1
  451. package/dist/assets/systemd-4A_iFExJ.js +0 -1
  452. package/dist/assets/talonscript-CkByrt1z.js +0 -1
  453. package/dist/assets/tasl-QIJgUcNo.js +0 -1
  454. package/dist/assets/tcl-dwOrl1Do.js +0 -1
  455. package/dist/assets/templ-P3uqSqPl.js +0 -1
  456. package/dist/assets/terraform-BETggiCN.js +0 -1
  457. package/dist/assets/tex-idrVyKtj.js +0 -1
  458. package/dist/assets/themeResolver-yJ9XpNMI.js +0 -1
  459. package/dist/assets/toml-vGWfd6FD.js +0 -1
  460. package/dist/assets/ts-tags-zn1MmPIZ.js +0 -1
  461. package/dist/assets/tsv-B_m7g4N7.js +0 -1
  462. package/dist/assets/tsx-COt5Ahok.js +0 -1
  463. package/dist/assets/turtle-BsS91CYL.js +0 -1
  464. package/dist/assets/twig-DNn4PbVi.js +0 -1
  465. package/dist/assets/typescript-BPQ3VLAy.js +0 -1
  466. package/dist/assets/typespec-BGHnOYBU.js +0 -1
  467. package/dist/assets/typst-DHCkPAjA.js +0 -1
  468. package/dist/assets/useAppFontEffects-CqHhRKmN.js +0 -212
  469. package/dist/assets/useFilesViewSearch-CqoYEK0U.js +0 -7
  470. package/dist/assets/v-BcVCzyr7.js +0 -1
  471. package/dist/assets/vala-CsfeWuGM.js +0 -1
  472. package/dist/assets/vb-D17OF-Vu.js +0 -1
  473. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js +0 -1
  474. package/dist/assets/vendor-base-ui-CKRUCG-f.js +0 -1
  475. package/dist/assets/vendor-boot-EC6IyLt1.js +0 -69
  476. package/dist/assets/vendor-codemirror-autocomplete-CGpAsPWp.js +0 -1
  477. package/dist/assets/vendor-codemirror-lang-angular-CDJoHJSY.js +0 -1
  478. package/dist/assets/vendor-codemirror-lang-cpp-BmHofQls.js +0 -1
  479. package/dist/assets/vendor-codemirror-lang-css-RM2HqXZ0.js +0 -1
  480. package/dist/assets/vendor-codemirror-lang-html-CHSHUpwq.js +0 -1
  481. package/dist/assets/vendor-codemirror-lang-java-lhQXgWu0.js +0 -1
  482. package/dist/assets/vendor-codemirror-lang-javascript-Dw4kFO4e.js +0 -13
  483. package/dist/assets/vendor-codemirror-lang-jinja-_pAC3UTN.js +0 -1
  484. package/dist/assets/vendor-codemirror-lang-json-B-b1vAv-.js +0 -1
  485. package/dist/assets/vendor-codemirror-lang-less-xIgOi1ze.js +0 -1
  486. package/dist/assets/vendor-codemirror-lang-liquid-CP49m5dB.js +0 -1
  487. package/dist/assets/vendor-codemirror-lang-markdown-BTht2ATe.js +0 -1
  488. package/dist/assets/vendor-codemirror-lang-php-BguZDhaO.js +0 -1
  489. package/dist/assets/vendor-codemirror-lang-python-CH6_em9L.js +0 -3
  490. package/dist/assets/vendor-codemirror-lang-rust-EG_DtGyi.js +0 -1
  491. package/dist/assets/vendor-codemirror-lang-sass-BknY5Qpo.js +0 -1
  492. package/dist/assets/vendor-codemirror-lang-vue-CyGn9snv.js +0 -1
  493. package/dist/assets/vendor-codemirror-lang-wast-CsFfSyyB.js +0 -1
  494. package/dist/assets/vendor-codemirror-lang-xml-Cdan_Jp1.js +0 -1
  495. package/dist/assets/vendor-codemirror-lang-yaml-COI5hck8.js +0 -1
  496. package/dist/assets/vendor-codemirror-search-DUfSCF9S.js +0 -2
  497. package/dist/assets/vendor-dompurify-r8glNMJW.js +0 -2
  498. package/dist/assets/vendor-elkjs-D27273Ms.js +0 -24
  499. package/dist/assets/vendor-fuse.js-Dw8P0qyA.js +0 -1
  500. package/dist/assets/vendor-lezer-cpp-DMZOJzBa.js +0 -1
  501. package/dist/assets/vendor-lezer-css-DUkkbMp7.js +0 -1
  502. package/dist/assets/vendor-lezer-java-tMazV_6X.js +0 -1
  503. package/dist/assets/vendor-lezer-javascript-ctwLWf4v.js +0 -1
  504. package/dist/assets/vendor-lezer-lr-B8TQctNw.js +0 -1
  505. package/dist/assets/vendor-lezer-markdown-aGLZf_3h.js +0 -6
  506. package/dist/assets/vendor-lezer-php-D5zCNzlt.js +0 -1
  507. package/dist/assets/vendor-lezer-rust-DO5c7OtA.js +0 -1
  508. package/dist/assets/vendor-marked-CX41MkDF.js +0 -59
  509. package/dist/assets/vendor-oniguruma-to-es-DLBnFDCE.js +0 -94
  510. package/dist/assets/vendor-property-information-rJCbAzvX.js +0 -1
  511. package/dist/assets/vendor-react-DASdDPIk.js +0 -1
  512. package/dist/assets/vendor-remend-BWYYytN3.js +0 -22
  513. package/dist/assets/vendor-replit-codemirror-vim-AnOuN8yJ.js +0 -39
  514. package/dist/assets/vendor-shiki-Bbf2GEcE.js +0 -2
  515. package/dist/assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js +0 -3
  516. package/dist/assets/vendor-tailwind-merge-CPcsbTWB.js +0 -1
  517. package/dist/assets/vendor-workbox-window-BIl4cyR9.js +0 -2
  518. package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
  519. package/dist/assets/vendor-zustand-CUi8eEds.js +0 -6
  520. package/dist/assets/verilog-BQ8w6xss.js +0 -1
  521. package/dist/assets/vhdl-CeAyd5Ju.js +0 -1
  522. package/dist/assets/viml-CJc9bBzg.js +0 -1
  523. package/dist/assets/vue-DN_0RTcg.js +0 -1
  524. package/dist/assets/vue-html-AaS7Mt5G.js +0 -1
  525. package/dist/assets/vue-vine-CQOfvN7w.js +0 -1
  526. package/dist/assets/vyper-CDx5xZoG.js +0 -1
  527. package/dist/assets/wasm-MzD3tlZU.js +0 -1
  528. package/dist/assets/wenyan-BV7otONQ.js +0 -1
  529. package/dist/assets/wgsl-Dx-B1_4e.js +0 -1
  530. package/dist/assets/wikitext-BhOHFoWU.js +0 -1
  531. package/dist/assets/wit-5i3qLPDT.js +0 -1
  532. package/dist/assets/wolfram-lXgVvXCa.js +0 -1
  533. package/dist/assets/worker-BBk7yuNN.js +0 -153
  534. package/dist/assets/workerFactory-tw7cIdmV.js +0 -1
  535. package/dist/assets/xml-sdJ4AIDG.js +0 -1
  536. package/dist/assets/xsl-CtQFsRM5.js +0 -1
  537. package/dist/assets/yaml-Buea-lGh.js +0 -1
  538. package/dist/assets/zenscript-DVFEvuxE.js +0 -1
  539. package/dist/assets/zig-VOosw3JB.js +0 -1
@@ -0,0 +1,6 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-boot-CoTxysn6.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/nativeFileSave-Bhafll_7.js","assets/index-C2ISrmRR.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-DgwThEwf.css","assets/useAppFontEffects-D_gtiA95.js","assets/runtimeSurface-CJN1oo_1.js"])))=>i.map(i=>d[i]);
2
+ import{C as Oi,aP as cr,j as e,bj as Ui}from"./vendor-boot-CoTxysn6.js";import{R as o,a as D}from"./vendor-react-Bz1tRBxM.js";import{aD as $s,i as Ee,K as bs,b as Ve,j as ot,s as Ja,r as dr,ba as Fi,bW as ts,bX as ur,z as Te,bY as Bi,bZ as $i,f as H,a as Le,a9 as Kt,o as ea,ag as pr,ai as Ki,aj as Vi,ak as Wi,al as mr,b_ as Hi,ah as Gi,b$ as qi,U as Ke,au as Qi,x as Me,h as W,c0 as Ji,c1 as hr,c2 as Yi,c3 as Xi,a$ as Zi,bh as Rt,c4 as eo,c5 as to,c6 as it,bM as so,c7 as ao,v as Ya,c8 as fr,c9 as bn,bV as yn,ca as wn,a7 as jn,cb as no,aK as kn,bm as ro,aI as io,cc as Nn,cd as oo,ce as lo,bl as co,cf as uo,cg as po,ch as mo,ci as ho,cj as fo,ck as go,cl as xo,cm as vo,cn as bo,co as yo,cp as rt,W as Cn,cq as Sn,cr as Ca,br as wo,V as Tn,cs as Xa,ct as Pn,cu as jo,cv as ko,cw as No}from"./index-C2ISrmRR.js";import{b_ as Co,b$ as In,c0 as So,f as gr,B as E,I as R,P as xr,o as fs,c1 as _e,c2 as ze,c3 as Oe,c4 as Ue,c5 as ye,e as Ks,as as Ze,t as $,av as jt,aw as kt,ax as Nt,ay as Ct,az as St,aA as ta,c6 as sa,c7 as Xt,c8 as Za,c9 as Zt,aO as To,aP as en,bV as Mt,at as ee,bs as vr,a as Vs,aB as Po,ca as Io,cb as Eo,cc as Ao,cd as Sa,ce as En,cf as Mo,cg as Lo,ch as Ro,ci as Do,cj as _o,ah as aa,z as na,ck as zo,cl as br,Q as Oo,s as Uo,cm as Fo,S as yr,cn as Bo,co as $o,cp as Ko,b4 as wr,cq as jr,cr as kr,cs as Nr,ct as Ws,O as Fe,cu as Hs,y as Cr,bS as tt,bT as st,cv as Vo,cw as Wo,cx as Ho,bL as Go,cy as qo,b7 as Qo,cz as Jo,aQ as Sr,aR as Tr,aS as Yo,cA as Xo,bI as Zo,E as gt}from"./useAppFontEffects-D_gtiA95.js";import{x as Y,y as Pe,z as ra,B as Be,E as el,G as tl,U as An,I as Ae,J as Mn,K as sl,L as al,P as nl,N as Ie,Q as Qe,R as pt,V as ke,X as Ft,Y as rl,Z as at,_ as Pr,$ as Ir,a0 as ys,a1 as vt,a2 as zt,a3 as bt,a4 as es,a5 as ss,a6 as Gs,a7 as Ta,a8 as Er,a9 as tn,aa as sn,ab as Ln,ac as Qt,ad as Jt,ae as il,af as Pa,ag as Ar,ah as ol,ai as gs,aj as ll,ak as cl,al as dl,am as ul}from"./runtimeEndpointReset-fozcAShH.js";import{_ as Ot}from"./vendor-vite-runtime-DD1OZmLC.js";import{Q as Mr}from"./vendor-qrcode-gzL9QFkg.js";import{p as pl}from"./vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js";import{c as ml}from"./vendor-zustand-CXhN0IMY.js";import{g as hl,s as fl}from"./runtimeSurface-CJN1oo_1.js";import{C as gl,a as xl,b as vl}from"./collapsible-0yfy07W2.js";const bl=["standalone","minimal-ui","fullscreen","window-controls-overlay"],yl=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,wl=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":bl.find(a=>yl(a))??"browser",qs="pichamber.mobile.connections.v1",jl="pichamber.mobile.",Rn="pichamber.mobile.deviceId",Lr=12,Rr=8e3,kl=2500,Nl=5e3,Dr=2500,as=15e3,_r=8e3,Cl=1500,Sl=5e3,Tl=()=>{try{const t=window.localStorage.getItem(Rn);if(t&&t.trim())return t.trim();const s=$s();return window.localStorage.setItem(Rn,s),s}catch{return $s()}},Dn=()=>`mobile:${Tl()}`,_n=()=>{try{const t=Oi.getPlatform();return t==="ios"||t==="android"?t:void 0}catch{return}},zr=()=>{let t=0;return{begin:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:s=>s===t}},Vt=t=>{const s=t.trim();if(!s)return"";const a=/^https?:\/\//i.test(s)?s:`http://${s}`,n=new URL(a);return n.hash="",n.search="",n.pathname=n.pathname.replace(/\/+$/,""),n.toString().replace(/\/+$/,"")},xs=t=>{try{return new URL(t).host}catch{return t}},yt=t=>{try{return Vt(t)}catch{return t.trim().replace(/\/+$/g,"")}},an=(t,s)=>yt(t)===yt(s),nn=t=>`relay:${t.serverId}@${t.relayUrl.trim()}`,Pl=t=>`relay://${t.serverId}`,ws=t=>t.candidates.filter(s=>s.kind==="direct"),Bt=t=>{const s=t.candidates.find(a=>a.kind==="relay");return s&&s.kind==="relay"?s.relay:null},Ut=t=>{const s=ws(t)[0];if(s)return s.url;const a=Bt(t);return a?Pl(a):""},Re=t=>{const s=Bt(t);if(s)return nn(s);const a=ws(t)[0];return a?yt(a.url):""},vs=(t,s)=>{const a=t.find(l=>l.kind==="relay"),n=a&&a.kind==="relay"?a.relay.serverId:null,r=new Set(t.filter(l=>l.kind==="direct").map(l=>yt(l.url)));return s.some(l=>l.kind==="relay"?n!==null&&l.relay.serverId===n:r.has(yt(l.url)))},rn=t=>{const s=(()=>{try{return Vt(t)}catch{return""}})();return s?[{kind:"direct",url:s}]:[]},zn=t=>{if(t.candidates&&t.candidates.length>0)return t.candidates;const s=[];return typeof t.url=="string"&&t.url.trim()&&!/^relay:\/\//i.test(t.url.trim())&&s.push(...rn(t.url)),t.relay&&s.push({kind:"relay",relay:t.relay}),s},on=t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t;if(typeof s.relayUrl!="string"||!s.relayUrl.trim()||typeof s.serverId!="string"||!s.serverId.trim())return null;const a=s.hostEncPubJwk;if(!a||typeof a!="object"||Array.isArray(a))return null;const n=a;return n.kty!=="EC"||n.crv!=="P-256"||typeof n.x!="string"||!n.x||typeof n.y!="string"||!n.y?null:{relayUrl:s.relayUrl,serverId:s.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:n.x,y:n.y}}},Il=t=>{if(!t||typeof t!="object")return null;const s=t;if(s.kind==="direct")return typeof s.url=="string"&&s.url.trim()?{kind:"direct",url:s.url}:null;if(s.kind==="relay"){const a=on(s.relay);return a?{kind:"relay",relay:a}:null}return null},El=t=>{if(t.mode==="relay"){const s=on(t.relay);return s?[{kind:"relay",relay:s}]:[]}return typeof t.url=="string"?rn(t.url):[]},js=t=>t.kind==="relay"?{kind:"relay",relay:{relayUrl:t.relay.relayUrl,serverId:t.relay.serverId,hostEncPubJwk:t.relay.hostEncPubJwk}}:{kind:"direct",url:t.url},Tt=()=>{if(typeof window>"u")return[];let t;try{t=JSON.parse(window.localStorage.getItem(qs)||"[]")}catch{return[]}if(!Array.isArray(t))return[];const s=Ee();return t.flatMap(a=>{if(!a||typeof a!="object")return[];const n=a;if(typeof n.id!="string")return[];const r=Array.isArray(n.candidates)?n.candidates.map(Il).filter(m=>!!m):El(n);if(r.length===0)return[];const l=typeof n.clientToken=="string"&&n.clientToken.trim()?n.clientToken:void 0,d=typeof n.label=="string"&&n.label.trim()?n.label:xs(Ut({candidates:r})),i=typeof n.pinnedServerId=="string"&&n.pinnedServerId.trim()?n.pinnedServerId.trim():void 0,u={id:n.id,label:d,candidates:r,lastUsedAt:typeof n.lastUsedAt=="number"?n.lastUsedAt:0,...i?{pinnedServerId:i}:{}};return s?[{...u,hasToken:!!n.hasToken||!!l}]:[{...u,clientToken:l,hasToken:!!l}]}).sort((a,n)=>n.lastUsedAt-a.lastUsedAt)},ln=t=>{if(typeof window>"u")return;const s=Ee(),a=t.slice(0,Lr).map(n=>{const r={id:n.id,label:n.label,candidates:n.candidates.map(js),lastUsedAt:n.lastUsedAt,...typeof n.pinnedServerId=="string"&&n.pinnedServerId.trim()?{pinnedServerId:n.pinnedServerId.trim()}:{}};return s?{...r,hasToken:!!(n.hasToken||n.clientToken)}:{...r,clientToken:n.clientToken}});try{window.localStorage.setItem(qs,JSON.stringify(a))}catch(n){console.warn("[mobile-storage] failed to persist connection metadata",n)}},Or=(t,s)=>{const a=t.find(l=>s.id&&l.id===s.id||vs(l.candidates,s.candidates)),n=Ee(),r={id:s.id||a?.id||$s(),label:s.label,candidates:s.candidates,lastUsedAt:Date.now(),pinnedServerId:typeof s.pinnedServerId=="string"&&s.pinnedServerId.trim()?s.pinnedServerId.trim():s.pinnedServerId===null?void 0:a?.pinnedServerId,...n?{hasToken:s.hasToken??(!!s.clientToken||a?.hasToken||!1)}:{clientToken:s.clientToken??a?.clientToken,hasToken:!!(s.clientToken??a?.clientToken)}};return[r,...t.filter(l=>l.id!==r.id&&!vs(l.candidates,s.candidates))].slice(0,Lr)},cn=pl,Al=0,ks=new Map,dn=t=>`${jl}token.${encodeURIComponent(t)}`,Ur=async(t,s)=>{let a;const n=new Promise(r=>{a=window.setTimeout(()=>r(s),Nl)});try{return await Promise.race([t.catch(()=>s),n])}finally{a!==void 0&&window.clearTimeout(a)}},Fr=async(t,s,a)=>Ee()?Ur(s().catch(n=>(console.warn(`[mobile-storage] ${t} failed`,n),a)),a):a,Ml=t=>{if(!t||typeof t!="object")return!1;const{code:s,message:a}=t;return s==="invalidData"?!0:typeof a=="string"&&/AEADBadTagException|BadPaddingException/.test(a)},Ns=async(t,s)=>{const a=s?.bypassCache?void 0:ks.get(t);if(typeof a=="string"&&a)return{status:"present",token:a};if(!Ee())return{status:"absent"};const n=await Ur(cn.internalGetItem({prefixedKey:dn(t),sync:!1}).then(l=>({kind:"ok",data:l?.data??null})).catch(l=>({kind:"error",error:l})),{kind:"timeout"});if(n.kind==="timeout")return console.warn("[mobile-storage] secure:read timed out"),{status:"failure"};if(n.kind==="error")return Ml(n.error)?(console.warn("[mobile-storage] secure:read undecryptable entry"),{status:"absent"}):(console.warn("[mobile-storage] secure:read failed",n.error),{status:"failure"});const r=n.data;return typeof r=="string"&&r.trim()?(ks.set(t,r),{status:"present",token:r}):{status:"absent"}},Lt=async(t,s)=>{if(!Ee())return!1;const a=await Fr("secure:write",async()=>(await cn.internalSetItem({prefixedKey:dn(t),data:s,sync:!1,access:Al}),!0),!1);return a&&s.trim()?ks.set(t,s):ks.delete(t),a},Ll=async t=>{ks.delete(t),await Fr("secure:delete",async()=>(await cn.internalRemoveItem({prefixedKey:dn(t),sync:!1}),!0),!1)},Br=async(t,s)=>{let a=0,n=0;return{records:await Promise.all(t.map(async l=>{if(!l||typeof l!="object")return l;const d=l,i=typeof d.url=="string"?d.url:null,u=typeof d.clientToken=="string"?d.clientToken.trim():"";if(!i||!u)return l;if(!await s(i,u))return n+=1,l;a+=1;const{clientToken:m,...p}=d;return{...p,hasToken:!0}})),migrated:a,failed:n}},$r=async()=>{if(typeof window>"u"||!Ee())return;let t;try{t=JSON.parse(window.localStorage.getItem(qs)||"[]")}catch{return}if(!Array.isArray(t)||t.filter(n=>!!n&&typeof n=="object"&&typeof n.url=="string"&&typeof n.clientToken=="string"&&!!n.clientToken.trim()).length===0)return;const a=await Br(t,async(n,r)=>{const l=yt(n);if(!await Lt(l,r))return!1;const d=await Ns(l,{bypassCache:!0});return d.status==="present"&&d.token===r});if(a.migrated>0)try{window.localStorage.setItem(qs,JSON.stringify(a.records))}catch(n){console.warn("[mobile-storage] failed to finalize secure token migration",n)}},Kr=async()=>(await $r(),Tt()),Cs=async t=>{const s=Or(Tt(),t);return ln(s),Ee()&&t.clientToken&&await Lt(Re({candidates:t.candidates}),t.clientToken),s},Vr=async t=>{const s=Tt(),a=s.find(r=>r.id===t)??null,n=s.filter(r=>r.id!==t);return ln(n),a&&Ee()&&await Ll(Re(a)),n},un=t=>{try{return JSON.stringify(t)}catch{return String(t)}},De=(t,s={})=>{console.info("[mobile-connect]",t,un(s)),dr("connect",{code:t,status:typeof s.status=="number"?s.status:void 0,detail:typeof s.reason=="string"?s.reason:typeof s.result=="string"?s.result:void 0})},Rl=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Dl=t=>{if(typeof t!="string")return t??void 0;try{return JSON.parse(t)}catch{return t}},_l=async(t,s,a)=>{if(!Ee())return null;const n=a?.timeoutMs??Rr;try{const{CapacitorHttp:r}=await Ot(async()=>{const{CapacitorHttp:i}=await import("./vendor-boot-CoTxysn6.js").then(u=>u.co);return{CapacitorHttp:i}},__vite__mapDeps([0,1,2])),l=Object.fromEntries(new Headers(s?.headers).entries()),d=await r.request({url:t,method:s?.method||"GET",headers:l,data:Dl(s?.body),connectTimeout:n,readTimeout:n});return{ok:d.status>=200&&d.status<300,status:d.status,source:"native-http",json:async()=>Rl(d.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",un({url:t,error:r instanceof Error?r.message:String(r)})),null}},zl=async(t,s)=>{const a=await fetch(t,s).catch(n=>(console.warn("[mobile-connect]","browser-fetch failed",un({url:t,error:n instanceof Error?n.message:String(n)})),null));return a?{ok:a.ok,status:a.status,source:"browser-fetch",json:()=>a.json()}:null},wt=async(t,s,a)=>{let n;const r=new Promise(l=>{n=window.setTimeout(()=>{a?.(),l(null)},t)});try{return await Promise.race([s,r])}catch{return null}finally{n!==void 0&&window.clearTimeout(n)}},$t=async(t,s,a)=>{const n=a?.totalTimeoutMs??Rr,r=Date.now(),l=Math.min(kl,n),d=await wt(l,_l(t,s,{timeoutMs:l}));if(d)return d;const i=new AbortController,u=Math.max(500,n-(Date.now()-r));return wt(u,zl(t,{...s,signal:i.signal}),()=>i.abort())},ia=async t=>{if(!t)return null;const s=await t.json().catch(()=>null);if(!s||typeof s!="object")return null;const a=s;return{authenticated:typeof a.authenticated=="boolean"?a.authenticated:void 0,disabled:typeof a.disabled=="boolean"?a.disabled:void 0,scope:typeof a.scope=="string"?a.scope:void 0}},Ol=async(t,s,a,n=as,r)=>{if(r?.shouldAbort?.())return{outcome:"unreachable"};const l=ur({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk}),d=i=>i==="ok"&&r?.keepTunnel?{outcome:i,tunnel:l}:(l.close(),{outcome:i});try{const i=s?{Authorization:`Bearer ${s}`}:void 0,u=await wt(n,l.fetch("/auth/session",{headers:i}).catch(()=>null));if(De("relay:session",{ok:u?.ok===!0,status:u?.status??null,hasToken:!!s}),!u)return d("unreachable");if(u.status===401)return d(s?"auth-failed":"needs-login");if(!u.ok&&u.status!==404)return d("auth-failed");const m=await ia(u);return m&&m.disabled!==!0&&m.authenticated===!1?d(s?"auth-failed":"needs-login"):d("ok")}catch(i){throw l.close(),i}},Ul=(t,s,a,n,r)=>{const l=typeof window<"u"?window.location.origin:"",d={relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk,...a?{grant:a}:{}};r&&Fi(d,r),Ja({apiBaseUrl:l,clientToken:s,runtimeKey:n??nn(t),relay:d})},Wr=async t=>{if(!t?.ok)return null;const s=await t.json().catch(()=>null),a=s&&typeof s=="object"?s.serverId:null;return typeof a=="string"&&a.trim()?a.trim():null},Qs=async(t,s,a)=>{const n=a?.shouldAbort,r=a?.fast?{totalTimeoutMs:Dr}:void 0,l=Bt({candidates:t})?.serverId??null,d=t.find(h=>h.kind==="relay")??null,i=t.filter(h=>h.kind==="direct"),u=typeof a?.pinnedServerId=="string"&&a.pinnedServerId.trim()?a.pinnedServerId.trim():null,m=async()=>{let h=!1,c=null;for(const f of i){if(n?.())return{status:"unreachable"};const y=Vt(f.url)||f.url,b=await $t(`${y}/health`,{method:"GET"},r);if(n?.())return{status:"unreachable"};if(!b?.ok)continue;const v=await Wr(b);if(u){if(v&&v!==u){De("probe:server-id-mismatch",{url:y}),h=!0;continue}}else v&&!c&&(c=v);if(l&&v&&v!==l){De("probe:server-id-mismatch",{url:y});continue}const L=s?{Authorization:`Bearer ${s}`}:void 0,j=await $t(`${y}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:L},r);if(n?.())return{status:"unreachable"};if(j?.status===401)return{status:"needs-login"};if(!j||!j.ok&&j.status!==404)continue;const T=await ia(j);if(T&&T.disabled!==!0&&T.authenticated===!1)return{status:"needs-login"};const P=T?.disabled===!0;return!s&&Ee()&&!P&&T?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:y,...v?{serverId:v}:{}},...c?{serverId:c}:{}}}return h?{status:"unreachable",reason:"wrong-server"}:{status:"unreachable"}},p=async()=>{if(!d)return{status:"unreachable"};if(n?.())return{status:"unreachable"};const{outcome:h,tunnel:c}=await Ol(d.relay,s,void 0,a?.fast?_r:void 0,{keepTunnel:!0,...n?{shouldAbort:n}:{}});return n?.()?(c?.close(),{status:"unreachable"}):h==="ok"?{status:"ok",transport:{kind:"relay",relay:d.relay,tunnel:c}}:h==="needs-login"||h==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return d?i.length===0?p():new Promise(h=>{let c=!1,f=!1,y,b=null,v=null;const L=P=>{P?.status==="ok"&&P.transport.kind==="relay"&&P.transport.tunnel?.close()},j=P=>{c||(c=!0,h(P))},T=()=>{f||c||n?.()||(y!==void 0&&(window.clearTimeout(y),y=void 0),p().then(P=>{if(v=P,c||f){L(P);return}if(P.status==="ok"||P.status==="needs-login"){j(P);return}b&&j(b)}))};m().then(P=>{if(b=P,!c){if(P.status==="ok"||P.status==="needs-login"){f=!0,y!==void 0&&window.clearTimeout(y),L(v),j(P);return}if(v){j(v);return}T()}}),y=window.setTimeout(T,Cl)}):m()},Dt=(t,s,a)=>{t.kind==="relay"?Ul(t.relay,s,a?.grant,a?.runtimeKey,t.tunnel):Ja({apiBaseUrl:t.url,clientToken:s,runtimeKey:a?.runtimeKey}),Yr()},Fl=()=>{const t=Tt()[0];return t?.label?.trim()?t.label:null},Bl=async()=>{const t=bs(),s=`${Ve()}|${ot()}`,a=()=>bs()!==t||`${Ve()}|${ot()}`!==s;if(await $r(),a())return{status:"no-candidate"};const n=Tt()[0];if(!n)return{status:"no-candidate"};let r;if(Ee()){if(!n.hasToken)return{status:"no-candidate"};const d=await Ns(Re(n));if(d.status==="failure")return{status:"unreachable",label:n.label};if(d.status==="absent"||!d.token)return{status:"needs-login",label:n.label};r=d.token}else if(r=n.clientToken,!r)return{status:"no-candidate"};const l=await Qs(n.candidates,r,{fast:!0,pinnedServerId:n.pinnedServerId});return a()?(Ua(l),{status:"no-candidate"}):l.status==="needs-login"?{status:"needs-login",label:n.label}:l.status!=="ok"?{status:"unreachable",label:n.label}:(await Cs({id:n.id,label:n.label,candidates:n.candidates,...!n.pinnedServerId&&l.serverId?{pinnedServerId:l.serverId}:{}}),a()?(Js(l.transport),{status:"no-candidate"}):(Dt(l.transport,r,{runtimeKey:Re(n)}),{status:"connected"}))},Hr=async(t,s)=>{let a="";try{a=Vt(t.url)}catch{return!1}if(!a)return!1;const n=t.clientToken?.trim()||void 0,r=n?{Authorization:`Bearer ${n}`}:void 0,l=s?.fast?{totalTimeoutMs:Dr}:void 0;if(!(await $t(`${a}/health`,{method:"GET",headers:r},l))?.ok)return!1;const i=await $t(`${a}/auth/session`,{method:"GET",credentials:n?"omit":"include",headers:r},l);if(!i||!i.ok&&i.status!==404)return!1;const u=await ia(i);return!(u&&u.disabled!==!0&&u.authenticated===!1)},On=async(t,s)=>{const a=Bt({candidates:t})?.serverId??null,n=typeof s=="string"&&s.trim()?s.trim():null;for(const r of t){if(r.kind==="relay"){const u=ur(r.relay),m=await wt(as,u.fetch("/health").catch(()=>null));if(De("establish:relay:health",{ok:m?.ok===!0,status:m?.status??null}),m?.ok)return{kind:"relay",relay:r.relay,tunnel:u};u.close();continue}const l=Vt(r.url)||r.url,d=await $t(`${l}/health`,{method:"GET"});if(De("establish:direct:health",{ok:d?.ok===!0,status:d?.status??null}),!d?.ok)continue;const i=await Wr(d);if(n&&i&&i!==n){De("establish:server-id-mismatch",{url:l});continue}if(a&&i&&i!==a){De("establish:server-id-mismatch",{url:l});continue}return{kind:"direct",url:l,...i?{serverId:i}:{}}}return null},$l=t=>[...t].sort((s,a)=>{const n=(s.priority??100)-(a.priority??100);if(n!==0)return n;const r=l=>l.type==="relay"?2:l.url.startsWith("https://")?0:1;return r(s)-r(a)}).flatMap(s=>{if(s.type==="relay"){const a=on({relayUrl:s.relayUrl,serverId:s.serverId,hostEncPubJwk:s.hostEncPubJwk});return a?[{kind:"relay",relay:a}]:[]}return rn(s.url)}),Gr=async(t,s)=>{if(!ts())return Hr(t,s);const a=await wt(s?.fast?_r:as,Te("/auth/session").then(r=>r).catch(()=>null));if(!a||!a.ok&&a.status!==404)return!1;const n=await ia(a);return!(n&&n.disabled!==!0&&n.authenticated===!1)},Kl=t=>t.kind==="relay"?ts():!ts()&&an(t.url,ot()),oa=()=>{const t=Ve();return t?Tt().find(s=>Re(s)===t)??null:null},Os=t=>{const s=Ve();return!!s&&Re(t)===s},pn=t=>({generation:bs(),runtimeKey:Ve(),apiBaseUrl:ot(),connectionId:t.id,secureKey:Re(t),candidatesJson:JSON.stringify(t.candidates.map(js))}),qr=t=>{if(bs()!==t.generation||Ve()!==t.runtimeKey||ot()!==t.apiBaseUrl)return!0;const s=oa();if(!s||s.id!==t.connectionId||Re(s)!==t.secureKey)return!0;try{if(JSON.stringify(s.candidates.map(js))!==t.candidatesJson)return!0}catch{return!0}return!1},Js=t=>{try{t?.kind==="relay"&&t.tunnel?.close()}catch{}},Ua=t=>{t.status==="ok"&&Js(t.transport)},Vl=t=>t?`${t.generation}|${t.runtimeKey}|${t.apiBaseUrl}|${t.connectionId}|${t.secureKey}|${t.candidatesJson}`:`noselection|${bs()}|${Ve()}`;let _t=null,Fa="";const Un=(t,s)=>{const a=s.finally(()=>{_t===a&&(_t=null,Fa="")});return _t=a,Fa=t,a},Ia=async()=>{const t=await Wl();return dr("reprobe",{code:t}),t},Qr=()=>{const t=oa(),s=t?pn(t):null,a=Vl(s);if(_t&&Fa===a)return _t;if(_t){const r=_t.then(()=>Ia(),()=>Ia());return Un(a,r)}return Un(a,Ia())},Wl=async()=>{const t=oa();if(!t)return"no-connection";const s=pn(t),a=()=>qr(s);let n;if(Ee()){if(t.hasToken){const m=await Ns(Re(t));if(m.status==="present")n=m.token;else return a()?"no-connection":m.status==="absent"?"needs-login":"unreachable"}if(a())return"no-connection"}else n=t.clientToken;if(!n)return"unreachable";if(a())return"no-connection";const r=t.candidates.findIndex(m=>Kl(m.kind==="relay"?{kind:"relay",relay:m.relay}:{kind:"direct",url:m.url})),l=r>=0?t.candidates.slice(0,r):t.candidates,d=await Qs(l,n,{fast:!0,shouldAbort:a,pinnedServerId:t.pinnedServerId});if(a())return Ua(d),"no-connection";if(d.status==="ok")return await Cs({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&d.serverId?{pinnedServerId:d.serverId}:{}}),a()?(Js(d.transport),"no-connection"):(Dt(d.transport,n,{runtimeKey:Re(t)}),"switched");if(d.status==="needs-login")return"needs-login";if(r>=0){if(a())return"no-connection";const m=await Gr({url:s.apiBaseUrl,clientToken:n},{fast:!0});if(a())return"no-connection";if(m)return Yr(),"unchanged"}const i=r>=0?t.candidates.slice(r+1):[];if(i.length===0)return"unreachable";const u=await Qs(i,n,{fast:!0,shouldAbort:a,pinnedServerId:t.pinnedServerId});return a()?(Ua(u),"no-connection"):u.status==="ok"?(await Cs({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&u.serverId?{pinnedServerId:u.serverId}:{}}),a()?(Js(u.transport),"no-connection"):(Dt(u.transport,n,{runtimeKey:Re(t)}),"switched")):u.status==="needs-login"?"needs-login":"unreachable"};let Ea=!1;const Jr=async()=>{if(Ea)return"skipped";const t=oa();if(!t)return De("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const s=Bt(t);if(!s)return De("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const a=pn(t),n=()=>qr(a);Ea=!0;try{const r=await wt(as,Te("/api/client-auth/connection/candidates").then(c=>c).catch(()=>null));if(!r?.ok)return De("candidates:refresh-skip",{reason:"fetch-failed",status:r?.status??null}),"skipped";if(n())return De("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const l=await r.json().catch(()=>null);if(!l||l.serverId!==s.serverId)return De("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const d=Array.isArray(l.candidates)?l.candidates:[],i=[],u=[];for(const c of d){if(!c||typeof c!="object")continue;const f=c;if(!(f.type!=="lan"&&f.type!=="tailscale"||typeof f.url!="string"))try{const y=Vt(f.url),b=f.type==="tailscale"?u:i;y&&!b.includes(y)&&b.push(y)}catch{}}if(i.length===0&&u.length===0)return De("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const m=ws(t).filter(c=>c.url.startsWith("https://")),p=[...i.map(c=>({kind:"direct",url:c})),...u.filter(c=>!i.includes(c)).map(c=>({kind:"direct",url:c})),...m.filter(c=>![...i,...u].includes(c.url)),{kind:"relay",relay:s}];return JSON.stringify(t.candidates.map(js))===JSON.stringify(p.map(js))?"unchanged":n()?(De("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(De("candidates:refreshed",{lanCount:i.length}),await Cs({id:t.id,label:t.label,candidates:p}),"updated")}finally{Ea=!1}},Yr=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const t=await Jr().catch(()=>"skipped");De("candidates:refresh-result",{result:t}),t==="updated"&&ts()&&await Qr().catch(()=>null)})()},Sl)},Xr=t=>{const[s,a]=o.useState(()=>Tt()),[n,r]=o.useState(null),[l,d]=o.useState(null),[i,u]=o.useState(null),m=o.useRef(s),p=o.useRef(null),h=o.useRef(zr()),c=o.useCallback(g=>{m.current=g,a(g)},[]),f=o.useCallback(g=>{p.current=g,r(g)},[]),y=o.useCallback(g=>{p.current===g&&(p.current=null,r(null))},[]);o.useEffect(()=>{let g=!1;return Kr().then(C=>{g||c(C)}),()=>{g=!0}},[c]);const b=o.useCallback(g=>{const C=Or(m.current,g);return c(C),ln(C),C},[c]),v=o.useCallback(async g=>{d(null),f("connect");try{const C=zn(g);if(C.length===0){d("Enter a server URL.");return}const w=g.id?m.current.find(_=>_.id===g.id):m.current.find(_=>vs(_.candidates,C)),x=g.label?.trim()||w?.label||xs(Ut({candidates:C})),N=g.relayGrant;let k=g.clientToken?.trim()||void 0;const I=!!k;if(!k)if(Ee()){if(w?.hasToken){const _=await Ns(Re({candidates:C}));if(_.status==="present")k=_.token;else if(_.status==="failure"){d("Could not read saved credentials. Please try again.");return}}}else k=w?.clientToken;De("connect:start",{candidates:C.map(_=>_.kind),hasToken:!!k});const S=await Qs(C,k,{pinnedServerId:w?.pinnedServerId});if(De("connect:probe",{status:S.status}),S.status==="unreachable"){S.reason==="wrong-server"?d("That address belongs to a different server. Check the address or re-pair."):d("Could not reach that PiChamber server.");return}if(S.status==="needs-login"){b({id:w?.id,label:x,candidates:C}),u({id:w?.id??$s(),label:x,candidates:C,relay:Bt({candidates:C})??void 0,relayGrant:N,...w?.pinnedServerId?{pinnedServerId:w.pinnedServerId}:{}});return}const z=!w?.pinnedServerId&&S.serverId?S.serverId:void 0;k&&I&&Ee()&&await Lt(Re({candidates:C}),k),b({id:w?.id,label:x,candidates:C,clientToken:k,...z?{pinnedServerId:z}:{}}),Dt(S.transport,k??null,{runtimeKey:Re({candidates:C}),grant:N}),t()}catch(C){console.warn("[mobile-connect] connect threw",C),d("That server URL is not valid.")}finally{y("connect")}},[f,y,t,b]),L=o.useCallback(async g=>{if(p.current==="pairing")return;d(null),f("pairing");const C=$l(g.candidates),w=m.current.find(k=>vs(k.candidates,C));let x=null,N=!1;try{if(x=await On(C,w?.pinnedServerId),!x){d("Could not reach that PiChamber server.");return}const k=JSON.stringify({pairingId:g.pairingId,secret:g.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:_n(),dedupeKey:Dn()}),I={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:k},S=x.kind==="relay"?await wt(as,x.tunnel.fetch("/api/client-auth/pairing/redeem",I).catch(()=>null)):await $t(`${x.url}/api/client-auth/pairing/redeem`,I);if(!S?.ok){d("This server needs a password or client token.");return}const z=await S.json().catch(()=>null),_=typeof z?.clientToken=="string"?z.clientToken.trim():"";if(!_){d("This server needs a password or client token.");return}const O=typeof z?.server?.label=="string"?z.server.label:"",V=g.label||O||xs(Ut({candidates:C}));if(Ee()&&!await Lt(Re({candidates:C}),_)){d("This server needs a password or client token.");return}b({id:w?.id,label:V,candidates:C,clientToken:_,...!w?.pinnedServerId&&x.kind==="direct"&&x.serverId?{pinnedServerId:x.serverId}:{}}),Dt(x.kind==="relay"?{kind:"relay",relay:x.relay,tunnel:x.tunnel}:{kind:"direct",url:x.url},_,{runtimeKey:Re({candidates:C})}),N=x.kind==="relay",t()}catch(k){console.warn("[mobile-connect] pairing threw",k),d("This server needs a password or client token.")}finally{!N&&x?.kind==="relay"&&x.tunnel.close(),y("pairing")}},[f,y,t,b]),j=o.useCallback(async g=>{if(!i||!g.trim()||p.current==="password")return;d(null),f("password");const C=h.current.begin(),w=()=>h.current.isCurrent(C),{id:x,label:N,candidates:k}=i,I=i.pinnedServerId;let S=null,z=!1;try{if(S=await On(k,I),!w())return;if(!S){d("Could not reach that PiChamber server.");return}const _={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:g,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:_n(),dedupeKey:Dn()})};De("password:start",{transport:S.kind});const O=S.kind==="relay"?await wt(as,S.tunnel.fetch("/auth/session",_).catch(()=>null)):await $t(`${S.url}/auth/session`,_);if(!w())return;if(De("password:done",{ok:O?.ok===!0,status:O?.status??null}),!O?.ok){d("Could not unlock that server. Check the password.");return}const V=await O.json().catch(()=>null);if(!w())return;const K=typeof V?.clientToken=="string"?V.clientToken.trim():"";if(De("password:token",{issued:!!K}),!K){if(S.kind==="direct"&&!Ee()){b({id:x,label:N,candidates:k}),u(null),Dt({kind:"direct",url:S.url},null,{runtimeKey:Re({candidates:k})}),t();return}d("This server needs a password or client token.");return}if(Ee()&&(!w()||(await Lt(Re({candidates:k}),K),!w()))||!w()||(b({id:x,label:N,candidates:k,clientToken:K,...!I&&S.kind==="direct"&&S.serverId?{pinnedServerId:S.serverId}:{}}),u(null),Dt(S.kind==="relay"?{kind:"relay",relay:S.relay,tunnel:S.tunnel}:{kind:"direct",url:S.url},K,{runtimeKey:Re({candidates:k})}),z=S.kind==="relay",!w()))return;t()}catch(_){if(!w())return;console.warn("[mobile-connect] password threw",_),d("Could not unlock that server. Check the password.")}finally{!z&&S?.kind==="relay"&&S.tunnel.close(),w()&&y("password")}},[f,y,t,i,b]),T=o.useCallback(()=>{h.current.cancel(),y("password"),u(null),d(null)},[y]),P=o.useCallback(async g=>{d(null);let C=zn(g);const w=g.id?m.current.find(O=>O.id===g.id)??null:null;if(w){const O=C.filter(Z=>Z.kind==="direct"),V=ws(w).filter(Z=>Z.url.startsWith("https://")&&!O.some(ae=>an(ae.url,Z.url))),K=Bt(w);C=[...O,...V,...K?[{kind:"relay",relay:K}]:[]]}if(C.length===0)return d("Enter a server URL."),null;const x=new Set((w?ws(w):[]).map(O=>yt(O.url))),N=new Set(C.filter(O=>O.kind==="direct").map(O=>yt(O.url))),k=x.size!==N.size||[...N].some(O=>!x.has(O)),I=w&&!k?void 0:null,S=g.clientToken?.trim()||void 0,z=g.label?.trim()||xs(Ut({candidates:C}));if(Ee()){const O=Re({candidates:C});if(S)await Lt(O,S);else if(w?.hasToken){const V=Re(w);if(V&&O&&V!==O){const K=await Ns(V);K.status==="present"&&await Lt(O,K.token)}}}return b({id:g.id,label:z,candidates:C,clientToken:S,pinnedServerId:I}).find(O=>vs(O.candidates,C))??null},[b]),A=o.useCallback(async g=>{const C=m.current.find(x=>x.id===g)??null,w=await Vr(g);return c(w),C},[c]);return{connections:s,isBusy:n!==null,isPasswordBusy:n==="password",error:l,pendingConnection:i,connect:v,redeemPairingConnection:L,submitPassword:j,cancelPassword:T,saveConnection:P,removeConnection:A,setError:d}},Hl=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:Bl,connectionDisplayUrl:Ut,createMobilePasswordOperationTracker:zr,deleteMobileConnection:Vr,getAutoConnectTargetLabel:Fl,getConnectionLabel:xs,isActiveRuntimeConnection:Os,isSameConnectionUrl:an,loadMobileConnections:Kr,migrateLegacyInlineTokenRecords:Br,normalizeConnectionUrl:Vt,refreshActiveConnectionCandidates:Jr,relayConnectionRuntimeKey:nn,reprobeActiveConnection:Qr,upsertMobileConnection:Cs,useMobileConnection:Xr,validateActiveRuntimeSession:Gr,validateMobileConnectionSession:Hr},Symbol.toStringTag,{value:"Module"})),Zr=()=>{if(typeof window>"u")return null;const s=window.Capacitor?.Plugins?.BarcodeScanner;return s&&(typeof s.scan=="function"||typeof s.startScan=="function")?s:null},ei=()=>window.Capacitor?.getPlatform?.()==="android",ti=t=>{const s=t.trim();if(!s)return null;if(/^pichamber:\/\//i.test(s)){const a=Bi(s);return a?{pairing:a}:null}return/^https?:\/\//i.test(s)?{url:s}:null},si=(t,s)=>{const a=ti(t);if(!a&&s?.pairingStringFallback){const n=$i(t);if(n)return{status:"pairing",pairing:n}}return a?"pairing"in a?{status:"pairing",...a}:{status:"ok",...a}:{status:"invalid"}},Gl=async(t,s)=>{if(!t.startScan||!t.stopScan||!t.addListener)return{status:"unsupported"};if(s?.aborted)return{status:"cancelled"};let a,n,r=!1,l=()=>{};const d=new Promise(m=>{l=m}),i=m=>{r||(r=!0,l(m))},u=()=>i({status:"cancelled"});s?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(t.addListener("barcodesScanned",({barcodes:p})=>{const h=p?.[0],c=(h?.rawValue??h?.displayValue??"").trim();c&&i(si(c,{pairingStringFallback:!0}))})).then(p=>{a=p}),Promise.resolve(t.addListener("scanError",()=>i({status:"failed"}))).then(p=>{n=p})])).some(({status:p})=>p==="rejected")?i({status:"failed"}):r||t.startScan({formats:["QR_CODE"]}).catch(()=>i({status:"failed"})),await d}finally{s?.removeEventListener("abort",u),await Promise.allSettled([Promise.resolve(a?.remove()),Promise.resolve(n?.remove()),t.stopScan()]),await ai()}},Fn=t=>{const s=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/);if(!s||s[4]!==void 0&&parseFloat(s[4])===0)return null;const a=parseInt(s[1],10).toString(16).padStart(2,"0"),n=parseInt(s[2],10).toString(16).padStart(2,"0"),r=parseInt(s[3],10).toString(16).padStart(2,"0");return`#${a}${n}${r}`},ql=()=>typeof window>"u"||typeof window.getComputedStyle!="function"?null:Fn(window.getComputedStyle(document.documentElement).backgroundColor)??(document.body?Fn(window.getComputedStyle(document.body).backgroundColor):null),ai=async()=>{if(!ei())return;const t=ql();if(!t)return;const{setNativeWebViewBackground:s}=await Ot(()=>import("./nativeFileSave-Bhafll_7.js"),__vite__mapDeps([3,0,1,2,4,5,6,7,8,9])).catch(()=>({setNativeWebViewBackground:void 0}));await s?.(t)},Ql=()=>Zr()!==null,Jl=async t=>{const s=Zr();if(!s)return{status:"unsupported"};try{if(s.requestPermissions){const d=(await s.requestPermissions())?.camera;if(d&&d!=="granted"&&d!=="limited")return{status:"permission-denied"}}if(t?.signal?.aborted)return{status:"cancelled"};if(ei())return Gl(s,t?.signal);if(!s.scan)return{status:"unsupported"};const n=(await s.scan({formats:["QR_CODE"]}))?.barcodes?.[0],r=(n?.rawValue??n?.displayValue??"").trim();return r?si(r):{status:"cancelled"}}catch{return{status:"failed"}}},Yl=t=>{switch(t.kind){case"connected":return{status:"ok",latencyMs:0};case"needs-login":return{status:"auth",latencyMs:0};case"unreachable":return{status:"unreachable",latencyMs:0};case"connecting":case"unknown":return null}},Xl=(t,s)=>{const a=Yl(s.status),n=Co(a,s.probing===!0),r=[];for(const i of t.candidates){if(i.kind==="relay"){r.some(m=>m.kind==="relay")||r.push({kind:"relay",label:In.relay,address:null});continue}const u=So(i.url);r.some(m=>m.kind===u)||r.push({kind:u,label:In[u],address:i.url})}let l=null;s.isCurrent&&s.status.kind==="connected"&&(l=s.status.transport==="relay"?r.find(i=>i.kind==="relay")??null:r.find(i=>i.kind!=="relay")??null);const d=r.some(i=>i.kind!=="relay");return{id:t.id,label:t.label,isCurrent:s.isCurrent,isDefault:!1,isLocal:!1,routes:r,activeRoute:l,status:n.status,latencyMs:s.status.kind==="connected"?s.status.latencyMs??null:n.latencyMs,canEdit:d,canRemove:!0,canOpenInNewWindow:!1}},Aa={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Zl="h-12 w-full rounded-[16px] border border-border/70 bg-surface-elevated px-4 text-[16px] text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20",ec=({onCancel:t})=>{const s=o.useRef(null);return gr(o.useCallback(()=>(t(),!0),[t])),o.useLayoutEffect(()=>{const a={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},n={value:document.body.style.getPropertyValue("background-color"),priority:document.body.style.getPropertyPriority("background-color")};document.documentElement.style.setProperty("background-color","rgba(0, 0, 0, 0)","important"),document.body.style.setProperty("background-color","rgba(0, 0, 0, 0)","important");const r=new Map,l=i=>{!(i instanceof HTMLElement)||i===s.current||r.has(i)||(r.set(i,{opacity:i.style.opacity,pointerEvents:i.style.pointerEvents}),i.style.setProperty("opacity","0"),i.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(l);const d=new MutationObserver(i=>{i.forEach(u=>u.addedNodes.forEach(l))});return d.observe(document.body,{childList:!0}),()=>{d.disconnect(),r.forEach((i,u)=>{u.style.opacity=i.opacity,u.style.pointerEvents=i.pointerEvents}),a.value?document.documentElement.style.setProperty("background-color",a.value,a.priority):document.documentElement.style.removeProperty("background-color"),n.value?document.body.style.setProperty("background-color",n.value,n.priority):document.body.style.removeProperty("background-color"),ai()}},[]),o.useEffect(()=>{const a=()=>{document.visibilityState==="hidden"&&t()};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},[t]),cr.createPortal(e.jsxs("div",{ref:s,role:"dialog","aria-modal":"true","aria-label":"Scan QR code",className:"fixed inset-0 z-[1000] flex flex-col bg-transparent px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+24px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+24px)] text-foreground",children:[e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[e.jsx("div",{className:"aspect-square w-full max-w-72 rounded-[28px] border-2 border-foreground/90 shadow-[0_0_0_9999px_color-mix(in_srgb,var(--surface-background)_18%,transparent)]","aria-hidden":!0}),e.jsx("p",{className:"max-w-sm rounded-[16px] border border-border/60 bg-background px-4 py-3 text-center typography-body text-foreground shadow-sm",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}),e.jsxs(E,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:t,children:[e.jsx(R,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},tc=()=>cr.createPortal(e.jsxs("div",{role:"status",className:"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-5 bg-background px-6 text-foreground",children:[e.jsx(xr,{width:96,height:96,isAnimated:!0}),e.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[e.jsx(R,{name:"loader-4",className:"size-[18px] animate-spin"}),e.jsx("span",{children:"Connecting..."})]})]}),document.body),Bn=({className:t})=>{const[s,a]=o.useState(null);o.useEffect(()=>{let r=!1;const l=typeof AbortController<"u"?new AbortController:void 0;return(async()=>{try{const i=await Te("/api/system/info",{signal:l?.signal,headers:{Accept:"application/json"}});if(!i.ok)return;const u=await i.json().catch(()=>null);if(!u||r)return;const m=typeof u.port=="number"&&Number.isFinite(u.port)&&u.port>0?u.port:null,p=typeof u.tunnelUrl=="string"&&u.tunnelUrl.trim().length>0?u.tunnelUrl.trim():null;a({port:m,tunnelUrl:p})}catch{}})(),()=>{r=!0,l?.abort()}},[]);const n=[];return s?.port!==null&&s?.port!==void 0&&n.push({key:"application",label:"Application",url:`http://localhost:${s.port}/`}),s?.tunnelUrl&&n.push({key:"tunnel",label:"Tunnel",url:s.tunnelUrl}),n.length===0?null:e.jsx("div",{className:H("flex flex-wrap items-center gap-2",t),children:n.map(r=>e.jsxs(E,{type:"button",variant:"outline",size:"sm",title:r.label,className:"max-w-full gap-1.5 px-2.5",onClick:()=>{fs(r.url)},children:[e.jsx(R,{name:"external-link",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"max-w-64 truncate font-mono typography-micro",children:r.url})]},r.key))})},Us=t=>t==="rc"?"rc":"stable",Ma={stable:"Stable",rc:"Release candidate"},$n=()=>{const t=ot().trim();return t?mr(t):"Server"},Kn=({channel:t,disabled:s,label:a,onChange:n})=>e.jsxs(_e,{value:t,onValueChange:n,disabled:s,children:[e.jsx(ze,{size:Be,className:ra,"aria-label":a,children:e.jsx(Oe,{children:r=>Ma[Us(r)]})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"stable",children:Ma.stable}),e.jsx(ye,{value:"rc",children:Ma.rc})]})]}),sc=()=>{const t=Le(),[s,a]=o.useState(0),n=t&&Kt(),[r,l]=o.useState($n),d=`Server update channel (${r})`,[i,u]=o.useState("stable"),[m,p]=o.useState("stable"),[h,c]=o.useState(t),[f,y]=o.useState(t&&!n),[b,v]=o.useState(!1),[L,j]=o.useState(!1),[T,P]=o.useState(null),[A,g]=o.useState(null),C=o.useRef(0);if(o.useEffect(()=>ea(()=>{C.current+=1,a(N=>N+1)}),[]),o.useEffect(()=>{if(!t||n)return;let N=!1;const k=$n();return l(k),pr().then(I=>{if(N)return;const S=Gi(),z=Ki([Vi(S),...I.hosts]),_=z.id===Wi||z.id==="custom"?"":z.label.trim();l(mr(_||k))}).catch(()=>{N||l(k)}),()=>{N=!0}},[t,n,s]),o.useEffect(()=>{if(!t)return;let N=!1;return c(!0),Hi().then(k=>{N||(u(k),P(null))}).catch(k=>{N||P(k instanceof Error?k.message:"Unable to load the desktop update channel.")}).finally(()=>{N||c(!1)}),()=>{N=!0}},[t]),o.useEffect(()=>{const N=++C.current;if(!t||n){y(!1),g(null);return}y(!0),j(!1),(async()=>{try{const k=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!k.ok)throw new Error("Unable to load the server update channel.");const I=await k.json().catch(()=>null);if(!I)throw new Error("Unable to load the server update channel.");C.current===N&&(p(Us(I.serverUpdateChannel)),g(null))}catch(k){C.current===N&&g(k instanceof Error?k.message:"Unable to load the server update channel.")}finally{C.current===N&&y(!1)}})()},[t,n,s]),!t)return null;const w=N=>{const k=Us(N),I=i;u(k),v(!0),P(null),qi(k).then(S=>{u(S),Ks.getState().reset(),Ks.getState().checkForUpdates()}).catch(S=>{u(I),P(S instanceof Error?S.message:"Unable to save the desktop update channel.")}).finally(()=>v(!1))},x=N=>{const k=Us(N),I=m,S=++C.current;p(k),j(!0),g(null),(async()=>{try{await Ke({serverUpdateChannel:k},{immediate:!0});const z=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error("Unable to save the server update channel.");if((await z.json().catch(()=>null))?.serverUpdateChannel!==k)throw new Error("Unable to save the server update channel.");C.current===S&&el()}catch(z){C.current===S&&(p(I),g(z instanceof Error?z.message:"Unable to save the server update channel."))}finally{C.current===S&&j(!1)}})()};return e.jsxs(Y,{title:"Updates",children:[e.jsx(Pe,{label:"Desktop app update channel",info:"Stable receives production desktop releases only. Release candidate offers the highest available version across stable and desktop RC builds. Switching to Stable changes future update eligibility and does not downgrade an installed RC.",description:T?e.jsx("span",{className:"text-[var(--status-error)]",children:T}):void 0,settingsItem:"about.desktop-update-channel",labelClassName:"@xl:w-auto",controlClassName:"@xl:flex-1",children:e.jsx(Kn,{channel:i,disabled:h||b,label:"Desktop app update channel",onChange:w})}),!n&&e.jsx(Pe,{label:e.jsxs("span",{className:"@xl:whitespace-nowrap",children:["Server update channel ",e.jsxs("span",{className:"font-normal text-muted-foreground",children:["· ",r]})]}),info:"Stable receives production server releases only. Release candidate offers the highest available version across stable and server RC builds. Switching to Stable changes future update eligibility and does not downgrade an installed RC.",description:A?e.jsx("span",{className:"text-[var(--status-error)]",children:A}):void 0,settingsItem:"about.server-update-channel",labelClassName:"@xl:w-auto",controlClassName:"@xl:flex-1",children:e.jsx(Kn,{channel:m,disabled:f||L,label:d,onChange:x})})]})},Ba="https://github.com/RyderAsKing/PiChamber",$a="https://pi.dev/",ac=800,ni=({initialUpdateDialogOpen:t=!1})=>{const[s,a]=o.useState(t?"client":null),[n,r]=o.useState(!1),[l,d]=o.useState(null),i=Ks(Ui(g=>({info:g.info,serverInfo:g.serverInfo,checking:g.checking,available:g.available,error:g.error,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,runtimeType:g.runtimeType,lastChecked:g.lastChecked,checkForUpdates:g.checkForUpdates,downloadUpdate:g.downloadUpdate,restartToUpdate:g.restartToUpdate}))),{isMobile:u}=Ze(),m=Qi()&&!Kt(),p=o.useMemo(()=>Ee(),[]),h=m||p,c=l||i.info?.currentVersion||"unknown",f=i.info?.currentVersion||"1.0.6-rc.2",y=i.serverInfo?.currentVersion||l||"unknown",b=i.available,v=h&&(i.serverInfo?.available??!1),L=b||v,j=s==="server"?i.serverInfo:i.info,T=s==="server"?"web":i.runtimeType;o.useEffect(()=>{let g=!1;return(async()=>{try{const w=await Te("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!w.ok)return;const x=await w.json().catch(()=>null),N=typeof x?.pichamberVersion=="string"&&x.pichamberVersion.trim().length>0?x.pichamberVersion.trim():null;g||d(N)}catch{g||d(null)}})(),()=>{g=!0}},[]);const P=o.useRef(!1);o.useEffect(()=>{if(i.checking)r(!0),P.current=!0;else if(n){const g=setTimeout(()=>{if(r(!1),P.current){const{info:C,serverInfo:w}=Ks.getState(),x=C!==null&&(!h||w!==null);!L&&!i.error&&x&&$.success("You are on the latest version"),P.current=!1}},ac);return()=>clearTimeout(g)}},[i.checking,n,L,i.error,h]);const A=i.checking||n;return u?e.jsxs("div",{className:"w-full space-y-6 pb-2",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx(xr,{width:72,height:72}),e.jsx("h2",{className:`mt-4 ${tl}`,children:"PiChamber"}),e.jsx(Bn,{className:"mt-3 justify-center"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-border/40 overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ms,{label:"Client",version:f,updateInfo:i.info,checked:i.lastChecked!==null,checking:A,onOpen:()=>a("client")}),e.jsx(Ms,{label:"Server",version:y,updateInfo:i.serverInfo,checked:i.lastChecked!==null,checking:A,onOpen:()=>a("server")})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{label:"Client",version:"1.0.6-rc.2",updateInfo:null,note:"Updates with server",checked:!1,checking:!1,onOpen:()=>{}}),e.jsx(Ms,{label:"Server",version:i.info?.currentVersion||l||"unknown",updateInfo:i.info,checked:i.lastChecked!==null,checking:A,onOpen:()=>a("client")})]})}),e.jsx("div",{className:"flex justify-center",children:e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:()=>i.checkForUpdates(),disabled:A,className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[A?e.jsx(R,{name:"loader",className:"size-4 animate-spin"}):e.jsx(R,{name:"refresh",className:"size-4"}),A?"Checking...":"Check for updates"]})})]}),i.error&&e.jsx("p",{className:"rounded-xl border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-meta text-[var(--status-error)]",children:i.error}),e.jsx("div",{className:"flex flex-col items-center gap-3 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-5",children:[e.jsxs("a",{href:Ba,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(R,{name:"github-fill",className:"size-5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:$a,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(R,{name:"information",className:"size-5"}),e.jsx("span",{children:"Pi Agent"})]})]})}),e.jsx(Wn,{}),e.jsx("p",{className:"text-center typography-ui text-muted-foreground/60",children:"Made with care for the community"}),e.jsx(An,{open:s!==null,onOpenChange:g=>{g||a(null)},info:j,downloading:i.downloading,downloaded:i.downloaded,progress:i.progress,error:i.error,onDownload:i.downloadUpdate,onRestart:i.restartToUpdate,runtimeType:T})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Y,{divider:!1,children:[e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex flex-col @xl:flex-row @xl:items-center justify-between gap-4 px-4 py-3 border-b border-border/40",children:[e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:Ae,children:"Version"}),m?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(Vn,{label:"Client",version:f,updateInfo:i.info,onOpen:()=>a("client")}),e.jsx("span",{className:"text-muted-foreground/60","aria-hidden":"true",children:"·"}),e.jsx(Vn,{label:"Server",version:y,updateInfo:i.serverInfo,onOpen:()=>a("server")})]}):e.jsx("span",{className:"typography-meta text-muted-foreground font-mono",children:c})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[i.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!i.checking&&!m&&i.available&&e.jsxs(E,{size:"sm",variant:"default",onClick:()=>a("client"),children:[e.jsx(R,{name:"download",className:"h-4 w-4 mr-1"}),`Update to ${i.info?.version||""}`]}),!i.checking&&m&&L&&e.jsx("span",{className:"typography-meta text-[var(--primary-base)]",children:"Updates available"}),!i.checking&&!L&&!i.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>i.checkForUpdates(),disabled:i.checking,children:"Check for updates"})]})]}),i.error&&e.jsx("div",{className:"px-3 py-2 border-b border-border/40",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:i.error})}),e.jsxs("div",{className:"flex flex-col gap-2 border-b border-border/40 px-4 py-3 @xl:flex-row @xl:items-center @xl:justify-between",children:[e.jsx("span",{className:Ae,children:"Instance URLs"}),e.jsx(Bn,{})]}),e.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[e.jsxs("a",{href:Ba,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground typography-meta transition-colors",children:[e.jsx(R,{name:"github-fill",className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:$a,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground typography-meta transition-colors",children:[e.jsx(R,{name:"information",className:"h-4 w-4"}),e.jsx("span",{children:"Pi Agent"})]})]})]}),e.jsx(An,{open:s!==null,onOpenChange:g=>{g||a(null)},info:j,downloading:s==="client"&&i.downloading,downloaded:s==="client"&&i.downloaded,progress:s==="client"?i.progress:null,error:i.error,onDownload:i.downloadUpdate,onRestart:i.restartToUpdate,runtimeType:T})]}),e.jsx(sc,{}),e.jsx(Wn,{})]})},Vn=({label:t,version:s,updateInfo:a,onOpen:n})=>{if(!a?.available)return e.jsx("span",{className:"font-mono",children:`${t} ${s}`});const r=`Open ${t.toLowerCase()} updater${a.version?` for ${a.version}`:""}`;return e.jsxs(E,{variant:"ghost",size:"xs",onClick:n,className:"normal-case font-mono text-[var(--primary-base)]","aria-label":r,title:r,children:[e.jsx("span",{children:`${t} ${s}`}),e.jsx(R,{name:"arrow-up",className:"size-3.5","aria-hidden":"true"})]})},Ms=({label:t,version:s,updateInfo:a,note:n,checked:r,checking:l,onOpen:d})=>{let i=null;return n?i=e.jsx("span",{className:"typography-meta text-muted-foreground",children:n}):a?.available?i=e.jsxs(E,{type:"button",variant:"default",size:"sm",onClick:d,"aria-label":`Open ${t.toLowerCase()} updater${a.version?` for ${a.version}`:""}`,children:[e.jsx(R,{name:"download",className:"size-4"}),a.version?`Update to ${a.version}`:"Update"]}):!l&&a?i=e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"}):!l&&r&&(i=e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Couldn't check"})),e.jsxs("div",{className:"flex min-h-12 items-center justify-between gap-3 px-4 py-2",children:[e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx("span",{className:Ae,children:t}),e.jsx("span",{className:"truncate typography-meta font-mono text-muted-foreground",children:s})]}),i?e.jsx("div",{className:"shrink-0",children:i}):null]})},Wn=()=>e.jsxs(e.Fragment,{children:[e.jsx(Y,{title:"What is PiChamber",divider:!1,children:e.jsxs("div",{className:"max-w-2xl space-y-3 typography-ui text-muted-foreground",children:[e.jsx("p",{children:"PiChamber is an open-source workspace for running and supervising Pi Coding Agent sessions from a desktop app or browser."}),e.jsx("p",{children:"It keeps the Pi session daemon on your host while giving trusted devices a focused, authenticated interface for creating sessions, following live work, and steering the agent when needed."})]})}),e.jsx(Y,{title:"Our goals",children:e.jsxs("ul",{className:"max-w-2xl list-disc space-y-2 pl-5 typography-ui text-muted-foreground",children:[e.jsx("li",{children:"Make agent-assisted development practical from anywhere you work."}),e.jsx("li",{children:"Keep users in control of sessions, tools, project context, and credentials."}),e.jsx("li",{children:"Offer a calm, responsive interface for both focused coding and supervision."}),e.jsx("li",{children:"Stay open, self-hostable, and respectful of the systems where Pi runs."})]})}),e.jsx(Y,{title:"Built around Pi",children:e.jsxs("div",{className:"max-w-2xl space-y-3 typography-ui text-muted-foreground",children:[e.jsx("p",{children:"Pi is the coding agent and session engine underneath PiChamber. It is designed for working with your tools and code directly, and PiChamber adds the multi-device workspace around that experience."}),e.jsxs("p",{children:["Learn more about Pi Coding Agent at"," ",e.jsx("a",{href:$a,target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline underline-offset-4 hover:text-primary",children:"pi.dev"}),"."]})]})}),e.jsx(Y,{title:"Special thanks",children:e.jsxs("div",{className:"max-w-2xl space-y-3 typography-ui text-muted-foreground",children:[e.jsxs("p",{children:["PiChamber is a community fork of"," ",e.jsx("a",{href:"https://github.com/openchamber/openchamber",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline underline-offset-4 hover:text-primary",children:"OpenChamber"})," ","by Bohdan Triapitsyn. We are grateful for the foundation and the required MIT attribution carried forward from that project."]}),e.jsx("p",{children:"Thank you to Pierre, the Pi community, xterm.js, and every contributor whose work, feedback, and ideas help make this project possible."})]})}),e.jsx(Y,{title:"Links and license",children:e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 typography-ui-label",children:[e.jsx("a",{href:Ba,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground transition-colors hover:text-foreground",children:"PiChamber on GitHub"}),e.jsx("a",{href:"https://github.com/RyderAsKing/PiChamber/blob/main/LICENSE",target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground transition-colors hover:text-foreground",children:"MIT license"})]})})]}),nc=({onResolved:t})=>{const[s,a]=o.useState(!1),[n,r]=o.useState(!1);o.useEffect(()=>{let d=!0;return Me.getSettings({runtimeKey:Ve()}).then(i=>{d&&a(i.pi.project.requiresTrust===!0)}).catch(()=>{}),()=>{d=!1}},[]);const l=async d=>{r(!0);try{const i=await Me.setPiSettings({scope:"project",trust:d},{runtimeKey:Ve()});a(!1),sa(i)&&$.info(Xt("Project trust")),t?.()}catch(i){const u=i instanceof Error&&i.message?i.message:"Failed to update project trust";Za(i)?$.info(Zt("Project trust")):$.error(u)}finally{r(!1)}};return e.jsx(jt,{open:s,onOpenChange:()=>{},children:e.jsxs(kt,{className:"max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Trust this project?"}),e.jsx(St,{children:"This project contains Pi settings, skills, prompts, or extensions. Trusting it allows Pi to load those project resources."})]}),e.jsxs(ta,{children:[e.jsx(E,{variant:"ghost",size:"sm",disabled:n,onClick:()=>{l(!1)},children:"Keep untrusted"}),e.jsx(E,{size:"sm",disabled:n,onClick:()=>{l(!0)},children:"Trust project"})]})]})})},we=({children:t,className:s,outerClassName:a,title:n,titleLeading:r,titleAccessory:l,description:d,headerEnd:i})=>{const u=n!=null||d!=null||i!=null,m=typeof n=="string"||typeof n=="number",p=r!=null||l!=null;return e.jsx(To,{outerClassName:H("h-full",a),className:"w-full @container",children:e.jsxs("div",{className:H("mx-auto max-w-[840px] space-y-0 px-6 py-5 @3xl:px-10 @3xl:py-7","[&>section:first-of-type]:border-t-0 [&>section:first-of-type]:pt-0",s),children:[u&&e.jsxs("div",{className:"mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-3 pb-6",children:[n!=null||d!=null?e.jsxs("div",{className:"min-w-0 flex-1 basis-64 space-y-1",children:[n!=null?m?p?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[r,e.jsx("h1",{className:H(Mn,"min-w-0 truncate"),children:n}),e.jsx("span",{className:"shrink-0",children:l})]}):e.jsx("h1",{className:Mn,children:n}):n:null,d!=null?typeof d=="string"||typeof d=="number"?e.jsx("p",{className:sl,children:d}):d:null]}):null,i!=null?e.jsx("div",{className:"flex min-w-0 max-w-full shrink-0 flex-wrap items-center justify-end gap-3 [&>*]:min-w-0 [&>*]:max-w-full",children:i}):null]}),t]})})},la=({value:t,onChange:s,readOnly:a=!1,initialMode:n="preview",placeholder:r="Enter snippet text... Use markdown to format your snippet. It will expand as #name in the composer.",contentLabel:l="Snippet content",settingsItem:d,minHeight:i=220,hideExpandsNote:u=!1,triggerPreview:m,triggerActionLabel:p="Expands as",variableChips:h})=>{const[c,f]=o.useState(()=>a?"preview":n),y=t.trim().length>0;o.useEffect(()=>{a&&c==="write"&&f("preview")},[a,c,y]);const b=c==="write"&&!a,v=o.useRef(null),L=o.useCallback(j=>{const T=v.current?.selectionStart??t.length,P=v.current?.selectionEnd??t.length;s(t.slice(0,T)+j+t.slice(P)),requestAnimationFrame(()=>{const A=v.current;if(!A)return;A.focus();const g=T+j.length;A.setSelectionRange(g,g)})},[s,t]);return e.jsxs("div",{"data-settings-item":d,className:"overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/20 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":c==="preview",onClick:()=>f("preview"),children:[e.jsx(R,{name:"eye",className:"size-3.5","aria-hidden":!0}),"Preview"]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":c==="write",disabled:a,onClick:()=>f("write"),className:H(a&&"opacity-50"),children:[e.jsx(R,{name:"edit",className:"size-3.5","aria-hidden":!0}),"Write"]})]}),a?e.jsx("span",{className:"hidden typography-micro text-muted-foreground @xl:inline",children:"Read-only"}):null]}),b?e.jsxs("div",{className:"p-0",children:[h&&h.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-border/60 bg-muted/20 px-3 py-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Variables"}),h.map(j=>e.jsx(E,{variant:"chip",size:"xs",onClick:()=>L(j.value),"aria-label":j.hint??`Insert ${j.value}`,title:j.hint??j.value,children:e.jsx("span",{className:"font-mono",children:j.label??j.value})},j.value))]}):null,e.jsx(al,{ref:v,value:t,onChange:j=>s(j.target.value),placeholder:r,simple:!0,fillContainer:!1,outerClassName:"border-0 ring-0 rounded-none bg-transparent",className:H("min-h-[220px] w-full bg-transparent px-3 py-3 font-mono typography-meta leading-6","placeholder:text-muted-foreground/70"),style:{minHeight:i},"aria-label":l})]}):e.jsx("div",{className:"min-h-[220px] px-4 py-4 @xl:px-6",style:{minHeight:i},children:y?e.jsx(en,{content:t,className:"max-w-none"}):e.jsxs("div",{className:"flex min-h-[180px] flex-col items-center justify-center gap-2 py-10 text-center",children:[e.jsx(R,{name:"file-text",className:"size-6 text-muted-foreground/50","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:a?"No content":"Nothing to preview"}),a?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Start writing in the Write tab to see a live preview."})]})}),a?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border/40 bg-muted/10 px-3 py-2 typography-micro text-muted-foreground",children:[!u&&m?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(R,{name:"information",className:"size-3.5 shrink-0 opacity-60","aria-hidden":!0}),p," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:m})," in the composer"]}):e.jsx("span",{}),e.jsxs("span",{className:"tabular-nums",children:[t.length," chars"]})]})]})},rc=()=>{const{isMobile:t}=Ze(),[s,a]=o.useState(null),[n,r]=o.useState({}),[l,d]=o.useState(null),[i,u]=o.useState(!1),m=o.useCallback(async()=>{const h=await Me.listResources({runtimeKey:Ve()});a(h.agents),r(Object.fromEntries(h.agents.map(c=>[c.id,c.content??""]))),u(!1)},[]);o.useEffect(()=>{m().catch(()=>u(!0))},[m]);const p=async h=>{d(h.id);try{const c=await Me.updateResource({resourceId:h.id,content:n[h.id]??""},{runtimeKey:Ve()});a(c.agents),r(Object.fromEntries(c.agents.map(f=>[f.id,f.content??""]))),sa(c)?$.info(Xt("Behavior")):$.success("Behavior saved successfully")}catch(c){Za(c)?$.info(Zt("Behavior")):$.error("Failed to save behavior")}finally{d(null)}};return e.jsxs(e.Fragment,{children:[e.jsx(nc,{onResolved:()=>{m().catch(()=>u(!0))}}),e.jsxs(we,{title:t?void 0:"Behavior",description:t?void 0:"Guide how the agent responds.",children:[i?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,(s??[]).map((h,c)=>{const f=n[h.id]??"",y=h.location==="global"?"Global AGENTS.md":`Project ${h.name}`,b=h.editable===!0,v=f!==(h.content??"");return e.jsxs(Y,{title:y,divider:c>0,settingsItem:h.location==="global"?"behavior.global-agents":"behavior.project-agents",contentClassName:"space-y-3",info:b?"Markdown supported. Changes are saved immediately and applied when active sessions are idle.":"Read-only — this file is managed by a package or template.",children:[e.jsx(la,{value:f,onChange:L=>r(j=>({...j,[h.id]:L})),readOnly:!b,placeholder:b?"Describe how the agent should behave. Use markdown for structure.":void 0,settingsItem:h.location==="global"?"behavior.global-agents":"behavior.project-agents",hideExpandsNote:!0,minHeight:260}),b?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:v?"Unsaved changes":"No changes"}),e.jsx(E,{size:"xs",onClick:()=>{p(h)},disabled:l!==null||!v,children:l===h.id?"Saving...":"Save Changes"})]}):null]},h.id)})]})]})},ic=({skill:t,onSelect:s,showLocationPill:a=!0})=>{const n=t.location==="project"?"Project":t.location==="global"?"Global":t.location,r=t.description?.trim()||"No description";return e.jsxs("button",{type:"button",onClick:()=>s(t.name),"aria-label":`${t.name} skill, ${n}`,className:H("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[a?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:H("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 typography-micro font-medium capitalize",t.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:n})}):null,e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:t.name}),e.jsx("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:r})]})]})},oc=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,a)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"h-5 w-16 animate-pulse rounded-full bg-muted"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-full animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-muted"})]})]},a))}),lc=()=>{const{isMobile:t}=Ze(),s=Mt(w=>w.selectedSkillName),a=Mt(w=>w.setSelectedSkill),n=Mt(w=>w.skills),r=Mt(w=>w.isLoading),l=Mt(w=>w.loadSkills),[d,i]=o.useState(""),[u,m]=o.useState("all"),[p,h]=o.useState(!1),c=o.useMemo(()=>n.find(w=>w.name===s)??null,[n,s]),f=Mt(w=>w.updateSkillContent),[y,b]=o.useState(!1),[v,L]=o.useState(""),[j,T]=o.useState(!1);o.useEffect(()=>{c&&L(c.content??""),b(!1)},[c?.id,c?.content]);const P=o.useCallback(async()=>{if(!p){h(!0);try{const{invalidateSkillsLoadCache:w}=await Ot(async()=>{const{invalidateSkillsLoadCache:x}=await import("./useAppFontEffects-D_gtiA95.js").then(N=>N.ek);return{invalidateSkillsLoadCache:x}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));w(),await l()}finally{h(!1)}}},[l,p]);o.useEffect(()=>{l()},[l]);const A=o.useMemo(()=>[...n].sort((w,x)=>{if(w.location!==x.location){if(w.location==="project")return-1;if(x.location==="project")return 1;if(w.location==="global")return-1;if(x.location==="global")return 1}return w.name.localeCompare(x.name,void 0,{sensitivity:"base"})}),[n]),g=o.useMemo(()=>{let w=A;u!=="all"&&(w=w.filter(N=>N.location===u));const x=d.trim().toLowerCase();return x?w.filter(N=>{const k=N.name.toLowerCase(),I=(N.description??"").toLowerCase();return k.includes(x)||I.includes(x)}):w},[A,u,d]),C=o.useMemo(()=>{let w=0,x=0;for(const N of n)N.location==="project"?w+=1:N.location==="global"&&(x+=1);return{all:n.length,project:w,global:x}},[n]);if(c){const w=c.location==="project"?"Project":c.location==="global"?"Global":c.location,x=typeof c.content=="string"&&c.content.trim().length>0,N=c.editable===!0,k=v!==(c.content??""),I=async()=>{if(!N||j)return;T(!0);const z=await f(c.name,v);T(!1),z?($.success("Skill saved"),b(!1)):$.error("Failed to save skill")},S=()=>{L(c.content??""),b(!1)};return e.jsx(e.Fragment,{children:e.jsxs(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>a(null),"aria-label":"Back to skills",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:c.name})]}),description:c.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:c.description}):void 0,headerEnd:N&&!y?e.jsxs(E,{variant:"outline",size:"xs",onClick:()=>b(!0),children:[e.jsx(R,{name:"edit",className:"size-3.5"}),"Edit"]}):void 0,children:[e.jsxs(Y,{title:"Details",divider:!1,settingsItem:"skills.discovery",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 typography-micro",children:[e.jsx("span",{className:"inline-flex items-center rounded-full bg-muted px-2.5 py-1 font-medium capitalize text-muted-foreground",children:w}),N?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-[var(--status-success)]/10 px-2.5 py-1 font-medium text-[var(--status-success)]",children:[e.jsx(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 font-medium text-muted-foreground",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-muted-foreground/60","aria-hidden":!0}),"Read-only"]})]}),N?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"This skill is provided by a package or template and cannot be edited. Create a new skill in your project to customize it."})]}),e.jsxs(Y,{title:"Skill Guide",settingsItem:"skills.content",info:y?"Markdown supported. Preview your changes before saving.":"Rendered from the SKILL.md markdown file discovered by Pi.",headerAction:N&&y?e.jsx("span",{className:"typography-micro text-muted-foreground",children:k?"Unsaved changes":"No changes"}):void 0,children:[y?e.jsxs(e.Fragment,{children:[e.jsx(la,{value:v,onChange:L,placeholder:"Write the skill guide in markdown...",hideExpandsNote:!0,minHeight:360}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:S,disabled:j,children:"Cancel"}),e.jsx(E,{size:"xs",onClick:()=>{I()},disabled:j||!k,children:j?"Saving...":"Save Changes"})]})]}):x?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(en,{content:c.content??"",stripFrontmatter:!0,className:"max-w-none"})}):e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border/60 bg-muted/20 px-4 py-10 text-center",children:[e.jsx(R,{name:"book-open",className:"size-6 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No guide content available for this skill."}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"The daemon did not return markdown for this resource."}),N?e.jsxs(E,{variant:"outline",size:"xs",onClick:()=>b(!0),className:"mt-2",children:[e.jsx(R,{name:"edit",className:"size-3.5"}),"Add content"]}):null]}),N&&!y&&x?e.jsx("div",{className:"flex justify-end pt-3",children:e.jsxs(E,{variant:"outline",size:"xs",onClick:()=>b(!0),children:[e.jsx(R,{name:"edit",className:"size-3.5"}),"Edit"]})}):null]})]})})}return r&&n.length===0?e.jsx(e.Fragment,{children:e.jsx(we,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{P()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:H("size-4",p&&"animate-spin")})})}),children:e.jsx(Y,{title:"Skills",divider:!1,settingsItem:"skills.discovery",children:e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:e.jsx(oc,{count:6})})})})}):g.length===0&&d.trim()===""&&n.length===0?e.jsx(e.Fragment,{children:e.jsx(we,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:d,onChange:w=>i(w.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-full pl-8"}),d?e.jsx("button",{type:"button",onClick:()=>i(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{P()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:H("size-4",p&&"animate-spin")})})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"book-open",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No skills configured"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Skills appear here when Pi discovers SKILL.md files."})]})})}):e.jsx(e.Fragment,{children:e.jsx(we,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:d,onChange:w=>i(w.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-full pl-8"}),d?e.jsx("button",{type:"button",onClick:()=>i(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{P()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:H("size-4",p&&"animate-spin")})})]}),children:e.jsxs(Y,{title:"Skills",divider:!1,settingsItem:"skills.discovery",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":u==="all",onClick:()=>m("all"),children:["All ",C.all]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":u==="project",onClick:()=>m("project"),children:["Project ",C.project]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":u==="global",onClick:()=>m("global"),children:["Global ",C.global]})]}),g.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:d.trim()?`No skills match “${d}”.`:`No ${u} skills.`}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>{i(""),m("all")},children:"Clear filters"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:g.map(w=>e.jsx(ic,{skill:w,onSelect:a,showLocationPill:u==="all"},w.id))})]})})})},cc=({project:t,onSelect:s})=>{const a=t.label?.trim()||t.path.split("/").pop()?.trim()||t.path,n=!!t.label?.trim();return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${a} project, ${t.path}`,className:H("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(vr,{directory:t.path,label:a,className:"size-8"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a}),n?e.jsx("div",{className:"truncate font-mono typography-micro text-muted-foreground",children:t.path}):e.jsx("div",{className:"truncate typography-micro text-muted-foreground",children:t.path})]})]})},dc=()=>{const{isMobile:t}=Ze(),s=Vs(c=>c.projects),a=Vs(c=>c.updateProjectMeta),n=W(c=>c.settingsProjectsSelectedId),r=W(c=>c.setSettingsProjectsSelectedId),[l,d]=o.useState(""),i=o.useCallback(()=>{Po.requestDirectoryDialog()},[]),u=o.useMemo(()=>n?s.find(c=>c.id===n)??null:null,[s,n]);o.useEffect(()=>{n&&!s.some(c=>c.id===n)&&r(null)},[s,n,r]);const m=o.useCallback(async c=>{u&&a(u.id,{label:c.label,defaultModel:c.defaultModel??null})},[u,a]),p=o.useMemo(()=>[...s].sort((c,f)=>{const y=(c.label?.trim()||c.path).toLowerCase(),b=(f.label?.trim()||f.path).toLowerCase();return y.localeCompare(b,void 0,{sensitivity:"base"})}),[s]),h=o.useMemo(()=>{const c=l.trim().toLowerCase();return c?p.filter(f=>{const y=(f.label??"").toLowerCase(),b=f.path.toLowerCase();return y.includes(c)||b.includes(c)}):p},[p,l]);if(u){const c=u.label?.trim()||u.path.split("/").pop()?.trim()||u.path;return e.jsx(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>r(null),"aria-label":"Back to projects",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx(vr,{directory:u.path,label:c,className:"size-5"}),e.jsx("span",{className:"truncate",children:c})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:u.path}),children:e.jsx(nl,{project:u,onIdentitySave:m})})}return s.length===0?e.jsx(we,{title:t?void 0:"Projects",description:t?void 0:"Manage your projects and worktrees. Add a project to configure its defaults and actions.",headerEnd:e.jsxs(E,{variant:"outline",size:"sm",onClick:i,children:[e.jsx(R,{name:"add",className:"size-4"}),"Add project"]}),children:e.jsx(Y,{title:"Projects",divider:!1,settingsItem:"projects.browse",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"folders",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No projects yet"}),e.jsx("p",{className:"typography-micro max-w-sm text-muted-foreground",children:"Add a local directory to start saving per-project defaults, session history, and header actions."}),e.jsxs(E,{variant:"outline",size:"sm",onClick:i,children:[e.jsx(R,{name:"add",className:"size-4"}),"Add project"]})]})})}):e.jsx(we,{title:t?void 0:"Projects",description:t?void 0:"Manage your projects and worktrees. Click a card to configure its defaults and actions.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:l,onChange:c=>d(c.target.value),placeholder:"Search projects","aria-label":"Search projects",className:"h-9 w-[18rem] max-w-full pl-8"}),l?e.jsx("button",{type:"button",onClick:()=>d(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:i,children:[e.jsx(R,{name:"add",className:"size-4"}),"Add project"]})]}),children:e.jsx(Y,{title:"Projects",divider:!1,settingsItem:"projects.browse",children:h.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["No projects match “",l,"”."]}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>d(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[h.map(c=>e.jsx(cc,{project:c,onSelect:r},c.id)),e.jsxs("button",{type:"button",onClick:i,"aria-label":"Add project",className:H("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"Add project"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Local directory"})]})]})})})},Hn=(t,s,a)=>!t||!Number.isFinite(t)?s:new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short",hour12:a==="auto"?void 0:a==="12h"}).format(t),uc=()=>{const t=W(g=>g.timeFormatPreference),[s,a]=o.useState(!1),[n,r]=o.useState(!0),[l,d]=o.useState(!1),[i,u]=o.useState(null),[m,p]=o.useState(!1),[h,c]=o.useState([]),[f,y]=o.useState(Io),[b,v]=o.useState(""),L=o.useMemo(()=>Eo(),[]),j=o.useCallback(async()=>{r(!0),v("");try{const g=await Ao();c(g)}catch(g){const C=g instanceof Error?g.message:"Could not load passkeys.";v(C)}finally{r(!1)}},[]);o.useEffect(()=>{let g=!1;return(async()=>{try{if(!L.supported){g||(a(!1),r(!1));return}g||a(!0)}catch{g||a(!1)}if(!g){const C=await Sa();if(y(C),!C.enabled){c([]),r(!1);return}await j()}})(),()=>{g=!0,En()}},[j,L.supported]);const T=o.useCallback(async()=>{if(!f.enabled){const g="Enable the UI password lock before adding passkeys.";v(g),$.message(g);return}if(!s){v(L.reason),$.message(L.reason);return}if(l){En(),d(!1);return}v(""),d(!0);try{await Mo(),y(await Sa()),await j(),$.success("Passkey added")}catch(g){if(Lo(g)){$.message("Passkey setup canceled");return}const C=g instanceof Error?g.message:"Could not add passkey.";v(C),$.error(C)}finally{d(!1)}},[l,j,f.enabled,L.reason,s]),P=o.useCallback(async g=>{u(g),v("");try{await Ro(g),y(await Sa()),await j(),$.success("Passkey removed")}catch(C){const w=C instanceof Error?C.message:"Could not remove passkey.";v(w),$.error(w)}finally{u(null)}},[j]),A=o.useCallback(async()=>{p(!0),v("");try{await Do(),window.location.reload()}catch(g){const C=g instanceof Error?g.message:"Could not clear saved authentication.";v(C),$.error(C),p(!1)}},[]);return e.jsxs(Y,{title:"Passkeys",settingsItem:"remote-access.passkeys",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Pe,{label:"Current device",children:[e.jsx(E,{type:"button",variant:l?"secondary":"outline",size:"xs",onClick:()=>{T()},disabled:n||m,className:"!font-normal",children:l?"Cancel passkey setup":"Add passkey"}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",onClick:()=>{A()},disabled:n||l||m,className:"!font-normal text-muted-foreground hover:text-foreground",children:m?"Signing out…":"Sign out everywhere"})]}),!f.enabled&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Passkeys are available only when the UI password lock is enabled."}),f.enabled&&!s&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:L.reason}),n?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading passkeys…"}):h.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No passkeys saved for this host yet."}):e.jsx("div",{className:"space-y-1 pt-1",children:h.map(g=>e.jsxs(Pe,{label:e.jsx("span",{className:"truncate",children:g.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:g.lastUsedAt?`Last used ${Hn(g.lastUsedAt,"Never used",t)}`:`Added ${Hn(g.createdAt,"Never used",t)}`}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",onClick:()=>{P(g.id)},disabled:i===g.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:i===g.id?"Removing…":"Delete"})]},g.id))})]}),b&&e.jsx("div",{className:"mt-1 py-1.5",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:b})})]})},pc=({addDevice:t,isDesktop:s})=>{const{phase:a,creating:n,loopbackOnly:r,pairingUrl:l,pairingQrDataUrl:d,pairingCopied:i,countdownText:u,announcedCountdownText:m,routeChips:p,error:h,closeDialog:c,regenerate:f,copyLink:y,scrollToWays:b}=t;return e.jsx(e.Fragment,{children:r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Other devices can't reach this computer yet"}),e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Turn on a route in Ways to connect so this code has somewhere to connect through."})]}),s?null:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Local network needs the server started with --lan."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s?e.jsx(E,{type:"button",size:"xs",className:"!font-normal",onClick:()=>b("lan"),children:"Turn on Local network"}):null,e.jsx(E,{type:"button",size:"xs",variant:s?"outline":"default",className:"!font-normal",onClick:()=>b("tailscale"),children:"Set up Tailscale"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:c,children:"Cancel"})})]}):n&&!l?e.jsxs("div",{className:"flex items-center gap-2 py-6 typography-ui text-muted-foreground",role:"status",children:[e.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin","aria-hidden":!0}),"Creating secure code…"]}):e.jsxs("div",{className:"space-y-3",children:[d?e.jsx("div",{className:"flex justify-center",children:e.jsx("img",{src:d,alt:"PiChamber connection QR code",className:H("w-full max-w-[420px] rounded-md bg-white p-4",a==="expired"&&"opacity-40 grayscale"),"aria-hidden":a==="expired"})}):null,e.jsx("p",{className:"typography-ui-label text-center text-foreground",children:a==="expired"?"Code expired":"Scan with the PiChamber app"}),a==="ready"&&u?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-center text-muted-foreground","aria-hidden":!0,children:u}),e.jsx("p",{className:"sr-only","aria-live":"polite",children:m??u})]}):null,a==="expired"?e.jsx("p",{className:"typography-meta text-center text-muted-foreground",children:"This code expired. Create a new one to keep pairing."}):null,p.length>0?e.jsx("div",{className:"flex flex-wrap justify-center gap-1.5","aria-label":"Included routes",children:p.map(v=>e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1.5 py-0.5 rounded shrink-0 leading-none border border-border/50",children:v.label},v.key))}):null,a==="ready"?e.jsxs("p",{className:"flex items-center justify-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-[var(--status-warning)] animate-pulse","aria-hidden":!0}),"Waiting for device…"]}):null,h?e.jsx("p",{className:"typography-meta text-center text-[var(--status-error)]",role:"alert",children:h}):null,l?e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-[var(--interactive-border)] p-2",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate typography-code text-muted-foreground",children:l}),e.jsxs(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:y,"aria-label":i?"Pairing link copied":"Copy pairing link",children:[e.jsx(R,{name:i?"check":"file-copy",className:H("h-3.5 w-3.5",i&&"text-[var(--status-success)]"),"aria-hidden":!0}),i?"Copied":"Copy"]})]}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:c,children:"Cancel"}),e.jsxs(E,{type:"button",variant:a==="expired"?"default":"outline",size:"xs",className:"!font-normal",onClick:f,disabled:n,children:[e.jsx(R,{name:"refresh",className:"h-3.5 w-3.5","aria-hidden":!0}),"New code"]})]})]})})},mc=({addDevice:t,isDesktop:s})=>{const a=!t.loopbackOnly&&!!t.pairingQrDataUrl;return e.jsx(jt,{open:t.open,onOpenChange:n=>{n||t.closeDialog()},children:e.jsxs(kt,{className:"sm:max-w-lg",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Add a device"}),a?e.jsx(St,{children:"Scan this with the PiChamber app on your other device. It is single-use and expires."}):null]}),e.jsx(pc,{addDevice:t,isDesktop:s})]})})},Gn=t=>{switch((t||"").toLowerCase()){case"ios":return"iOS";case"android":return"Android";case"macos":case"darwin":return"macOS";case"windows":case"win32":return"Windows";case"linux":return"Linux";default:return null}},hc=({devices:t})=>{const s=W(p=>p.timeFormatPreference),{remoteClients:a,pendingPairings:n,loading:r,error:l,revokedClientCount:d,revokeRemoteClient:i,purgeRevokedRemoteClients:u,cancelPendingPairing:m}=t;return e.jsxs(Y,{title:"Devices with access",info:"Devices that can open this server. Revoking removes a device immediately, including its live connections.",settingsItem:"remote-access.devices",contentClassName:"space-y-2.5",children:[d>0?e.jsx("div",{className:"flex justify-end",children:e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>u(),children:"Clear revoked"})}):null,r&&a.length===0&&n.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading devices..."}):a.length===0&&n.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No devices connected yet."}):e.jsxs(e.Fragment,{children:[n.map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-[var(--status-warning)] animate-pulse","aria-hidden":!0}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:p.label||"Pair new device"}),p.usesRelay?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:"Relay"}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:"Waiting to connect…"})]}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>m(p.id),"aria-label":`Cancel pairing for ${p.label||"new device"}`,children:"Cancel"})]},`pending-${p.id}`)),a.map(p=>{const h=p.clientKind==="desktop-local",c=p.lastUsedAt?Date.parse(p.lastUsedAt):Number.NaN,f=!p.revokedAt&&(h||Number.isFinite(c)&&Date.now()-c<9e4),y=p.revokedAt?"Revoked":f?p.lastTransport==="relay"&&!h?"Connected · Relay":"Connected · Local network":Number.isFinite(c)?`Last used ${_o(c,s,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:"Never used";return e.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5",children:[e.jsx("span",{"aria-hidden":!0,className:H("h-2 w-2 shrink-0 rounded-full",p.revokedAt?"bg-muted-foreground/20":f?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:p.label}),Gn(p.devicePlatform)?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:Gn(p.devicePlatform)}):null,h?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"This device"}):null,e.jsx("span",{className:H("typography-micro truncate",f&&!p.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:y})]})}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>i(p),disabled:!!p.revokedAt,"aria-label":`Revoke ${p.label}`,children:"Revoke"})]},p.id)})]}),l?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:l}):null]})},fc=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:pt,children:e.jsx(ke,{settingsItem:"sessions.desktop-lan-access",checked:t.draftLanEnabled,onChange:t.setDraftLanEnabled,disabled:t.isLoading||t.isSaving,label:"Let other devices on your local network open this app",info:"Restarts the app so phones, tablets, and other computers on your Wi-Fi can open it. On Windows, allow PiChamber through the firewall if a phone still cannot connect.",description:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"block text-[var(--status-warning)]/85",children:"Warning: while enabled, the app is reachable by anyone on the same local network."}),t.lanRequiresPassword||t.lanBlockedByMissingPassword?e.jsx("span",{className:"block text-[var(--status-warning)]/85",children:"LAN access requires a Desktop UI Password. Until one is set, the desktop app starts local-only."}):null]}),ariaLabel:"Allow LAN access to desktop sidecar"})}),t.error?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t.error}):null,t.lanUrl?e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[t.isDirty&&!t.draftLanEnabled?"After restart, open from another device: ":"Open from another device: ",e.jsx("span",{className:"font-mono text-foreground",children:t.lanUrl})]}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(E,{type:"button",size:"xs",onClick:t.saveAndRestart,disabled:t.saveDisabled,className:"shrink-0 !font-normal",children:t.isSaving?"Saving...":"Save + Restart"})})]}),gc=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{settingsItem:"sessions.desktop-ui-password",label:e.jsx("label",{htmlFor:"desktop-ui-password",children:"Desktop UI Password"}),info:"PiChamber asks after restart, then when the login session expires: after 12 hours, or 7 days with Trust this device. Leave empty to disable login.",children:[e.jsx(ee,{id:"desktop-ui-password",type:t.showPassword?"text":"password",className:"h-8 min-w-0 flex-1",value:t.draftPassword,onChange:s=>t.handlePasswordChange(s.target.value),placeholder:"No password required",disabled:t.isLoading||t.isSaving,required:t.draftLanEnabled,"aria-invalid":t.lanRequiresPassword}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",onClick:()=>t.setShowPassword(s=>!s),className:Qe,"aria-label":t.showPassword?"Hide password":"Show password","aria-pressed":t.showPassword,children:e.jsx(R,{name:t.showPassword?"eye-off":"eye",className:"h-4 w-4"})})]}),t.error?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t.error}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(E,{type:"button",size:"xs",onClick:t.saveAndRestart,disabled:t.saveDisabled,className:"shrink-0 !font-normal",children:t.isSaving?"Saving...":"Save + Restart"})})]}),xc=()=>{const t=Le()&&Kt(),[s,a]=D.useState(!1),[n,r]=D.useState(!1),[l,d]=D.useState(""),[i,u]=D.useState(""),[m,p]=D.useState(!1),[h,c]=D.useState(!1),[f,y]=D.useState(null),[b,v]=D.useState(!0),[L,j]=D.useState(!1),[T,P]=D.useState(null),[A,g]=D.useState(null);D.useEffect(()=>{if(!t){v(!1);return}let _=!1;return(async()=>{try{const O=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!O.ok)throw new Error("Failed to load desktop settings");const V=await O.json().catch(()=>null);if(_)return;const K=V?.desktopLanAccessEnabled===!0,Z=typeof V?.desktopUiPassword=="string"?V.desktopUiPassword:"";a(K),r(K),d(Z),u(Z),c(V?.desktopLanAccessActive===!0),y(typeof V?.desktopLanAccessBlockedReason=="string"?V.desktopLanAccessBlockedReason:null),P(null)}catch(O){_||P(O instanceof Error?O.message:"Failed to load desktop settings")}finally{_||v(!1)}})(),()=>{_=!0}},[t]),D.useEffect(()=>{if(!t||!n){g(null);return}let _=!1;return(async()=>{const O=await Ji();_||g(O)})(),()=>{_=!0}},[n,t]);const C=n!==s||i!==l,w=D.useMemo(()=>{if(typeof window>"u")return null;const O=ot()||window.location.href;let V=0;try{V=Number(new URL(O).port)}catch{V=Number(window.location.port)}return Number.isFinite(V)&&V>0?V:null},[]),x=n&&h&&A&&w?`http://${A}:${w}`:null,N=n&&!i.trim(),k=s&&!h&&f==="missing-password",I=b||L||!C||N,S=D.useCallback(_=>{u(_),_.trim()||r(!1)},[]),z=D.useCallback(async()=>{if(C){j(!0),P(null);try{if(!(await Te("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:n,desktopUiPassword:i})})).ok)throw new Error("Failed to save desktop settings");if(a(n),d(i),!await hr())throw new Error("Saved, but failed to restart app")}catch(_){P(_ instanceof Error?_.message:"Failed to save desktop settings"),j(!1)}}},[i,n,C]);return{isLocalDesktop:t,isLoading:b,isSaving:L,error:T,draftLanEnabled:n,setDraftLanEnabled:r,draftPassword:i,handlePasswordChange:S,showPassword:m,setShowPassword:p,lanAccessActive:h,lanRequiresPassword:N,lanBlockedByMissingPassword:k,lanUrl:x,isDirty:C,saveDisabled:I,saveAndRestart:()=>{z()}}},ri=()=>{const[t,s]=D.useState(!1),a=D.useRef(null);D.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]);const n=D.useCallback(r=>{aa(r).then(l=>{l.ok&&(s(!0),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>s(!1),2e3))})},[]);return{copied:t,copy:n}},vc={neutral:"text-muted-foreground bg-muted border-border/50",success:"text-[var(--status-success)] bg-[var(--status-success)]/10 border-[var(--status-success)]/30",warning:"text-[var(--status-warning)] bg-[var(--status-warning)]/10 border-[var(--status-warning)]/30",error:"text-[var(--status-error)] bg-[var(--status-error-background)] border-[var(--status-error-border)]",info:"text-[var(--status-info)] bg-[var(--status-info-background)] border-[var(--status-info-border)]"},ut=({tone:t,children:s})=>e.jsx("span",{className:H("typography-micro shrink-0 rounded border px-1.5 py-px leading-relaxed",vc[t]),children:s}),Yt=({id:t,icon:s,title:a,pill:n,description:r,settingsItem:l,children:d})=>e.jsx(Ft,{settingsItem:l,title:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",id:t,children:[e.jsx(R,{name:s,className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:rl,children:a}),n]}),children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:r}),d]})}),ii=({url:t,copyLabel:s,onOpen:a,openLabel:n})=>{const{copied:r,copy:l}=ri(),d=r?`${s} (copied)`:s,i=e.jsxs(e.Fragment,{children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono typography-micro text-foreground",children:t}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[r?e.jsx("span",{className:"typography-micro text-[var(--status-success)]",children:"Copied"}):null,e.jsx(R,{name:r?"check":"file-copy",className:H("h-3.5 w-3.5",r?"text-[var(--status-success)]":"text-muted-foreground"),"aria-hidden":!0})]}),r?e.jsx("span",{className:"sr-only",role:"status",children:"Copied"}):null]});return a?e.jsxs("div",{className:"flex min-w-0 max-w-[24rem] items-center gap-0.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] py-1 pl-2 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>l(t),"aria-label":d,title:t,className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-sm px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:i}),e.jsx("button",{type:"button",onClick:a,"aria-label":n??"Open address",title:n??void 0,className:"flex shrink-0 items-center justify-center rounded-sm p-1 text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:e.jsx(R,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})})]}):e.jsx("button",{type:"button",onClick:()=>l(t),"aria-label":d,title:t,className:"flex min-w-0 max-w-[24rem] items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2 py-1.5 text-left transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:i})},bc=({lan:t})=>{if(Le()&&Kt()){const a=t.lanUrl?e.jsx(ut,{tone:"success",children:"On"}):t.draftLanEnabled?e.jsx(ut,{tone:"warning",children:"Restart needed"}):e.jsx(ut,{tone:"neutral",children:"Off"});return e.jsx(Yt,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:a,description:"Phones and computers on your Wi-Fi reach this computer directly.",settingsItem:"remote-access.lan",children:e.jsx(fc,{lan:t})})}return e.jsx(yc,{})},yc=()=>{const{clientAuth:t}=na(),[s,a]=D.useState(null),[n,r]=D.useState(!0),[l,d]=D.useState(!1);return D.useEffect(()=>{if(!t?.getPairingTransports){r(!1);return}let i=!1;return(async()=>{try{const u=await t.getPairingTransports();i||(a(u),d(!1))}catch{i||d(!0)}finally{i||r(!1)}})(),()=>{i=!0}},[t]),n?e.jsx(Yt,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(ut,{tone:"neutral",children:"Checking…"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Checking whether this server is exposed on your network…"})}):l||!s?e.jsx(Yt,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(ut,{tone:"neutral",children:"Unknown"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Couldn't check local network status. Check your connection and try again."})}):s.lan?e.jsx(Yt,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(ut,{tone:"success",children:"On"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx(ii,{url:s.lan,copyLabel:"Copy local network address"})}):e.jsx(Yt,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(ut,{tone:"neutral",children:"Off"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Not exposed on your network. Start the server with --lan and a UI password to allow local devices."})})},mn=t=>!!t&&typeof t=="object"&&typeof t.state=="string",hn=async(t,s)=>{const a=await t.json().catch(()=>null),n=typeof a?.error=="string"&&a.error?a.error:s,r=new Error(n);throw typeof a?.code=="string"&&(r.code=a.code),r.status=t.status,r},wc=async t=>{const s=await Te("/api/pichamber/tailscale/status",{headers:{Accept:"application/json"}});s.ok||await hn(s,"Failed to get Tailscale status");const a=await s.json().catch(()=>null);if(!mn(a))throw new Error("Invalid Tailscale status response");return a},jc=async t=>{const s=await Te("/api/pichamber/tailscale/config",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});s.ok||await hn(s,"Failed to update Tailscale config");const a=await s.json().catch(()=>null);if(!mn(a))throw new Error("Invalid Tailscale status response");return a},kc=async()=>{const t=await Te("/api/pichamber/tailscale/retry",{method:"POST",headers:{Accept:"application/json"}});t.ok||await hn(t,"Tailscale retry failed");const s=await t.json().catch(()=>null);if(!mn(s))throw new Error("Invalid Tailscale status response");return s},Nc=2e3,Cc=15e3,La=t=>t==="starting"||t==="needs-approval"?Nc:Cc,oi=t=>t.config.enabled?t.config.mode:"off",Sc=(t,s)=>s==="public"&&t!=="public",qn=(t,s)=>{if(!t)return!1;const a=t.authGate;return a?s==="private"?a.privateAllowed!==!1:a.publicAllowed!==!1:!0},Tc=t=>{if(!t)return null;if(t.installed===!1)return{pill:"Not installed",tone:"neutral",controlDisabled:!0,controlDisabledReason:"Install Tailscale to use this route.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Tailscale is not installed on this computer."};if(t.running===!1||t.loggedIn===!1)return{pill:"Not signed in",tone:"warning",controlDisabled:!0,controlDisabledReason:"Open Tailscale and sign in first.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.running===!1?"The Tailscale daemon is not running.":"Tailscale is installed but you are not signed in."};switch(t.state){case"off":return{pill:"Off",tone:"neutral",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:null};case"unavailable":return t.errorCode==="not_installed"?{pill:"Not installed",tone:"neutral",controlDisabled:!0,controlDisabledReason:"Install Tailscale to use this route.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Tailscale is not installed on this computer."}:t.errorCode==="not_running"||t.errorCode==="not_logged_in"?{pill:"Not signed in",tone:"warning",controlDisabled:!0,controlDisabledReason:"Open Tailscale and sign in first.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorCode==="not_running"?"The Tailscale daemon is not running.":"Tailscale is installed but you are not signed in."}:{pill:"Unavailable",tone:"neutral",controlDisabled:!0,controlDisabledReason:t.errorMessage,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage};case"blocked":return{pill:"Blocked",tone:"warning",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!0,publicDnsNote:null,headline:"Tailscale needs a UI password before it can be enabled."};case"starting":return{pill:"Setting up…",tone:"info",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:null};case"needs-approval":return{pill:"Waiting for approval…",tone:"warning",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!0,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Your tailnet admin must approve this route."};case"active":{const s=t.config.mode==="public"&&(t.publicDns==="pending"||t.publicDns==="unknown")?t.publicDns:null;return{pill:t.config.mode==="public"?"On · Public":"On · Private",tone:t.config.mode==="public"?"warning":"success",controlDisabled:!1,controlDisabledReason:null,showUrl:!0,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:s,headline:null}}case"conflict":return{pill:"Port in use",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!0,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Another destination already uses this port in Tailscale."};case"error":return t.errorCode==="status_query_failed"?{pill:"Error",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Could not read the current Tailscale status, so nothing was changed. Try again."}:t.errorCode==="permission_denied"?{pill:"Permission needed",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!0,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Tailscale denied the serve configuration."}:{pill:"Error",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Something went wrong."};default:return null}},Pc=()=>{const[t,s]=D.useState(null),[a,n]=D.useState(!0),[r,l]=D.useState(!1),[d,i]=D.useState(null),[u,m]=D.useState(null),[p,h]=D.useState(null),[c,f]=D.useState(!1),[y,b]=D.useState(null),[v,L]=D.useState(!1),j=D.useRef(0),T=D.useCallback(I=>{s(I),l(!1),i(null)},[]),P=D.useCallback(async I=>{const S=j.current;try{const z=await wc();if(j.current!==S)return;T(z)}catch(z){if(j.current!==S)return;I?.initial&&!t&&l(!0),i(z instanceof Error?z.message:"Failed to load Tailscale status")}finally{j.current===S&&I?.initial&&n(!1)}},[T]);D.useEffect(()=>(P({initial:!0}),()=>{j.current+=1}),[P]),D.useEffect(()=>{if(typeof window>"u")return;let I=null,S=!1;const z=async()=>{if(!S){if(typeof document<"u"&&document.visibilityState==="hidden"){_(La(t?.state??null));return}await P(),S||_(La(t?.state??null))}},_=V=>{S||(I=setTimeout(()=>{z()},V))};_(La(t?.state??null));const O=()=>{document.visibilityState==="visible"&&(I&&clearTimeout(I),z())};return document.addEventListener("visibilitychange",O),()=>{S=!0,I&&clearTimeout(I),document.removeEventListener("visibilitychange",O)}},[P,t?.state]);const A=D.useCallback(async I=>{const S=j.current;f(!0),m(null),h(null);try{const z=await jc(I);if(j.current!==S)return;T(z)}catch(z){if(j.current!==S)return;const _=z.code;m(z instanceof Error?z.message:"Failed to update Tailscale"),h(typeof _=="string"?_:null)}finally{j.current===S&&(f(!1),b(null))}},[T]),g=D.useCallback(I=>{if(!t||c)return;const S=oi(t);if(I!==S){if(Sc(S,I)){L(!0);return}b(I),A(I==="off"?{enabled:!1}:{enabled:!0,mode:I})}},[t,c,A]),C=D.useCallback(()=>{L(!1),!(!t||c)&&(b("public"),A({enabled:!0,mode:"public"}))},[t,c,A]),w=D.useCallback(()=>{L(!1)},[]),x=D.useCallback(I=>{!t||c||t.config.httpsPort!==I&&A({httpsPort:I})},[t,c,A]),N=D.useCallback(async()=>{const I=j.current;f(!0),m(null),h(null);try{const S=await kc();if(j.current!==I)return;T(S)}catch(S){if(j.current!==I)return;const z=S.code;m(S instanceof Error?S.message:"Tailscale retry failed"),h(typeof z=="string"?z:null)}finally{j.current===I&&(f(!1),b(null))}},[T]),k=D.useCallback(()=>{n(!0),l(!1),i(null),P({initial:!0})},[P]);return{status:t,initialLoading:a,loadFailed:r,loadError:d,actionError:u,actionErrorCode:p,mutationInFlight:c,pendingMode:y,confirmPublicOpen:v,setMode:g,confirmPublic:C,cancelPublicConfirm:w,setPort:x,retryNow:N,reload:k}},Ic="https://tailscale.com/download",Qn="sudo tailscale set --operator=$USER",Ec=[{value:"off",label:"Off"},{value:"private",label:"Private"},{value:"public",label:"Public"}],Ac={off:"Tailscale is not used.",private:"Only devices signed in to your Tailscale.",public:"Reachable from the internet through Tailscale Funnel. Devices still need to be paired."},Jn=()=>{const t=document.getElementById("desktop-ui-password");t&&(t.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>t.focus({preventScroll:!0}),250))},Mc=(t,s)=>t?s==="auth_required"?`${t} (auth_required)`:s==="invalid_config"?`${t} (invalid_config)`:s?`${t} (${s})`:/failed to fetch|networkerror|load failed|fetch/i.test(t)?`${t} Check your connection and try again.`:t:null,Lc=()=>{const t=Pc(),{status:s,initialLoading:a,loadFailed:n,loadError:r,actionError:l,actionErrorCode:d,mutationInFlight:i,pendingMode:u,confirmPublicOpen:m}=t,p=Le(),h=Tc(s),c=s?oi(s):"off",f=u??c,{copied:y,copy:b}=ri(),v=!!h?.controlDisabled,L=qn(s,"private"),j=qn(s,"public"),T=s?!L||!j:!1,P=S=>i?!0:S==="off"?!1:v?!0:S==="private"?!L:S==="public"?!j:!1,A=S=>S==="off"||!s?null:v?h?.controlDisabledReason??null:S==="private"&&!L||S==="public"&&!j?"Set a UI password first":null,g=D.useRef(null),C=D.useCallback(S=>{g.current?.querySelector(`[data-mode="${S}"]`)?.focus()},[]),w=D.useCallback(S=>{if(S.key!=="ArrowRight"&&S.key!=="ArrowLeft"&&S.key!=="ArrowUp"&&S.key!=="ArrowDown")return;S.preventDefault();const z=["off","private","public"],_=S.target?.closest("[data-mode]")?.dataset.mode,O=z.includes(_)?_:f,V=z.indexOf(O),K=S.key==="ArrowRight"||S.key==="ArrowDown"?1:-1;for(let Z=1;Z<=z.length;Z+=1){const ae=z[(V+K*Z+z.length)%z.length];if(!P(ae)){C(ae);return}}},[f,i,v,L,j,s]),x=a||!h?e.jsx(ut,{tone:"neutral",children:n?"Unknown":"Checking…"}):e.jsx(ut,{tone:i&&u?"info":h.tone,children:i&&u?"Saving…":h.pill}),N=!!s&&(s?.installed===!1||s?.errorCode==="not_installed"),k=!!s&&s?.installed!==!1&&(s?.running===!1||s?.loggedIn===!1||s?.errorCode==="not_running"||s?.errorCode==="not_logged_in"),I=Mc(l,d);return e.jsxs(Yt,{id:"remote-access-tailscale-row",icon:"global",title:"Tailscale",pill:x,description:"Reach this computer through your Tailscale network, at home or away.",settingsItem:"remote-access.tailscale",children:[a&&!s?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Checking Tailscale status…"}):n&&!s?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:r??"Couldn't load Tailscale status."}),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.reload,children:"Try again"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{ref:g,role:"radiogroup","aria-label":"Tailscale mode",className:"flex flex-wrap items-center gap-1",onKeyDown:w,children:Ec.map(S=>{const z=P(S.value),_=A(S.value),O=f===S.value;return e.jsx(E,{type:"button",variant:"chip",size:"xs","data-mode":S.value,role:"radio","aria-checked":O,"aria-label":_?`${S.label} (${_})`:S.label,title:_??void 0,disabled:z,"aria-pressed":void 0,className:"!font-normal",onClick:()=>t.setMode(S.value),children:S.label},S.value)})}),i&&u?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Saving…"}):null,v?null:e.jsx("p",{className:at,children:Ac[f]}),T&&!v?e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Set a UI password first"}),p?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:!L&&!j?"Private and Public need a desktop UI password before they can be enabled.":j?"Private needs a desktop UI password before it can be enabled.":"Public needs a desktop UI password before it can be enabled."}),e.jsx("div",{className:"mt-2",children:e.jsx(E,{type:"button",size:"xs",className:"!font-normal",onClick:Jn,children:"Go to password"})})]}):e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a UI password. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})]}):null,h?.headline&&h.showUrl!==!0&&!h.showAuthCallout&&!T?e.jsx("p",{className:"typography-ui-label text-foreground",children:h.headline}):null,h?.showUrl&&s?.url?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ii,{url:s.url,copyLabel:"Copy Tailscale address",onOpen:()=>{fs(s.url)},openLabel:"Open Tailscale address"}),h?.publicDnsNote==="pending"?e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Public link is waiting for DNS. New Funnel links can take 10–15 minutes to work outside your tailnet; devices on your tailnet can connect now."]}):null,h?.publicDnsNote==="unknown"?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Couldn't check public DNS. New Funnel links can take 10–15 minutes to work outside your tailnet."}):null]}):null,N?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Install Tailscale on this computer, then sign in to the same tailnet as your phone."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{fs(Ic)},children:["Get Tailscale",e.jsx(R,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})]}),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:i,children:"Check again"})]})]}):null,k?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Open Tailscale and sign in, then check again."}),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:i,children:"Check again"})]}):null,h?.showAuthCallout&&!T?e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Set a password first"}),p?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a desktop UI password before it can be enabled."}),e.jsx("div",{className:"mt-2",children:e.jsx(E,{type:"button",size:"xs",className:"!font-normal",onClick:Jn,children:"Go to password"})})]}):e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a UI password. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})]}):null,s?.state==="starting"?e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Setting up…"]}):null,h?.showApproval?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Waiting for approval…"}),s?.approvalUrl?e.jsxs(E,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{fs(s.approvalUrl)},children:["Approve in Tailscale",e.jsx(R,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null,h?.showPermissionFix?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex min-w-0 max-w-[24rem] items-center gap-1.5 rounded-md border border-[var(--interactive-border)] px-2 py-1.5",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono typography-micro text-foreground",children:Qn}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal shrink-0",onClick:()=>b(Qn),"aria-label":y?"Fix command copied":"Copy fix command",children:e.jsx(R,{name:y?"check":"file-copy",className:H("h-3.5 w-3.5",y&&"text-[var(--status-success)]"),"aria-hidden":!0})})]}),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:i,children:"Try again"})]}):null,s?.state==="error"&&!h?.showPermissionFix?e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:i,children:"Try again"})}):null,I?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:I}):null,s&&s.config.enabled?e.jsx(Pr,{label:"Advanced",children:e.jsxs("div",{className:"space-y-2","data-settings-item":"remote-access.tailscale-port",children:[e.jsx("p",{className:at,children:"HTTPS port for the Tailscale address. Public (Funnel) addresses only allow 443, 8443, or 10000."}),e.jsx("div",{role:"radiogroup","aria-label":"Tailscale HTTPS port",className:"flex flex-wrap items-center gap-1",children:["443","8443","10000"].map(S=>e.jsx(E,{type:"button",variant:"chip",size:"xs",role:"radio","aria-checked":String(s.config.httpsPort)===S,"aria-label":`Port ${S}`,className:"!font-normal",disabled:i,onClick:()=>t.setPort(Number(S)),children:S},S))})]})}):null]}),e.jsx(jt,{open:m,onOpenChange:S=>{S||t.cancelPublicConfirm()},children:e.jsxs(kt,{className:"sm:max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Make PiChamber reachable from the internet?"}),e.jsx(St,{children:"Anyone with the address can reach the sign-in page. Devices still need to be paired, and the UI password protects browser sign-in. If your phone has Tailscale, Private is the safer choice."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.cancelPublicConfirm,children:"Cancel"}),e.jsx(E,{type:"button",size:"xs",className:"!font-normal",onClick:t.confirmPublic,children:"Make public"})]})]})})]})},Rc=t=>({...t.lan?{serverUrl:t.lan}:{},includeRelay:t.relayAvailable,includeDirect:!0}),Dc=t=>!t.lan&&!(t.tailscale?.available&&t.tailscale.url)&&!t.relayAvailable,_c=t=>{const s=[],a=t.candidates.find(r=>r.type==="lan"||r.type==="tunnel");if(a&&"url"in a&&a.url){let r=a.url;try{r=new URL(a.url).hostname}catch{}s.push({key:"lan",label:`Local network · ${r}`})}else if(t.lanUrl){let r=t.lanUrl;try{r=new URL(t.lanUrl).hostname}catch{}s.push({key:"lan",label:`Local network · ${r}`})}const n=t.candidates.find(r=>r.type==="tailscale");return n&&"mode"in n&&s.push({key:"tailscale",label:`Tailscale · ${n.mode==="public"?"Public":"Private"}`}),t.candidates.some(r=>r.type==="relay")&&s.push({key:"relay",label:"Relay · works away from home"}),s},Ra=t=>{if(!Number.isFinite(t)||t<=0)return null;const s=Math.floor(t/1e3),a=Math.floor(s/60),n=s%60;return`Expires in ${a}:${String(n).padStart(2,"0")}`},zc=(t,s)=>{if(!Number.isFinite(t)||!Number.isFinite(s))return!1;if(t<=0||s<=0)return t<=0!=s<=0;const a=n=>Math.floor(n/6e4);return a(t)!==a(s)?!0:t<=1e4&&Math.floor(t/1e3)!==Math.floor(s/1e3)},Oc=t=>{if(t.succeeded)return"succeeded";if(!t.hasPayload||!t.expiresAt)return"creating";const s=Date.parse(t.expiresAt);return Number.isFinite(s)?s<=t.nowMs?"expired":"ready":"creating"},Uc=1e3,Fc=(t,s)=>{const[a,n]=D.useState(!1),[r,l]=D.useState(!1),[d,i]=D.useState(!1),[u,m]=D.useState(null),[p,h]=D.useState(null),[c,f]=D.useState(!1),[y,b]=D.useState(null),[v,L]=D.useState(null),[j,T]=D.useState([]),[P,A]=D.useState(null),[g,C]=D.useState(null),[w,x]=D.useState(()=>Date.now()),[N,k]=D.useState(!1),[I,S]=D.useState(null),z=D.useRef(!1),_=D.useRef(0),O=D.useRef(null),V=d?"creating":Oc({expiresAt:v,nowMs:w,hasPayload:!!u,succeeded:N}),K=v?Date.parse(v)-w:Number.NaN,Z=V==="ready"?Ra(K):null,ae=D.useMemo(()=>_c({candidates:j,lanUrl:P}),[j,P]);D.useEffect(()=>{if(!a||!v||N)return;const re=window.setInterval(()=>{const me=Date.now();x(me);const J=Date.parse(v)-me,B=O.current;if(O.current=J,B!==null&&zc(J,B)){const U=Ra(J);U&&S(U)}},Uc);return()=>window.clearInterval(re)},[a,v,N]);const fe=D.useCallback(async()=>{if(!t?.createPairingSession){C("Pairing is not available on this server.");return}const re=_.current+1;_.current=re,l(!0),C(null),m(null),h(null),f(!1),b(null),L(null),T([]),k(!1),z.current=!1,O.current=null;try{const me=await t.getPairingTransports();if(_.current!==re)return;if(A(me.lan),Dc(me)){i(!0);return}i(!1);const J=Rc(me),{pairing:B,server:U}=await t.createPairingSession({allowedClientKinds:["mobile","desktop"],serverUrl:J.serverUrl,includeRelay:J.includeRelay,includeDirect:J.includeDirect});if(_.current!==re){t.cancelPairing&&t.cancelPairing(B.id).catch(()=>{});return}const X=Yi({pairingId:B.id,secret:B.secret,label:U.label,fingerprint:B.fingerprint??void 0,expiresAt:B.expiresAt,candidates:U.candidates}),he=Xi(X);if(m(he),h(await Mr.toDataURL(he,{width:1024,margin:2,errorCorrectionLevel:"L"})),_.current!==re)return;b(B.id),L(B.expiresAt??null),T(U.candidates),x(Date.now()),O.current=B.expiresAt?Date.parse(B.expiresAt)-Date.now():null;const je=B.expiresAt?Ra(Date.parse(B.expiresAt)-Date.now()):null;S(je)}catch(me){if(_.current!==re)return;C(me instanceof Error?me.message:String(me))}finally{_.current===re&&l(!1)}},[t]),ce=D.useCallback(()=>{C(null),i(!1),n(!0),fe()},[fe]),be=D.useCallback(re=>{!re||!t?.cancelPairing||t.cancelPairing(re).catch(()=>{})},[t]),ie=D.useCallback(()=>{N||be(y),_.current+=1,n(!1),l(!1),b(null)},[N,y,be]),ne=D.useCallback(()=>{be(y),fe()},[be,y,fe]),pe=D.useCallback(()=>{u&&aa(u).then(re=>{re.ok&&(f(!0),window.setTimeout(()=>f(!1),2e3))})},[u]),oe=D.useCallback(re=>{n(!1),window.requestAnimationFrame(()=>{document.getElementById(re==="lan"?"remote-access-lan-row":"remote-access-tailscale-row")?.scrollIntoView({block:"center",behavior:"smooth"})})},[]),{pendingPairings:G,remoteClients:q,reload:Ce}=s;return D.useEffect(()=>{if(!(!a||!y||N)){if(G.some(re=>re.id===y)){z.current=!0;return}z.current&&(k(!0),b(null),n(!1),q.some(re=>re.pairingId===y)&&$.success("Device connected."),Ce())}},[a,y,N,G,q,Ce]),{open:a,phase:V,creating:r,loopbackOnly:d&&a&&!r&&!u,pairingUrl:u,pairingQrDataUrl:p,pairingCopied:c,expiresAt:v,countdownText:Z,announcedCountdownText:I,routeChips:ae,error:g,openDialog:ce,closeDialog:ie,regenerate:ne,copyLink:pe,scrollToWays:oe}},Bc=t=>{const[s,a]=D.useState([]),[n,r]=D.useState([]),[l,d]=D.useState(!1),[i,u]=D.useState(null),m=D.useMemo(()=>s.filter(b=>!!b.revokedAt).length,[s]),p=D.useCallback(async b=>{if(t){b?.silent||d(!0),b?.silent||u(null);try{const[v,L]=await Promise.all([t.listClients(),t.listPendingPairings().catch(()=>null)]);a(v),L&&r(L)}catch(v){b?.silent||u(v instanceof Error?v.message:String(v))}finally{b?.silent||d(!1)}}},[t]);D.useEffect(()=>{if(!t)return;p();const b=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||p({silent:!0})},5e3);return()=>window.clearInterval(b)},[t,p]);const h=D.useCallback(async b=>{if(t)try{await t.cancelPairing(b),r(v=>v.filter(L=>L.id!==b)),await p({silent:!0})}catch(v){u(v instanceof Error?v.message:String(v))}},[t,p]),c=D.useCallback(async b=>{if(!t)return;const v=b.clientKind==="desktop-local";u(null);try{if(await t.revokeClient(b.id),v&&Le()){const L=await pr();await Zi({hosts:L.hosts,defaultHostId:L.defaultHostId,initialHostChoiceCompleted:L.initialHostChoiceCompleted,localClientToken:null}),a(j=>j.map(T=>T.id===b.id?{...T,revokedAt:new Date().toISOString()}:T)),Ja({apiBaseUrl:ot(),clientToken:null,runtimeKey:"local"});return}await p()}catch(L){u(L instanceof Error?L.message:String(L))}},[t,p]),f=D.useCallback(async()=>{if(t){u(null);try{await t.purgeRevokedClients(),await p()}catch(b){u(b instanceof Error?b.message:String(b))}}},[t,p]),y=D.useCallback(()=>{p({silent:!0})},[p]);return{remoteClients:s,pendingPairings:n,loading:l,error:i,revokedClientCount:m,reload:y,revokeRemoteClient:b=>{c(b)},purgeRevokedRemoteClients:()=>{f()},cancelPendingPairing:b=>{h(b)}}},$c=t=>{const[s,a]=o.useState("loading");return o.useEffect(()=>{let n=!1;return(async()=>{try{const r=await zo();if(n)return;if(r.status===401){a("set");return}if(!r.ok){a("unknown");return}const l=await r.json().catch(()=>null);a(l?.disabled===!0?"not-set":"set")}catch{n||a("unknown")}})(),()=>{n=!0}},[t]),s},Kc=()=>{const t=$c(!0);return t==="loading"?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Checking UI password…"}):t==="set"?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"UI password is set. The server requires it for browser sign-in."}):t==="not-set"?e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No UI password is set. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The UI password is set when the server starts."})},Yn=()=>{const{isMobile:t}=Ze(),{clientAuth:s}=na(),a=Le(),n=a&&Kt(),r=Rt()&&!Le()&&!Ee(),l=xc(),d=Bc(s),i=Fc(s,d);return e.jsxs(we,{title:t?void 0:"Remote Access",description:t?void 0:"How other devices reach this computer.",headerEnd:s?e.jsx("div",{"data-settings-item":"remote-access.client-auth",children:e.jsxs(E,{type:"button",size:"sm",className:"!font-normal",onClick:()=>i.openDialog(),children:[e.jsx(R,{name:"add",className:"h-4 w-4","aria-hidden":!0}),"Add a device"]})}):void 0,children:[e.jsxs(Y,{title:"Ways to connect",divider:!1,settingsItem:"remote-access.ways",contentClassName:"space-y-6",children:[e.jsx(bc,{lan:l}),e.jsx(Lc,{})]}),s?e.jsx(hc,{devices:d}):null,e.jsxs(Y,{title:"Security",description:"The password protects browser sign-in. It is required for Local network and Tailscale access.",settingsItem:"remote-access.security",contentClassName:"space-y-3",children:[n?e.jsx(gc,{lan:l}):null,n?null:e.jsx(Kc,{})]}),r?e.jsx(uc,{}):null,e.jsx(mc,{addDevice:i,isDesktop:a})]})},Vc=({open:t,step:s,onStepChange:a,onClose:n,canScanQr:r,onScanQr:l,onImportLink:d,importSaving:i=!1,importError:u=null,onAddManual:m,manualSaving:p=!1,manualError:h=null})=>{const[c,f]=D.useState(""),[y,b]=D.useState(""),[v,L]=D.useState(""),[j,T]=D.useState(""),[P,A]=D.useState([]);D.useEffect(()=>{t||(f(""),b(""),L(""),T(""),A([]))},[t]);const g=i||p;return s==="menu"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(E,{type:"button",className:"w-full",disabled:g,onClick:()=>a("link"),children:"Paste a pairing link"}),r&&e.jsx(E,{type:"button",variant:"outline",className:"w-full",disabled:g,onClick:()=>l?.(),children:"Scan QR code"}),e.jsx(E,{type:"button",variant:"outline",className:"w-full",disabled:g,onClick:()=>a("manual"),children:"Enter address manually"}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Manual entry is advanced: the server must already be running and reachable."})]}):s==="link"?e.jsxs("form",{className:"space-y-3",onSubmit:C=>{C.preventDefault(),d(c)},children:[e.jsx(ee,{className:"h-8",value:c,onChange:C=>f(C.target.value),placeholder:"pichamber://connect?...",disabled:g,autoFocus:!0}),u?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:u}):null,e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>a("menu"),disabled:g,children:"Back"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:n,disabled:g,children:"Cancel"}),e.jsxs(E,{type:"submit",size:"xs",className:"!font-normal",disabled:g||!c.trim(),children:[i?e.jsx(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null,"Import link"]})]})]})]}):e.jsxs("form",{className:"space-y-3",onSubmit:C=>{C.preventDefault(),m({label:y,url:v,token:j,headers:P})},children:[e.jsx(ee,{className:"h-8",value:y,onChange:C=>b(C.target.value),placeholder:"Label (optional)",disabled:g}),e.jsx(ee,{className:"h-8",value:v,onChange:C=>L(C.target.value),placeholder:"https://host:port",disabled:g,autoFocus:!0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"h-8",value:j,onChange:C=>T(C.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:g}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Connection tokens are saved on this device and used only when this app connects to that server."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Additional headers",e.jsx("span",{className:"ml-1.5 font-normal text-muted-foreground",children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),P.map(C=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:C.name,onChange:w=>A(x=>x.map(N=>N.id===C.id?{...N,name:w.target.value}:N)),placeholder:"Header name",disabled:g}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:C.value,onChange:w=>A(x=>x.map(N=>N.id===C.id?{...N,value:w.target.value}:N)),placeholder:"Header value",type:"password",disabled:g}),e.jsx("button",{type:"button",onClick:()=>A(w=>w.filter(x=>x.id!==C.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":"Remove header",disabled:g,children:e.jsx(R,{name:"close",className:"h-4 w-4","aria-hidden":"true"})})]},C.id)),e.jsxs(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>A(C=>[...C,br()]),disabled:g,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5","aria-hidden":"true"}),"Add header"]})]}),h?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:h}):null,e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>a("menu"),disabled:g,children:"Back"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:n,disabled:g,children:"Cancel"}),e.jsx(E,{type:"submit",size:"xs",className:"!font-normal",disabled:g||!v.trim(),children:"Add server"})]})]})]})},li=({open:t,onOpenChange:s,canScanQr:a,onScanQr:n,onImportLink:r,importSaving:l=!1,importError:d=null,onAddManual:i,manualSaving:u=!1,manualError:m=null,initialStep:p="menu"})=>{const[h,c]=D.useState(p);return D.useEffect(()=>{t&&c(p)},[t,p]),e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(kt,{className:"sm:max-w-lg",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Add server"}),e.jsx(St,{children:h==="manual"?"Add another PiChamber server by address. Use this when the server is already running and you have a connection token.":h==="link"?"Paste a pairing link from another PiChamber server.":"Import a pairing link from the other server, or add one by address."})]}),e.jsx(Vc,{open:t,step:h,onStepChange:c,onClose:()=>s(!1),canScanQr:a,onScanQr:n,onImportLink:r,importSaving:l,importError:d,onAddManual:i,manualSaving:u,manualError:m})]})})},Wc=({open:t,onOpenChange:s,label:a,onLabelChange:n,url:r,onUrlChange:l,token:d,onTokenChange:i,headers:u,onHeadersChange:m,saving:p,error:h=null,onSave:c})=>e.jsx(jt,{open:t,onOpenChange:s,children:e.jsxs(kt,{className:"sm:max-w-lg",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Edit"}),e.jsx(St,{children:"Servers this app can switch to. Import a pairing link from the other server, or add one by address."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:f=>{f.preventDefault(),c()},children:[e.jsx(ee,{className:"h-8",value:a,onChange:f=>n(f.target.value),placeholder:"Label (optional)",disabled:p}),e.jsx(ee,{className:"h-8",value:r,onChange:f=>l(f.target.value),placeholder:"https://host:port",disabled:p,autoFocus:!0}),e.jsx(ee,{className:"h-8",value:d,onChange:f=>i(f.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:p}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ir,{children:"Additional headers"}),e.jsx(ys,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),u.map(f=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:f.name,onChange:y=>m(b=>b.map(v=>v.id===f.id?{...v,name:y.target.value}:v)),placeholder:"Header name",disabled:p}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:f.value,onChange:y=>m(b=>b.map(v=>v.id===f.id?{...v,value:y.target.value}:v)),placeholder:"Header value",type:"password",disabled:p}),e.jsx("button",{type:"button",onClick:()=>m(y=>y.filter(b=>b.id!==f.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":"Remove header",disabled:p,children:e.jsx(R,{name:"close",className:"h-4 w-4"})})]},f.id)),e.jsxs(E,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>m(f=>[...f,br()]),disabled:p,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),h?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:h}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:p,children:"Cancel"}),e.jsx(E,{type:"submit",size:"xs",className:"!font-normal",disabled:p,children:"Save Changes"})]})]})]})}),Hc=t=>t.wasLast||t.wasActive,Gc=t=>t.needsLogin?{kind:"needs-login"}:t.connecting?{kind:"connecting"}:t.isCurrent?t.uncertain?{kind:"unreachable"}:{kind:"connected",transport:t.relayActive?"relay":"direct"}:{kind:"unknown"},qc=async(t,s)=>{const a=t.connections.find(n=>n.id===s);return a?(await t.connect({id:a.id,candidates:a.candidates,clientToken:a.clientToken,label:a.label}),!0):!1},Qc=async(t,s,a)=>{const n=t.readConnectionCount()<=1,r=await t.removeConnection(s);return r?(Hc({wasLast:n,wasActive:t.isActive(r)})&&a(),!0):!1},Jc=t=>`mobile-connect:${t}`,Yc=(t,s)=>Fo(Jc(t),s);function Xc(t){const{onConnected:s,onActiveConnectionDeleted:a}=t,n=Xr(s),r=Oo(),[l,d]=D.useState(null),i=D.useSyncExternalStore(eo,ts,ts),u=D.useRef(a);u.current=a;const m=D.useRef(n);m.current=n;const p=D.useCallback(async y=>{if(!m.current.connections.some(v=>v.id===y))return!1;d(y);try{return await Yc(y,()=>qc(m.current,y)),!0}finally{d(v=>v===y?null:v)}},[]),h=D.useCallback(async y=>Qc({connections:m.current.connections,connect:m.current.connect,removeConnection:m.current.removeConnection,readConnectionCount:()=>Tt().length,isActive:b=>Os(b)},y,()=>u.current()),[]),c=n.pendingConnection?.id??null;return{items:D.useMemo(()=>{const y=n.connections.map(b=>Xl(b,{isCurrent:Os(b),status:Gc({isCurrent:Os(b),relayActive:i,needsLogin:c!==null&&c===b.id,connecting:l!==null&&l===b.id,uncertain:r}),probing:l!==null&&l===b.id}));return Uo(y)},[n.connections,l,c,i,r]),connections:n.connections,isBusy:n.isBusy,isPasswordBusy:n.isPasswordBusy,error:n.error,pendingConnection:n.pendingConnection,connectingId:l,conn:n,connectServer:p,removeServer:h}}const Zc=({onConnect:t,onActiveConnectionDeleted:s,showDiagnostics:a=!1})=>{const n=Xc({onConnected:t,onActiveConnectionDeleted:s}),{conn:r,items:l,connectingId:d}=n,{connections:i,isBusy:u,isPasswordBusy:m,error:p,pendingConnection:h,saveConnection:c,setError:f}=r,[y,b]=o.useState(null),v=y?i.find(J=>J.id===y)??null:null,[L,j]=o.useState(""),[T,P]=o.useState(""),[A,g]=o.useState(""),[C,w]=o.useState(""),[x,N]=o.useState(!1),[k,I]=o.useState(!1),[S,z]=o.useState(!1),[_,O]=o.useState(!1),[V,K]=o.useState(null),Z=o.useRef(null),ae=o.useMemo(()=>Ql(),[]);o.useEffect(()=>{h&&N(!1)},[h]);const fe=o.useCallback(()=>{b(null),j(""),P(""),g(""),f(null)},[f]),ce=o.useCallback(J=>{const B=i.find(U=>U.id===J)??null;B&&(b(J),j(Ut(B)),P(B.label),g(B.clientToken||""),f(null))},[i,f]),be=o.useCallback(J=>{J.preventDefault(),c({id:y??void 0,url:L,label:T,clientToken:A}).then(B=>{B&&fe()})},[A,y,T,fe,c,L]),ie=o.useCallback(async()=>{if(Z.current)return;f(null),I(!0);const J=new AbortController;Z.current=J;try{const B=await Jl({signal:J.signal});switch(Z.current===J&&(Z.current=null,I(!1)),B.status){case"ok":z(!0),await r.connect({url:B.url,clientToken:B.clientToken,label:B.label});break;case"pairing":z(!0),await r.redeemPairingConnection(B.pairing);break;case"cancelled":break;default:{const U=B.status==="permission-denied"?"Camera access is off. Enable it in Settings to scan a QR code.":B.status==="invalid"?"That QR code is not an PiChamber connection code.":B.status==="unsupported"?"QR scanning is only available in the installed mobile app.":"Could not scan that QR code. Try again or enter the URL manually.";N(!1),f(U);break}}}finally{z(!1),Z.current===J&&(Z.current=null,I(!1))}},[r,f]);o.useEffect(()=>()=>Z.current?.abort(),[]);const ne=o.useCallback(J=>{const B=ti(J.trim());if(!B){f("Invalid PiChamber connection link.");return}if("pairing"in B){r.redeemPairingConnection(B.pairing);return}r.connect({url:B.url})},[r,f]),pe=o.useCallback(J=>{if(!J.url.trim()){f("Enter a server URL.");return}r.connect({url:J.url,label:J.label,clientToken:J.token})},[r,f]),oe=o.useCallback(J=>{J.preventDefault(),r.submitPassword(C)},[r,C]),G=o.useCallback(()=>{w(""),r.cancelPassword()},[r]),q=o.useCallback(async()=>{if(!_){K(null),O(!0);try{const J=await to();K(J==="copied"?"Diagnostics copied to the clipboard.":J==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{K("Diagnostics export was cancelled or unavailable.")}finally{O(!1)}}},[_]),Ce=o.useCallback(()=>{f(null),N(!0)},[f]),re=o.useCallback(()=>k?(Z.current?.abort(),!0):x?(N(!1),!0):v?(fe(),!0):h?(G(),!0):!1,[x,G,v,k,h,fe]);gr(re);const me=Zl;return h?e.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:e.jsx("form",{className:"flex-1 overflow-y-auto px-5 py-4",onSubmit:oe,children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:e.jsx(R,{name:"lock",className:"size-[18px]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate typography-ui-label text-foreground",children:h.label}),e.jsx("p",{className:"truncate typography-small text-muted-foreground",children:h.candidates.some(J=>J.kind==="direct")?Ut({candidates:h.candidates}):"via PiChamber Relay"})]})]}),e.jsx("input",{...Aa,value:C,onChange:J=>w(J.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:me}),p?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:p}):null,e.jsx(E,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:m||!C.trim(),children:m?"Connecting...":"Unlock and connect"}),e.jsx(E,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:G,children:"Use another server"})]})})}):e.jsxs(e.Fragment,{children:[k?e.jsx(ec,{onCancel:()=>Z.current?.abort()}):null,S?e.jsx(tc,{}):null,e.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yr,{items:l,layout:"touch",switchLabel:"Connect",pendingId:d,actionsDisabled:u,onSwitch:J=>{n.connectServer(J.id)},onEdit:J=>ce(J.id),onRemove:J=>{n.removeServer(J.id)},emptyMessage:"No saved servers yet."}),p&&!x&&!v?e.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",role:"alert",children:p}):null,a?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(E,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{q()},disabled:_,children:[e.jsx(R,{name:"download",className:"size-[18px]"}),_?"Preparing diagnostics…":"Export diagnostics"]}),V?e.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:V}):null]}):null,v?e.jsxs("form",{className:"space-y-3",onSubmit:be,children:[e.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[e.jsx("h3",{className:"typography-ui-label text-foreground",children:"Edit server"}),e.jsx(E,{type:"button",variant:"ghost",size:"xs",onClick:fe,children:"Cancel"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),e.jsx("input",{...Aa,value:L,onChange:J=>j(J.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:me})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),e.jsx("input",{value:T,onChange:J=>P(J.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:me})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),e.jsx("input",{...Aa,value:A,onChange:J=>g(J.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:me}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),p?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:p}):null,e.jsx(E,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:"Save server"})]}):e.jsx("div",{className:"space-y-2",children:e.jsxs(E,{type:"button",size:"lg",className:"h-12 w-full",onClick:Ce,disabled:u,children:[e.jsx(R,{name:"add",className:"size-[18px]"}),"Add server"]})})]})})}),e.jsx(li,{open:x,onOpenChange:J=>{N(J),J||f(null)},canScanQr:ae,onScanQr:()=>{ie()},onImportLink:ne,importSaving:u,importError:p,onAddManual:pe,manualSaving:u,manualError:p})]})},ed=({onActiveConnectionDeleted:t})=>e.jsx(we,{title:"Servers",description:"Which PiChamber server this app uses. Add other servers to switch between them.",children:e.jsx(Y,{title:"Other PiChamber servers",info:"Servers this app can connect to. Add a server by address, pairing link, or QR code.",divider:!1,settingsItem:"servers.direct-hosts",contentClassName:"space-y-4",children:e.jsx(Zc,{onConnect:()=>{},onActiveConnectionDeleted:t??(()=>{})})})}),td=({onActiveConnectionDeleted:t})=>o.useMemo(()=>Ee(),[])?e.jsx(ed,{onActiveConnectionDeleted:t}):e.jsx(sd,{}),sd=()=>{const t=Bo(),[s,a]=o.useState(!1),[n,r]=o.useState(null),[l,d]=o.useState(""),[i,u]=o.useState(""),[m,p]=o.useState(""),[h,c]=o.useState([]),f=o.useMemo(()=>t.items.filter(L=>!L.isLocal),[t.items]),y=t.remoteHosts;o.useEffect(()=>{y.length!==0&&t.probeAll(t.allHosts)},[y]);const b=o.useCallback(L=>{const j=t.remoteHosts.find(T=>T.id===L);j&&(r(j),d(j.label),u(j.apiUrl||j.url),p(j.clientToken||""),c($o(j.requestHeaders)),t.setError(null))},[t]),v=o.useCallback(async()=>{if(!n)return;(await t.updateServer(n.id,{label:l,url:i,token:m,headers:h})).ok&&r(null)},[n,l,i,m,h,t]);return e.jsxs(we,{title:"Servers",description:"Which PiChamber server this app uses. Add other servers to switch between them.",children:[e.jsxs(Y,{title:"Other PiChamber servers",info:"Servers this app can switch to. Import a pairing link from the other server, or add one by address.",divider:!1,settingsItem:"servers.direct-hosts",contentClassName:"space-y-4",headerAction:e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:e.jsxs(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{t.setError(null),a(!0)},disabled:t.saving,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5","aria-hidden":!0}),"Add server"]})}),children:[t.loading?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading servers..."}):e.jsx(yr,{items:f,emptyMessage:"No other servers added yet.",refreshing:t.probing,actionsDisabled:t.saving,onSwitch:L=>{t.switchToHost(L.id)},onSetDefault:L=>{t.setDefaultServer(L.id)},onEdit:L=>b(L.id),onRemove:L=>{t.removeServer(L.id)}}),t.error?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:t.error}):null]}),e.jsx(li,{open:s,onOpenChange:a,canScanQr:!1,onImportLink:async L=>{(await t.importPairingLink(L)).ok&&a(!1)},importSaving:t.saving,importError:t.error,onAddManual:async L=>{(await t.addManualServer(L)).ok&&a(!1)},manualSaving:t.saving,manualError:t.error}),e.jsx(Wc,{open:!!n,onOpenChange:L=>{L||r(null)},label:l,onLabelChange:d,url:i,onUrlChange:u,token:m,onTokenChange:p,headers:h,onHeadersChange:c,saving:t.saving,error:t.error,onSave:()=>{v()}})]})},Ka=128e3,Va=16384,Xn=["off","minimal","low","medium","high","xhigh","max"],Zn=t=>{const s=(t??"").trim();if(!s||!/^\d+$/.test(s))return;const a=Number(s);return Number.isSafeInteger(a)&&a>0?a:void 0};function ad(t){let s=!1,a=!1;for(const n of t)a?a=!1:s&&n==="\\"?a=!0:n==='"'&&(s=!s);return s}function Wa(t){const s=[];let a=0,n=!1,r=!1;for(let d=0;d<t.length;d+=1){const i=t[d];if(r){r=!1;continue}if(n&&i==="\\"){r=!0;continue}if(i==='"'){n=!n;continue}if(!n&&(i===","||i===`
3
+ `)){const u=t.slice(a,d).trim();u&&s.push(u),a=d+1}}const l=t.slice(a).trim();return l&&s.push(l),s}function nd(t){const s=Wa(t??"");if(s.length===0)return{};const a={};for(const n of s){const r=n.indexOf("="),l=r>=0?n.slice(0,r).trim():void 0,d=l?Xn.find(u=>u===l):Xn.find(u=>n===u||n.startsWith(`${u}-`));if(!d)return{error:"Use off, minimal, low, medium, high, xhigh, or max, optionally as key=value"};if(Object.prototype.hasOwnProperty.call(a,d))return{error:`Only one ${d} value is allowed`};let i=n;if(r>=0){const u=n.slice(r+1).trim();if(!u)return{error:"Thinking values cannot be empty"};if(u==="null")i=null;else if(u.startsWith('"'))try{const m=JSON.parse(u);if(typeof m!="string")throw new Error("not a string");i=m}catch{return{error:"Quoted thinking values must be valid strings"}}else i=u}if(i!==null&&i.length>512)return{error:"Thinking values must be 512 characters or fewer"};a[d]=i}return{value:a}}function ci(t){const s=t.modelId.trim(),a=(t.displayName??"").trim(),n=Zn(t.contextWindowText),r=Zn(t.maxTokensText),l=nd(t.thinkingLevelMapText),d={...s?s.length>512?{modelId:"Use 512 characters or fewer"}:{}:{modelId:"Required"},...a.length>512?{displayName:"Use 512 characters or fewer"}:{},...(t.contextWindowText??"").trim()&&n===void 0?{contextWindow:"Enter a positive whole number"}:{},...(t.maxTokensText??"").trim()&&r===void 0?{maxTokens:"Enter a positive whole number"}:{},...l.error?{thinkingLevelMap:l.error}:{},...l.value&&!t.supportsThinking?{thinkingLevelMap:"Enable Supports thinking to add thinking levels"}:{}};if(Object.values(d).some(Boolean))return{errors:d};const i=[...t.inputText?["text"]:[],...t.inputImage?["image"]:[]];return{errors:d,result:{id:s,...a?{name:a}:{},...n!==void 0?{contextWindow:n}:{},...r!==void 0?{maxTokens:r}:{},...i.length>0?{input:i}:{},...t.supportsThinking?{reasoning:!0}:{},...l.value?{thinkingLevelMap:l.value}:{}}}}const rd="@ai-sdk/openai-compatible",id=/^[a-z0-9][a-z0-9-_]*$/,od=/^https?:\/\//,ld=/^\{env:([^}]+)\}$/,cd=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function di(t){return cd.some(s=>s===t)}let dd=0;const fn=()=>`row-${dd++}`,Ys=()=>({row:fn(),advancedOpen:!1,modelId:"",displayName:"",contextWindowText:"",maxTokensText:"",inputText:!1,inputImage:!1,supportsThinking:!1,thinkingLevelMapText:""}),gn=()=>({row:fn(),key:"",value:""}),ud=()=>({providerID:"",name:"",baseURL:"",api:"openai-completions",apiKey:"",models:[Ys()],headers:[gn()]});function pd(t){const s=t.trim();if(!s)return{};const n=s.match(ld)?.[1]?.trim();return n?{env:n}:{key:s}}function md(t){const s=t.options&&typeof t.options=="object"?t.options:{},a=typeof s.baseURL=="string"?s.baseURL:"",n=s.headers&&typeof s.headers=="object"&&!Array.isArray(s.headers)?s.headers:{},r=Object.entries(n).filter(m=>typeof m[0]=="string"&&typeof m[1]=="string").map(([m,p])=>({row:fn(),key:m,value:p})),l=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([m,p])=>({...p&&typeof p=="object"&&!Array.isArray(p)?p:{},id:m,name:p&&typeof p=="object"&&"name"in p&&typeof p.name=="string"?p.name:m})):[],d=l.length>0?l.map(m=>({...Ys(),modelId:typeof m?.id=="string"?m.id:"",displayName:typeof m?.name=="string"?m.name:"",contextWindowText:m&&"contextWindow"in m&&typeof m.contextWindow=="number"?String(m.contextWindow):"",maxTokensText:m&&"maxTokens"in m&&typeof m.maxTokens=="number"?String(m.maxTokens):"",inputText:!!(m&&"input"in m&&Array.isArray(m.input)&&m.input.includes("text")),inputImage:!!(m&&"input"in m&&Array.isArray(m.input)&&m.input.includes("image")),supportsThinking:!!(m&&("supportsThinking"in m&&m.supportsThinking===!0||"reasoning"in m&&m.reasoning===!0)),thinkingLevelMapText:m&&"thinkingLevelMap"in m&&m.thinkingLevelMap?Object.entries(m.thinkingLevelMap).map(([p,h])=>`${p}=${h===null?"null":JSON.stringify(h)}`).join(`
4
+ `):""})):[Ys()],i=Array.isArray(t.env)?t.env.find(m=>typeof m=="string"&&m.trim().length>0)?.trim():void 0,u=typeof t.api=="string"&&di(t.api)?t.api:"openai-completions";return{providerID:t.id,name:typeof t.name=="string"&&t.name.trim()?t.name:t.id,baseURL:a,api:u,apiKey:i?`{env:${i}}`:"",models:d,headers:r.length>0?r:[gn()]}}function hd(t){const s=t.form.providerID.trim(),a=t.form.name.trim(),n=t.form.baseURL.trim(),{env:r,key:l}=pd(t.form.apiKey),d=t.disabledProviders??[],i=t.editingProviderID?.trim(),u=s?id.test(s)?void 0:"Use lowercase letters, numbers, hyphens, or underscores":"Provider ID is required",m=a?void 0:"Display name is required",p=n?od.test(n)?void 0:"Base URL must start with http:// or https://":"Base URL is required",c=!!(r||l||i&&t.allowExistingAuth&&i===s)?void 0:"API key or {env:VAR_NAME} is required",f=d.includes(s),b=u||!!(i&&i===s)?void 0:t.existingProviderIDs.has(s)&&!f?"A provider with this ID is already connected":void 0,v=new Set,L=t.form.models.map(k=>{const I=ci(k),S=k.modelId.trim();return S&&v.has(S)?{errors:{...I.errors,modelId:"Duplicate"}}:(S&&v.add(S),I)}),j=L.map(k=>k.errors),T=L.every(k=>k.result!==void 0),P=Object.fromEntries(L.flatMap(k=>k.result?[[k.result.id,k.result]]:[])),A=new Set,g=t.form.headers.map(k=>{const I=k.key.trim(),S=k.value.trim();return!I&&!S?{}:{key:I?A.has(I.toLowerCase())?"Duplicate":void A.add(I.toLowerCase()):"Required",value:S?void 0:"Required"}}),C=g.every(k=>!k.key&&!k.value),w=Object.fromEntries(t.form.headers.map(k=>({key:k.key.trim(),value:k.value.trim()})).filter(k=>k.key&&k.value).map(k=>[k.key,k.value])),x={providerID:u??b,name:m,baseURL:p,apiKey:c};return!u&&!b&&!m&&!p&&!c&&T&&C?{err:x,models:j,headers:g,result:{providerID:s,name:a,apiKey:l,config:{npm:rd,name:a,api:t.form.api,...r?{env:[r]}:{},options:{baseURL:n,...Object.keys(w).length>0?{headers:w}:{}},models:P}}}:{err:x,models:j,headers:g}}const ui=({value:t,onChange:s,disabled:a=!1,hasError:n=!1,id:r})=>{const[l,d]=o.useState(""),i=Wa(t),u=()=>{const m=Wa(l);if(m.length===0)return;const p=[...i];for(const h of m)p.includes(h)||p.push(h);s(p.join(`
5
+ `)),d("")};return e.jsxs("div",{className:"space-y-2",children:[i.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5","aria-label":"Configured thinking levels",children:i.map(m=>e.jsxs(E,{type:"button",variant:"chip",size:"xs",disabled:a,"aria-label":`Remove ${m}`,onClick:()=>s(i.filter(p=>p!==m).join(`
6
+ `)),children:[e.jsx("span",{className:"font-mono text-xs normal-case",children:m}),e.jsx(R,{name:"close",className:"size-3","aria-hidden":!0})]},m))}):null,e.jsx(ee,{id:r,value:l,onChange:m=>d(m.target.value),onKeyDown:m=>{(m.key==="Enter"||m.key===","&&!ad(l))&&(m.preventDefault(),u())},onBlur:u,placeholder:"low-effort",className:"h-8 font-mono text-xs",disabled:a,"aria-invalid":n||void 0,"aria-label":"Add thinking level"}),e.jsx("p",{className:at,children:'Press Enter or comma to add a value. Use low-effort for standard values, or low="value" and low=null for explicit mappings.'})]})},cs=({children:t})=>t?e.jsx("p",{role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:t}):null,fd=({model:t,errors:s,busy:a,removable:n,onChange:r,onRemove:l})=>{const d=`custom-provider-${t.row}`;return e.jsxs("div",{className:"space-y-3 border-b border-border/60 pb-4 last:border-b-0",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ae,htmlFor:`${d}-id`,children:"Model ID"}),e.jsx(ee,{id:`${d}-id`,value:t.modelId,onChange:i=>r("modelId",i.target.value,"modelId"),placeholder:"gpt-4o",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs",disabled:a,"aria-invalid":!!s?.modelId||void 0}),e.jsx(cs,{children:s?.modelId})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,htmlFor:`${d}-name`,children:"Display name"}),e.jsx(ee,{id:`${d}-name`,value:t.displayName,onChange:i=>r("displayName",i.target.value,"displayName"),placeholder:"Same as Model ID",className:"mt-1 h-8 rounded-md px-3",disabled:a,"aria-invalid":!!s?.displayName||void 0}),e.jsx(cs,{children:s?.displayName})]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"icon",className:Qe,disabled:!n||a,onClick:l,"aria-label":"Remove model",children:e.jsx(R,{name:"delete-bin",className:"size-4"})})]}),e.jsxs(E,{type:"button",variant:"ghost",size:"sm",className:"w-full justify-between px-0","aria-expanded":t.advancedOpen,"aria-controls":`${d}-advanced`,onClick:()=>r("advancedOpen",!t.advancedOpen),disabled:a,children:[e.jsx("span",{children:"Advanced settings"}),e.jsx(R,{name:"arrow-down-s",className:H("size-4 transition-transform",t.advancedOpen&&"rotate-180")})]}),t.advancedOpen?e.jsxs("div",{id:`${d}-advanced`,className:"grid grid-cols-1 gap-3 border-t border-border/60 pt-3 @xl:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ae,htmlFor:`${d}-context`,children:"Context window"}),e.jsx(ee,{id:`${d}-context`,value:t.contextWindowText,onChange:i=>r("contextWindowText",i.target.value,"contextWindow"),placeholder:String(Ka),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:a,"aria-invalid":!!s?.contextWindow||void 0}),e.jsx(cs,{children:s?.contextWindow})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,htmlFor:`${d}-max`,children:"Max output tokens"}),e.jsx(ee,{id:`${d}-max`,value:t.maxTokensText,onChange:i=>r("maxTokensText",i.target.value,"maxTokens"),placeholder:String(Va),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:a,"aria-invalid":!!s?.maxTokens||void 0}),e.jsx(cs,{children:s?.maxTokens})]}),e.jsxs("div",{className:"@xl:col-span-2",children:[e.jsx("span",{className:Ae,children:"Input modalities"}),e.jsxs("div",{className:"mt-1 space-y-1.5",children:[e.jsx(ke,{checked:!!t.inputText,onChange:i=>r("inputText",i),label:"Text",ariaLabel:"Text input",disabled:a}),e.jsx(ke,{checked:!!t.inputImage,onChange:i=>r("inputImage",i),label:"Image",ariaLabel:"Image input",disabled:a})]})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(ke,{checked:!!t.supportsThinking,onChange:i=>r("supportsThinking",i,"thinkingLevelMap"),label:"Supports thinking",ariaLabel:"Supports thinking",disabled:a,info:"Pi defaults to off. Unchecked omits this setting."}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,htmlFor:`${d}-thinking`,children:"Thinking levels"}),e.jsx(ui,{id:`${d}-thinking`,value:t.thinkingLevelMapText??"",onChange:i=>r("thinkingLevelMapText",i,"thinkingLevelMap"),disabled:a||!t.supportsThinking,hasError:!!s?.thinkingLevelMap}),e.jsx(cs,{children:s?.thinkingLevelMap})]})]})]}):null]})},gd=({existingProviderIDs:t,disabledProviders:s=[],busy:a=!1,mode:n="create",initialValues:r,allowExistingAuth:l=!1,authFailureHint:d=null,onSubmit:i,onCancel:u,onDisconnect:m})=>{const p=n==="edit",[h,c]=o.useState(()=>r??ud()),[f,y]=o.useState({}),[b,v]=o.useState([]),[L,j]=o.useState([]),T=o.useRef(null);o.useEffect(()=>{r&&(p&&T.current===r.providerID||(T.current=p?r.providerID:null,c(r),y({}),v([]),j([])))},[r,p]);const P=(w,x)=>{c(N=>({...N,[w]:x})),y(N=>({...N,[w]:void 0}))},A=(w,x,N,k)=>{c(I=>({...I,models:I.models.map((S,z)=>z===w?{...S,[x]:N}:S)})),k&&v(I=>{const S=[...I];return S[w]={...S[w]??{},[k]:void 0},S})},g=(w,x,N)=>{c(k=>({...k,headers:k.headers.map((I,S)=>S===w?{...I,[x]:N}:I)})),j(k=>{const I=[...k];return I[w]={...I[w]??{},[x]:void 0},I})},C=async w=>{if(w.preventDefault(),a)return;const x=hd({form:h,existingProviderIDs:t,disabledProviders:s,editingProviderID:p?h.providerID:void 0,allowExistingAuth:p&&l});y(x.err),v(x.models),j(x.headers),x.result&&await i(x.result)};return e.jsxs("form",{onSubmit:C,className:"grid grid-cols-1 @3xl:grid-cols-2 @3xl:gap-x-10",children:[e.jsxs(Y,{divider:!1,settingsItem:"providers.custom",className:"@3xl:col-span-2",contentClassName:vt,children:[e.jsx("p",{className:at,children:"Add a provider with a base URL, API format, credentials, and model list. Saved to Pi so it is available in chat like any other provider."}),d?e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:d}):null,e.jsxs(zt,{children:[e.jsxs(Ie,{label:"Provider ID",info:"Lowercase letters, numbers, hyphens, and underscores. Used as the Pi provider id.",children:[e.jsx(ee,{value:h.providerID,onChange:w=>P("providerID",w.target.value),placeholder:"my-provider",className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:!p,disabled:p||a,"aria-invalid":!!f.providerID,"aria-label":"Provider ID"}),f.providerID?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.providerID}):null]}),e.jsxs(Ie,{label:"Display name",info:"Shown in the provider and model pickers.",children:[e.jsx(ee,{value:h.name,onChange:w=>P("name",w.target.value),placeholder:"My Provider",className:"h-8 rounded-md px-3","aria-invalid":!!f.name,"aria-label":"Display name"}),f.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.name}):null]}),e.jsxs(Ie,{label:"Base URL",info:"Provider API base URL. Must start with http:// or https://.",children:[e.jsx(ee,{value:h.baseURL,onChange:w=>P("baseURL",w.target.value),placeholder:"https://api.example.com/v1",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!f.baseURL,"aria-label":"Base URL"}),f.baseURL?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.baseURL}):null]}),e.jsx(Ie,{label:"API format",info:"Select the request and response format implemented by this provider.",children:e.jsxs(_e,{value:h.api,onValueChange:w=>{di(w)&&c(x=>({...x,api:w}))},disabled:a,children:[e.jsx(ze,{size:Be,className:bt,"aria-label":"API format",children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"openai-completions",children:"OpenAI Chat Completions"}),e.jsx(ye,{value:"openai-responses",children:"OpenAI Responses"}),e.jsx(ye,{value:"anthropic-messages",children:"Anthropic Messages"}),e.jsx(ye,{value:"google-generative-ai",children:"Google Generative AI"})]})]})}),e.jsxs(Ie,{label:"API key",info:p&&l?"Leave blank to keep the existing credential, or enter a new key / {env:VAR_NAME}.":"Stored in Pi authentication, not by PiChamber. Use {env:VAR_NAME} to read a key from the environment instead.",children:[e.jsx(ee,{type:"password",value:h.apiKey,onChange:w=>P("apiKey",w.target.value),placeholder:p&&l?"Leave blank to keep existing key":"sk-... or {env:VAR_NAME}",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!f.apiKey,"aria-label":"API key"}),f.apiKey?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.apiKey}):null]})]})]}),e.jsxs(Y,{title:"Models",contentClassName:vt,children:[h.models.map((w,x)=>e.jsx(fd,{model:w,errors:b[x],busy:a,removable:h.models.length>1,onChange:(N,k,I)=>A(x,N,k,I),onRemove:()=>{h.models.length<=1||(c(N=>({...N,models:N.models.filter((k,I)=>I!==x)})),v(N=>N.filter((k,I)=>I!==x)))}},w.row)),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{c(w=>({...w,models:[...w.models,Ys()]})),v(w=>[...w,{}])},children:"Add model"})]}),e.jsxs(Y,{title:"Headers",contentClassName:vt,children:[e.jsx("p",{className:at,children:"Optional request headers sent with every call."}),h.headers.map((w,x)=>e.jsx("div",{className:`${es} space-y-2`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ae,children:"Header name"}),e.jsx(ee,{value:w.key,onChange:N=>g(x,"key",N.target.value),placeholder:"X-Custom-Header",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header name"}),L[x]?.key?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:L[x]?.key}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:Ae,children:"Header value"}),e.jsx(ee,{value:w.value,onChange:N=>g(x,"value",N.target.value),placeholder:"value",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header value"}),L[x]?.value?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:L[x]?.value}):null]})]}),e.jsx(E,{type:"button",variant:"ghost",size:"icon",className:Qe,disabled:h.headers.length<=1,onClick:()=>{h.headers.length<=1||(c(N=>({...N,headers:N.headers.filter((k,I)=>I!==x)})),j(N=>N.filter((k,I)=>I!==x)))},"aria-label":"Remove header",children:e.jsx(R,{name:"delete-bin",className:"size-4"})})]})},w.row)),e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{c(w=>({...w,headers:[...w.headers,gn()]})),j(w=>[...w,{}])},children:"Add header"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4 @3xl:col-span-2",children:[u?e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:u,disabled:a,children:"Back"}):null,m?e.jsx(E,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{m()},disabled:a,children:"Disconnect"}):null,e.jsx(E,{type:"submit",size:"xs",className:"!font-normal",disabled:a,children:a?"Saving...":p?"Update provider":"Save provider"})]})]})},Ye=()=>({runtimeKey:Ve()}),Ls="__pi_fallback__",xd=(t,s)=>{const a=[...t];return s&&!a.includes(s)&&a.push(s),a},vd=t=>[...t].sort((s,a)=>s.authenticated!==a.authenticated?s.authenticated?-1:1:s.label.localeCompare(a.label,void 0,{sensitivity:"base"})),bd=t=>{const s=t&&typeof t=="object"&&"code"in t?String(t.code):void 0;return s==="INVALID_ARGUMENT"?"Could not add this model. It may already exist, or this provider cannot accept manual models.":s==="PROVIDER_NOT_FOUND"?"This provider is no longer available. Refresh providers and try again.":s==="PI_MODEL_CONFIG_INVALID"?"Pi model configuration is invalid.":s?`Could not add model (${s}). Try again.`:"Could not add model. Try again."},yd=({open:t,onOpenChange:s,providerId:a,providerLabel:n,onAdded:r,initialAdvancedOpen:l=!1})=>{const[d,i]=o.useState(""),[u,m]=o.useState(""),[p,h]=o.useState(""),[c,f]=o.useState(""),[y,b]=o.useState(!1),[v,L]=o.useState(!1),[j,T]=o.useState(!1),[P,A]=o.useState(""),[g,C]=o.useState(l),[w,x]=o.useState({}),[N,k]=o.useState(null),[I,S]=o.useState(!1);o.useEffect(()=>{t&&(i(""),m(""),h(""),f(""),b(!1),L(!1),T(!1),A(""),C(l),x({}),k(null),S(!1))},[t,a,l]);const z=K=>{I&&!K||s(K)},_=K=>{x(Z=>Z[K]===void 0?Z:{...Z,[K]:void 0})},O=async K=>{if(K.preventDefault(),I)return;const Z=ci({modelId:d,displayName:u,contextWindowText:p,supportsThinking:j,maxTokensText:c,inputText:y,inputImage:v,thinkingLevelMapText:P});x(Z.errors);const ae=Z.result;if(!ae){(Z.errors.displayName||Z.errors.contextWindow||Z.errors.maxTokens||Z.errors.thinkingLevelMap)&&C(!0),k(null);return}S(!0),k(null);try{const fe=await Me.addProviderModel({providerId:a,model:ae},Ye()),ce=sa(fe);ce?$.info(Xt("Model")):$.success("Model added"),s(!1),await r?.({deferred:ce,providerId:a,modelId:ae.id})}catch(fe){k(bd(fe))}finally{S(!1)}},V=(K,Z,ae)=>ae?`${K} ${Z}`:K;return e.jsx(jt,{open:t,onOpenChange:z,children:e.jsxs(kt,{className:H(g?"max-w-3xl":"max-w-md","w-full @container p-4 sm:p-6"),children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Add model"}),e.jsx(St,{children:`Add a manual model to ${n}. Only the Model ID is required.`})]}),e.jsxs("form",{onSubmit:O,className:"@container space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("label",{className:Ae,htmlFor:"add-model-id",children:"Model ID"}),e.jsx("span",{className:"text-xs text-[var(--status-error)]","aria-hidden":!0,children:"*"})]}),e.jsx(ee,{id:"add-model-id",value:d,onChange:K=>{i(K.target.value),_("modelId")},placeholder:"my-model",className:"h-8 font-mono text-xs",autoFocus:!0,disabled:I,"aria-invalid":!!w.modelId||void 0,"aria-describedby":w.modelId?"add-model-id-error":void 0,"aria-label":"Model ID","aria-required":"true"}),w.modelId?e.jsx("p",{id:"add-model-id-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:w.modelId}):null]}),e.jsxs("div",{children:[e.jsxs(E,{type:"button",variant:"ghost",size:"sm",id:"add-model-advanced-toggle","aria-expanded":g,"aria-controls":"add-model-advanced",onClick:()=>C(K=>!K),className:"w-full justify-between px-0",children:[e.jsx("span",{children:"Advanced settings"}),e.jsx(R,{name:"arrow-down-s",className:H("size-4 transition-transform",g&&"rotate-180"),"aria-hidden":!0})]}),g?e.jsxs("div",{id:"add-model-advanced",role:"region","aria-labelledby":"add-model-advanced-toggle",className:"grid grid-cols-1 gap-4 border-t border-border/60 pt-4 @xl:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("label",{className:Ae,htmlFor:"add-model-label",children:"Display name"}),e.jsx(ys,{contentClassName:"max-w-xs",children:"Shown in pickers."})]}),e.jsx(ee,{id:"add-model-label",value:u,onChange:K=>{m(K.target.value),_("displayName")},placeholder:"Same as Model ID",className:"h-8",disabled:I,"aria-invalid":!!w.displayName||void 0,"aria-describedby":V("add-model-label-hint","add-model-label-error",!!w.displayName),"aria-label":"Display name"}),e.jsx("p",{id:"add-model-label-hint",className:H(at,"mt-1"),children:"Defaults to the Model ID. Leave empty to omit."}),w.displayName?e.jsx("p",{id:"add-model-label-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:w.displayName}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Ae,htmlFor:"add-model-context",children:"Context window"})}),e.jsx(ee,{id:"add-model-context",value:p,onChange:K=>{h(K.target.value),_("contextWindow")},placeholder:String(Ka),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:I,"aria-invalid":!!w.contextWindow||void 0,"aria-describedby":V("add-model-context-hint","add-model-context-error",!!w.contextWindow),"aria-label":"Context window"}),e.jsx("p",{id:"add-model-context-hint",className:H(at,"mt-1"),children:`Pi uses ${Ka.toLocaleString()} when empty.`}),w.contextWindow?e.jsx("p",{id:"add-model-context-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:w.contextWindow}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Ae,htmlFor:"add-model-max-tokens",children:"Max output tokens"})}),e.jsx(ee,{id:"add-model-max-tokens",value:c,onChange:K=>{f(K.target.value),_("maxTokens")},placeholder:String(Va),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:I,"aria-invalid":!!w.maxTokens||void 0,"aria-describedby":V("add-model-max-tokens-hint","add-model-max-tokens-error",!!w.maxTokens),"aria-label":"Max output tokens"}),e.jsx("p",{id:"add-model-max-tokens-hint",className:H(at,"mt-1"),children:`Pi uses ${Va.toLocaleString()} when empty.`}),w.maxTokens?e.jsx("p",{id:"add-model-max-tokens-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:w.maxTokens}):null]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("span",{className:Ae,id:"add-model-input-label",children:"Input modalities"}),e.jsx(ys,{contentClassName:"max-w-xs",children:"Select one or both; leave both off to omit."})]}),e.jsxs("div",{role:"group","aria-labelledby":"add-model-input-label","aria-describedby":"add-model-input-hint",className:"space-y-1.5",children:[e.jsx(ke,{checked:y,onChange:K=>b(K),label:"Text",ariaLabel:"Text input",disabled:I}),e.jsx(ke,{checked:v,onChange:K=>L(K),label:"Image",ariaLabel:"Image input",disabled:I})]}),e.jsx("p",{id:"add-model-input-hint",className:H(at,"mt-1"),children:"Defaults to text when omitted."})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(ke,{checked:j,onChange:K=>{T(K),_("thinkingLevelMap")},label:"Supports thinking",ariaLabel:"Supports thinking",disabled:I,info:"Pi defaults to off. Checked sends true; unchecked omits the field."}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Ae,htmlFor:"add-model-thinking-map",children:"Thinking levels"})}),e.jsx(ui,{id:"add-model-thinking-map",value:P,onChange:K=>{A(K),_("thinkingLevelMap")},disabled:I||!j,hasError:!!w.thinkingLevelMap}),e.jsx("p",{id:"add-model-thinking-map-hint",className:H(at,"mt-1"),children:"Requires Supports thinking."}),w.thinkingLevelMap?e.jsx("p",{id:"add-model-thinking-map-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:w.thinkingLevelMap}):null]})]})]}):null]}),N?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:N}):null,e.jsxs(ta,{className:"gap-2",children:[e.jsx(E,{type:"button",variant:"ghost",size:"sm",onClick:()=>z(!1),disabled:I,children:"Cancel"}),e.jsx(E,{type:"submit",size:"sm",disabled:I,children:I?"Adding…":"Add model"})]})]})]})})},wd=({provider:t,onSelect:s})=>{const a=t.models.length,n=a===1?"1 model":`${a} models`,{hasLogo:r}=Ko(t.id);return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.label} provider, ${n}${t.authenticated?", authenticated":""}`,className:H("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r?e.jsx(wr,{providerId:t.id,className:"size-8 shrink-0 rounded-md object-contain"}):e.jsx("span",{className:"inline-flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground",children:e.jsx(R,{name:"cloud",className:"size-4","aria-hidden":!0})}),t.authenticated?e.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro font-medium text-[var(--status-success)]",children:[e.jsx(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Connected"]}):null]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:t.label}),e.jsx("div",{className:"truncate font-mono typography-micro text-muted-foreground",children:t.id})]}),e.jsxs("div",{className:"flex items-center gap-1.5 typography-micro text-muted-foreground",children:[e.jsx(R,{name:"stack",className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"tabular-nums",children:n})]})]})},jd=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,a)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"size-8 shrink-0 animate-pulse rounded-md bg-muted"}),e.jsx("div",{className:"h-4 w-16 animate-pulse rounded bg-muted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-1/2 animate-pulse rounded bg-muted"})]}),e.jsx("div",{className:"h-3 w-16 animate-pulse rounded bg-muted"})]},a))}),ds="__pi_custom_provider__",Ha=ml(t=>({selectedProviderId:null,setSelectedProviderId:s=>t(a=>a.selectedProviderId===s?a:{selectedProviderId:s})})),kd=(t,s,a)=>t.some(n=>n.providerID===s&&n.modelID===a),pi=o.memo(({providerId:t,model:s,storedLevel:a,isBusy:n,isHidden:r,isConnected:l,onThinkingChange:d,onToggleHidden:i})=>{const u=o.useMemo(()=>jr(s),[s]),p=o.useMemo(()=>kr(u),[u])||a!==void 0,h=o.useMemo(()=>xd(u,a),[u,a]),c=a??Ls;return e.jsxs("div",{className:H("flex min-w-0 items-center gap-2 py-2",r&&"opacity-60"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",children:s.label||s.id}),p?e.jsxs(_e,{value:c,onValueChange:f=>d(t,s.id,f===Ls?null:f),disabled:n,children:[e.jsx(ze,{size:"sm",className:"w-auto min-w-[4.5rem] max-w-[8rem] shrink-0 border-0 bg-transparent px-1.5 shadow-none gap-1 text-muted-foreground hover:bg-muted hover:text-foreground data-[placeholder]:text-muted-foreground","aria-label":`Thinking for ${s.label||s.id}`,children:e.jsx(Oe,{children:f=>f===Ls?"Default":f&&Nr(f)?Ws[f]:f??""})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:Ls,children:"Default"}),h.map(f=>e.jsx(ye,{value:f,children:Ws[f]},f))]})]}):null,s.supportsThinking?e.jsx(R,{name:"brain-ai-3",className:"size-4 shrink-0 text-muted-foreground","aria-label":"Reasoning"}):null,typeof s.contextWindow=="number"?e.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:s.contextWindow}):null,l?e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>i(t,s.id),"aria-label":r?"Show model in pickers":"Hide model from pickers",title:r?"Show model in pickers":"Hide model from pickers",children:e.jsx(R,{name:r?"eye":"eye-off",className:"size-4"})}):null]})});pi.displayName="ProviderModelRow";const Nd=t=>{if(!t)return null;try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"?s:null}catch{return null}},Cd=({login:t,authUrl:s,promptValue:a,onPromptValueChange:n,onSubmit:r,busy:l})=>{const[d,i]=o.useState(!1),u=t.prompt?.placeholder,m=Nd(u)!==null,p=a.trim(),h=m&&u&&/^https?:\/\//i.test(p)&&!p.startsWith(u);o.useEffect(()=>{if(!d)return;const y=window.setTimeout(()=>i(!1),2e3);return()=>window.clearTimeout(y)},[d]);const c=async()=>{(await aa(s)).ok?i(!0):$.error("Could not copy the sign-in link")},f=y=>{y.preventDefault(),!(l||p.length===0||h)&&r()};return e.jsxs("div",{className:"space-y-5 border-t border-[var(--surface-subtle)] pt-4",children:[e.jsxs(Ie,{label:"1. Sign in",description:"Open the sign-in page and finish signing in.",children:[e.jsx(E,{asChild:!0,size:"sm",children:e.jsxs("a",{href:s,target:"_blank",rel:"noreferrer",children:[e.jsx(R,{name:"external-link",className:"size-4"}),"Open sign-in page"]})}),e.jsx(E,{variant:"ghost",size:"icon",className:Qe,onClick:()=>{c()},"aria-label":d?"Sign-in link copied":"Copy sign-in link",title:d?"Copied":"Copy sign-in link",children:e.jsx(R,{name:d?"check":"file-copy",className:"size-4"})})]}),e.jsxs("form",{onSubmit:f,children:[e.jsxs(Ie,{label:m?"2. Paste the redirect URL":"2. Paste the code",description:m?e.jsxs(e.Fragment,{children:["After you sign in, the browser opens a page starting with"," ",e.jsx("code",{className:"break-all text-foreground",children:u}),". That page may not load, which is expected. Copy the full address from the address bar and paste it here."]}):t.prompt?.message||"Copy the code shown after you sign in and paste it here.",controlClassName:"max-w-[32rem]",children:[e.jsx(ee,{className:"h-8 min-w-0 flex-1 rounded-md px-3",value:a,onChange:y=>n(y.target.value),placeholder:m?`${u}?code=…`:t.prompt?.placeholder,"aria-label":m?"Redirect URL":"Authorization code","aria-invalid":h?!0:void 0,autoComplete:"off",spellCheck:!1}),e.jsx(E,{type:"submit",size:"sm",disabled:l||p.length===0||!!h,children:l?"Connecting...":"Connect"})]}),h?e.jsxs("p",{className:"mt-2 typography-meta text-[var(--status-error)]",children:["This isn't the redirect address. Paste the URL that starts with ",u,"."]}):null]}),e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(R,{name:"loader-4",className:"size-4 shrink-0 animate-spin"}),m?"Waiting for sign-in. If your browser runs on the same machine as PiChamber, this finishes on its own.":"Waiting for the code…"]})]})},Sd=t=>{const{login:s,promptValue:a,onPromptValueChange:n,onSubmit:r,busy:l}=t;return s.authUrl&&s.prompt?.type==="manual_code"?e.jsx(Cd,{...t,authUrl:s.authUrl.url}):e.jsxs("div",{className:"space-y-3 border-t border-[var(--surface-subtle)] pt-3",children:[s.authUrl?e.jsx("a",{className:"typography-meta text-[var(--primary-base)] underline",href:s.authUrl.url,target:"_blank",rel:"noreferrer",children:s.authUrl.instructions||"Open"}):null,s.deviceCode?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("span",{className:"mr-2",children:"Device code"}),e.jsx("code",{className:"text-foreground",children:s.deviceCode.userCode}),e.jsx("a",{className:"ml-2 text-[var(--primary-base)] underline",href:s.deviceCode.verificationUri,target:"_blank",rel:"noreferrer",children:"Open"})]}):null,s.prompt?e.jsxs(Pe,{label:s.prompt.message||"Copy the authorization code from your browser and paste it here.",children:[s.prompt.type==="select"&&s.prompt.options?e.jsxs(_e,{value:a,onValueChange:n,children:[e.jsx(ze,{size:Be,className:ra,children:e.jsx(Oe,{})}),e.jsx(Ue,{children:s.prompt.options.map(d=>e.jsx(ye,{value:d.id,children:d.label},d.id))})]}):e.jsx(ee,{type:s.prompt.type==="secret"?"password":"text",value:a,onChange:d=>n(d.target.value),placeholder:s.prompt.placeholder,autoComplete:"off"}),e.jsx(E,{size:"sm",onClick:r,disabled:l||a.length===0,children:"Continue"})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Waiting for authorization…"})]})};function Td(){const t=Ha(F=>F.selectedProviderId),s=Ha(F=>F.setSelectedProviderId),a=W(F=>F.hiddenModels),n=W(F=>F.toggleHiddenModel),r=W(F=>F.hideAllModels),l=W(F=>F.showAllModels),d=Fe(F=>F.providers),i=Fe(F=>F.settingsDefaultThinkingByModel),u=Fe(F=>F.setSettingsDefaultThinkingByModel),m=Fe(F=>F.setSettingsDefaultThinking),[p,h]=o.useState(null),[c,f]=o.useState(""),[y,b]=o.useState(""),[v,L]=o.useState(null),[j,T]=o.useState(!1),[P,A]=o.useState(null),[g,C]=o.useState(!1),[w,x]=o.useState(!1),[N,k]=o.useState(!1),[I,S]=o.useState(!1),[z,_]=o.useState(null),[O,V]=o.useState(new Set),[K,Z]=o.useState(""),[ae,fe]=o.useState(80),[ce,be]=o.useState(null),ie=o.useCallback(async()=>{const{providers:F}=await Me.listProviders(Ye());h(F),x(!1),Fe.getState().loadProviders({source:"providersPage:refresh"})},[]),ne=o.useCallback(async()=>{if(!N){k(!0);try{const{providers:F}=await Me.refreshProviders(Ye());h(F),x(!1);const Q=Fe.getState();Q.invalidateProviderCache(),Q.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:F}))}catch{x(!0)}finally{k(!1)}}},[N]),pe=o.useCallback(async()=>{if(!I){S(!0),_(null);try{const{providers:F}=await Me.refreshProviders(Ye());h(F),x(!1),_("success");const Q=Fe.getState();Q.invalidateProviderCache(),Q.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:F})),$.success("Model catalog refreshed")}catch{x(!0),_("error"),$.error("Could not refresh model catalog")}finally{S(!1)}}},[I]),oe=o.useCallback(async(F,Q)=>{if(F){be(Q);return}const de=Ye();try{const{providers:te}=await Me.listProviders(de);if(de.runtimeKey!==Ve())return;h(te),x(!1);const ge=Fe.getState();ge.invalidateProviderCache(),ge.loadProviders({source:"providersPage:addModel"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:te}))}catch{if(de.runtimeKey!==Ve())return;$.error("Model added, but providers could not be refreshed")}},[]);o.useEffect(()=>{!ce||!d.some(Q=>Q.id===ce.providerId&&Q.models.some(de=>de.id===ce.modelId))||(be(null),oe(!1,ce))},[d,ce,oe]),o.useEffect(()=>{let F=!0;return ie().catch(()=>{F&&x(!0)}),()=>{F=!1}},[ie]),o.useEffect(()=>{let F=!0;const Q=Ye();return Me.getSettings(Q).then(de=>{if(!F||Q.runtimeKey!==Ve())return;const te=de.pichamber.defaultThinkingByModel??{},ge=de.pichamber.defaultThinking,$e=Fe.getState().settingsDefaultThinkingByModel;(()=>{const We=Object.keys($e),Xe=Object.keys(te);if(We.length!==Xe.length)return!1;for(const mt of We)if($e[mt]!==te[mt])return!1;return!0})()||u(te),ge!==Fe.getState().settingsDefaultThinking&&m(ge)}).catch(()=>{}),()=>{F=!1}},[m,u]),o.useEffect(()=>{if(!v||v.state!=="pending")return;let F=!0;const Q=window.setInterval(()=>{Me.getProviderLogin(v.providerId,v.id,Ye()).then(de=>{F&&(L(de.login),de.login.state==="complete"&&ie().catch(()=>x(!0)))}).catch(()=>{F&&L(de=>de&&{...de,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})})},1e3);return()=>{F=!1,window.clearInterval(Q)}},[v,ie]),o.useEffect(()=>{if(!v||v.state!=="complete"||!p)return;p.find(Q=>Q.id===v.providerId)?.authenticated===!0&&L(null)},[v,p]),o.useEffect(()=>{const F=Q=>{const de=Q.detail;Array.isArray(de)&&(h(de),x(!1))};return window.addEventListener("pichamber:providers-refreshed",F),()=>window.removeEventListener("pichamber:providers-refreshed",F)},[]);const G=p?.find(F=>F.id===t)??null,q=G?.id;o.useEffect(()=>{if(!q){A(null);return}let F=!0;return Me.getProviderConfig(q,Ye()).then(Q=>{F&&A(Q.config)}).catch(()=>{F&&A(null)}),()=>{F=!1}},[q]);const Ce=o.useCallback(async(F,Q,de)=>{const te=Hs({providerId:F,modelId:Q});if(!te)return;const ge=Ye(),$e=Fe.getState().settingsDefaultThinkingByModel,lt={...$e};de===null?delete lt[te]:lt[te]=de,u(lt),V(We=>new Set(We).add(te)),it("saving");try{const We=await Me.setPiChamberDefaults({defaultThinkingByModel:{[te]:de}},ge);if(ge.runtimeKey!==Ve()){u($e);return}const Xe=We.pichamber.defaultThinkingByModel??{};u(Xe),We.pichamber.defaultThinking!==void 0&&m(We.pichamber.defaultThinking),it("saved")}catch{ge.runtimeKey===Ve()&&u($e),it("error")}finally{V(We=>{const Xe=new Set(We);return Xe.delete(te),Xe})}},[m,u]),re=o.useCallback((F,Q,de)=>{Ce(F,Q,de)},[Ce]),me=o.useCallback((F,Q)=>{n(F,Q)},[n]);o.useEffect(()=>{fe(80)},[q]);const J=o.useMemo(()=>G?G.models.slice(0,ae):[],[G,ae]),B=G?G.models.length>J.length:!1,U=o.useMemo(()=>p?vd(p):[],[p]),X=o.useMemo(()=>{const F=K.trim().toLowerCase();return F?U.filter(Q=>{const de=Q.label.toLowerCase(),te=Q.id.toLowerCase();return de.includes(F)||te.includes(F)}):U},[U,K]);return{selectedProviderId:t,setSelectedProviderId:s,hiddenModels:a,toggleHiddenModel:n,hideAllModels:r,showAllModels:l,settingsDefaultThinkingByModel:i,setSettingsDefaultThinkingByModel:u,setSettingsDefaultThinking:m,providers:p,setProviders:h,apiKey:c,setApiKey:f,promptValue:y,setPromptValue:b,login:v,setLogin:L,customEditing:j,setCustomEditing:T,providerConfig:P,setProviderConfig:A,busy:g,setBusy:C,failed:w,setFailed:x,refreshing:N,setRefreshing:k,refreshingCatalog:I,setRefreshingCatalog:S,catalogRefreshFeedback:z,setCatalogRefreshFeedback:_,thinkingBusyKeys:O,setThinkingBusyKeys:V,providerQuery:K,setProviderQuery:Z,visibleCap:ae,setVisibleCap:fe,refresh:ie,refreshProviders:ne,refreshCatalog:pe,refreshAfterModelAdd:oe,provider:G,providerId:q,sortedProviders:U,filteredProviders:X,displayModels:J,hasMore:B,saveCustomProvider:async F=>{C(!0);try{const Q=await Me.setProviderModels({providerId:F.providerID,label:F.name,baseUrl:F.config.options.baseURL,api:F.config.api,models:Object.values(F.config.models).map(de=>({...de,providerId:F.providerID,...de.name?{label:de.name}:{}})),...F.config.options.headers?{headers:F.config.options.headers}:{},...F.config.env?.[0]?{apiKeyReference:`{env:${F.config.env[0]}}`}:{}},Ye());if(sa(Q)){$.info("Provider configuration saved. Connect it after active sessions are idle.");return}F.apiKey&&L((await Me.loginProvider({providerId:F.providerID,type:"api_key",apiKey:F.apiKey},Ye())).login),s(F.providerID),T(!1),await ie()}catch(Q){Za(Q)?$.info(Zt("Provider configuration")):x(!0)}finally{C(!1)}},startLogin:async F=>{if(!(!G||g||F==="api_key"&&c.trim().length===0)){C(!0);try{const Q=await Me.loginProvider({providerId:G.id,type:F,...F==="api_key"?{apiKey:c.trim()}:{}},Ye());f(""),b(""),L(Q.login),Q.login.state==="complete"&&await ie()}catch{L({id:"",providerId:G.id,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{C(!1)}}},submitPrompt:async()=>{if(!(!v||!v.prompt||y.length===0||g)){C(!0);try{const F=await Me.respondProviderLogin(v.providerId,v.id,y,Ye());b(""),L(F.login),F.login.state==="complete"&&await ie()}catch{try{const F=await Me.getProviderLogin(v.providerId,v.id,Ye());L(F.login),F.login.state==="complete"&&await ie()}catch{L(F=>F&&{...F,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}}finally{C(!1)}}},logout:async()=>{if(!(!G||g)){C(!0);try{await Me.logoutProvider({providerId:G.id},Ye()),L(null),await ie()}catch{x(!0)}finally{C(!1)}}},handleThinkingChange:re,handleToggleHidden:me}}const Pd=()=>{const{isMobile:t}=Ze(),{selectedProviderId:s,setSelectedProviderId:a,hiddenModels:n,hideAllModels:r,showAllModels:l,settingsDefaultThinkingByModel:d,providers:i,apiKey:u,setApiKey:m,promptValue:p,setPromptValue:h,login:c,customEditing:f,setCustomEditing:y,providerConfig:b,busy:v,failed:L,refreshing:j,refreshingCatalog:T,catalogRefreshFeedback:P,thinkingBusyKeys:A,providerQuery:g,setProviderQuery:C,setVisibleCap:w,refreshProviders:x,refreshCatalog:N,refreshAfterModelAdd:k,provider:I,filteredProviders:S,displayModels:z,hasMore:_,saveCustomProvider:O,startLogin:V,submitPrompt:K,logout:Z,handleThinkingChange:ae,handleToggleHidden:fe}=Td(),[ce,be]=o.useState(!1);if(L&&!i)return e.jsx(we,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Providers are unavailable."}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{x()},disabled:j,children:[e.jsx(R,{name:"refresh",className:H("size-4",j&&"animate-spin")}),j?"Retrying…":"Retry"]})]})});if(f||s===ds){const ne=b?.providerId===I?.id?b:null,pe=ne?md({id:ne.providerId,name:ne.label,options:{baseURL:ne.baseUrl},api:ne.api,models:ne.models}):void 0;return e.jsx(we,{title:ne?"Edit custom provider":"Custom provider",children:e.jsx(gd,{existingProviderIDs:new Set(i?.map(oe=>oe.id)??[]),mode:ne?"edit":"create",initialValues:pe,allowExistingAuth:I?.authenticated===!0,busy:v,onSubmit:oe=>{O(oe)},onCancel:()=>{y(!1),a(I?.id??null)}})})}if(I){const ne=c?.providerId===I.id?c:null,pe=I.authenticated||ne?.state==="complete";return e.jsxs(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>a(null),"aria-label":"Back to providers",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx(wr,{providerId:I.id,className:"size-5 shrink-0"}),e.jsx("span",{className:"truncate",children:I.label})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:I.id}),children:[L?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,e.jsxs(Y,{title:"Authentication",divider:!1,settingsItem:"providers.auth",headerAction:pe?e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>{Z()},disabled:v,children:v?"Disconnecting...":"Disconnect"}):null,children:[pe?e.jsxs("div",{className:"flex items-center gap-1.5 py-1.5 typography-ui-label",children:[e.jsx(R,{name:"check",className:"size-4 text-[var(--status-success)]"}),"Connected"]}):e.jsxs("div",{className:"space-y-4 py-1.5",children:[e.jsx(Pe,{label:"API Key",children:e.jsxs("div",{className:"flex w-full max-w-[24rem] gap-2",children:[e.jsx(ee,{type:"password",value:u,onChange:oe=>m(oe.target.value),placeholder:"sk-...",autoComplete:"off"}),e.jsx(E,{size:"sm",onClick:()=>{V("api_key")},disabled:v||u.trim().length===0,children:v?"Saving...":"Save Key"})]})}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>{V("oauth")},disabled:v,children:"Reconnect"})]}),ne?.state==="pending"?e.jsx(Sd,{login:ne,promptValue:p,onPromptValueChange:h,onSubmit:()=>{K()},busy:v}):null,ne?.state==="failed"?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Authorization was declined or did not complete."}),ne.error?.message?e.jsx("p",{className:"typography-meta break-words text-muted-foreground",children:ne.error.message}):null]}):null]}),e.jsxs(Y,{title:"Available Models",settingsItem:"providers.models",titleAccessory:e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>be(!0),"aria-label":`Add model to ${I.label}`,title:`Add model to ${I.label}`,children:e.jsx(R,{name:"add",className:"size-4"})}),headerAction:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(E,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{N()},disabled:T||v,"aria-label":"Refresh model catalog",title:"Refresh model catalog",children:e.jsx(R,{name:"refresh",className:H("size-4",T&&"animate-spin")})}),pe?e.jsxs(e.Fragment,{children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>l(I.id),children:"Show all"}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>r(I.id,I.models.map(oe=>oe.id)),children:"Hide all"})]}):null,b?e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>y(!0),children:"Update provider"}):null]}),children:[e.jsx("div",{"aria-live":"polite",className:"sr-only",children:T?"Refreshing model catalog":P==="success"?"Model catalog refreshed":P==="error"?"Could not refresh model catalog":""}),e.jsxs("div",{className:"divide-y divide-[var(--surface-subtle)]",children:[I.models.length===0?e.jsx("p",{className:"py-3 typography-meta text-muted-foreground",children:"No models available."}):z.map(oe=>{const G=kd(n,I.id,oe.id),q=Hs({providerId:I.id,modelId:oe.id})??`${I.id}/${oe.id}`,Ce=d[q],re=Nr(Ce)?Ce:void 0,me=A.has(q);return e.jsx(pi,{providerId:I.id,model:oe,storedLevel:re,isBusy:me,isHidden:G,isConnected:pe,onThinkingChange:ae,onToggleHidden:fe},oe.id)}),_?e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(E,{variant:"ghost",size:"xs",onClick:()=>w(oe=>oe+80),children:["Show ",Math.min(80,I.models.length-z.length)," more (",z.length," of"," ",I.models.length,")"]})}):null]})]}),e.jsx(yd,{open:ce,onOpenChange:be,providerId:I.id,providerLabel:I.label,onAdded:oe=>{k(oe.deferred,oe)}})]})}return i===null?e.jsx(we,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{x()},disabled:j,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:H("size-4",j&&"animate-spin")})})}),children:e.jsx(Y,{title:"Providers",divider:!1,settingsItem:"providers.browse",children:e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:e.jsx(jd,{count:6})})})}):S.length===0&&g.trim()===""&&i.length===0?e.jsx(we,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:g,onChange:ne=>C(ne.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-full pl-8"})]}),e.jsx(E,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{x()},disabled:j,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:H("size-4",j&&"animate-spin")})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>a(ds),children:[e.jsx(R,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"cloud-off",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No providers"}),e.jsx(E,{variant:"outline",size:"sm",onClick:()=>a(ds),children:"Add custom provider"})]})}):e.jsxs(we,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:g,onChange:ne=>C(ne.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-full pl-8"}),g?e.jsx("button",{type:"button",onClick:()=>C(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(E,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{x()},disabled:j,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:H("size-4",j&&"animate-spin")})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>a(ds),children:[e.jsx(R,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:[L?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Refresh failed — showing cached providers."}):null,e.jsx(Y,{title:"Providers",divider:!1,settingsItem:"providers.browse",children:S.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["No providers match “",g,"”."]}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>C(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[S.map(ne=>e.jsx(wd,{provider:ne,onSelect:a},ne.id)),e.jsxs("button",{type:"button",onClick:()=>a(ds),"aria-label":"Add custom provider",className:H("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"Add custom provider"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"OpenAI-compatible"})]})]})})]})},Id=({snippet:t,onSelect:s,showSourcePill:a=!0})=>{const n=t.source==="project"?"Project":t.source==="global"?"Global":t.source,r=t.description?.trim()||t.content.replace(/\s+/g," ").trim().slice(0,140)||"No description",l=r.length>=140||(t.description?.trim()?.length??0)===0&&t.content.length>140;return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.name} snippet, ${n}`,className:H("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[a?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:H("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 typography-micro font-medium capitalize",t.source==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:n})}):null,e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"truncate typography-ui-label font-medium text-foreground",children:["#",t.name]}),e.jsxs("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:[r,l?"…":null]})]})]})},mi=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,a)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"h-5 w-16 animate-pulse rounded-full bg-muted"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-full animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-muted"})]})]},a))}),Ed=t=>t.split(/[,\s]+/).map(s=>s.trim()).filter(s=>s.length>0),Ad=()=>{const{isMobile:t}=Ze(),s=Cr(),a=tt(B=>B.selectedSnippetId),n=tt(B=>B.snippetDraft),r=tt(B=>B.snippets),l=tt(B=>B.isLoading),d=tt(B=>B.setSelectedSnippet),i=tt(B=>B.setSnippetDraft),u=tt(B=>B.createSnippet),m=tt(B=>B.updateSnippet),p=tt(B=>B.deleteSnippet),h=tt(B=>B.loadSnippets),c=o.useMemo(()=>a?r.find(B=>B.id===a)??null:null,[a,r]),f=!!(n&&!c),[y,b]=o.useState(""),[v,L]=o.useState("global"),[j,T]=o.useState(""),[P,A]=o.useState(""),[g,C]=o.useState(""),[w,x]=o.useState(!1),[N,k]=o.useState(!1),[I,S]=o.useState(!1),z=o.useRef(""),_=o.useRef(""),O=o.useRef(""),V=o.useRef(""),K=o.useRef("global");o.useEffect(()=>{f&&n?(b(n.name),L(n.scope),T(n.description??""),A(""),C(n.content??""),z.current=n.content??"",_.current=n.description??"",O.current=n.name,V.current="",K.current=n.scope):c&&(b(c.name),L(c.source),T(c.description??""),A((c.aliases??[]).join(", ")),C(c.content),z.current=c.content,_.current=c.description??"",O.current=c.name,V.current=(c.aliases??[]).join(", "),K.current=c.source)},[n,f,c]);const Z=o.useCallback(()=>{f&&i(null),d(null)},[f,d,i]),ae=o.useCallback(async()=>{const B=y.trim().replace(/\s+/g,"-");if(!B){$.error("Snippet name is required");return}if(!/^[a-z0-9_-]+$/i.test(B)){$.error("Snippet name may only contain letters, numbers, dashes and underscores");return}if(!g.trim()){$.error("Snippet content is required");return}const U=Ed(P);if(U.length>10){$.error("Snippets support at most 10 aliases");return}for(const he of U)if(!/^[a-z0-9_-]+$/i.test(he)){$.error("Aliases may only contain letters, numbers, dashes and underscores");return}if(v==="project"&&!s?.trim()){$.error("Project snippets need an active project directory");return}x(!0);const X=f?await u(B,g,{description:j,aliases:U,scope:v,directory:s}):await m(c?.id??"",{name:B!==O.current?B:void 0,content:g!==z.current?g:void 0,description:j!==_.current?j:void 0,aliases:P.trim()!==V.current.trim()?U:void 0,...v!==K.current?{scope:v,...v==="project"&&s?{directory:s}:{}}:{}},s);x(!1),X?(f||i(null),$.success(f?"Snippet created":"Snippet updated")):$.error(f?"Failed to create snippet":"Failed to update snippet")},[P,g,u,j,s,f,y,v,c?.id,i,m]),fe=o.useCallback(async()=>{if(!c)return;k(!0);const B=await p(c.id,s);k(!1),B?($.success("Snippet deleted"),S(!1)):$.error("Failed to delete snippet")},[p,s,c]),[ce,be]=o.useState(""),[ie,ne]=o.useState("all"),[pe,oe]=o.useState(!1),G=o.useCallback(async()=>{if(!pe){oe(!0);try{const{invalidateSnippetsLoadCache:B}=await Ot(async()=>{const{invalidateSnippetsLoadCache:U}=await import("./useAppFontEffects-D_gtiA95.js").then(X=>X.eo);return{invalidateSnippetsLoadCache:U}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));B(s),await h(s)}finally{oe(!1)}}},[s,h,pe]);o.useEffect(()=>{h(s)},[s,h]);const q=o.useMemo(()=>[...r].sort((B,U)=>B.name.localeCompare(U.name)),[r]),Ce=o.useMemo(()=>{let B=q;ie!=="all"&&(B=B.filter(X=>X.source===ie));const U=ce.trim().toLowerCase();return U?B.filter(X=>{const he=X.name.toLowerCase().includes(U),je=(X.description??"").toLowerCase().includes(U),Se=X.content.toLowerCase().includes(U),et=(X.aliases??[]).some(F=>F.toLowerCase().includes(U));return he||je||Se||et}):B},[q,ie,ce]),re=o.useMemo(()=>{let B=0,U=0;for(const X of r)X.source==="project"?U+=1:B+=1;return{all:r.length,global:B,project:U}},[r]),me=o.useCallback(async()=>{const B=new Set(r.map(he=>he.name.toLowerCase()));let U="new-snippet",X=1;for(;B.has(U.toLowerCase());)U=`new-snippet-${X++}`;i({name:U,scope:"global",content:"",description:""}),d(null)},[d,i,r]);if(a!==null||n){if(!c&&!f)return e.jsx(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:Z,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:"Not found"})]}),description:"This snippet no longer exists.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"file-text",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The selected snippet was not found."}),e.jsx(E,{variant:"outline",size:"sm",onClick:Z,children:"Back to snippets"})]})});const B=f?y.trim()!==O.current||j!==_.current||g!==z.current||P.trim()!==V.current.trim()||v!==K.current:y.trim()!==O.current||g!==z.current||j!==_.current||P.trim()!==V.current.trim()||v!==K.current,U=B&&!w&&g.trim().length>0&&y.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:Z,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New snippet":`#${c?.name??y}`})]}),description:f?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a reusable text snippet"}):c?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:c.description}):void 0,headerEnd:!f&&c?e.jsxs(E,{variant:"ghost",size:"xs",onClick:()=>S(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[e.jsx(Y,{title:"Identity",divider:!1,settingsItem:"snippets.create",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 @xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"#"}),e.jsx(ee,{value:y,onChange:X=>b(X.target.value),placeholder:"my-snippet",className:"h-9 flex-1 font-mono",spellCheck:!1,autoComplete:"off"})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Used as"," ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["#",y.trim()||"name"]})," ","in chat. Letters, numbers, dashes and underscores only."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Scope"}),e.jsxs(_e,{value:v,onValueChange:X=>L(X),children:[e.jsx(ze,{size:Be,className:"w-full",children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"global",children:"Global"}),e.jsx(ye,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:v==="project"?"Available only in this project. Project snippets override same-named global snippets.":"Available in every project."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:j,onChange:X=>T(X.target.value),placeholder:"What does this snippet do?",className:"h-9 w-full"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Optional. Shown in the snippet card and autocomplete."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Aliases"}),e.jsx(ee,{value:P,onChange:X=>A(X.target.value),placeholder:"shortcut, alt-name",className:"h-9 w-full font-mono",spellCheck:!1,autoComplete:"off"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Optional alternate # triggers, comma-separated. They expand to the same literal text."})]})]})}),e.jsxs(Y,{title:"Content",divider:!0,settingsItem:"snippets.content",info:"Snippets perform literal text replacement. Type #name in chat to insert the content.",headerAction:e.jsx("span",{className:"typography-micro text-muted-foreground",children:B?"Unsaved changes":"No changes"}),children:[e.jsx(la,{value:g,onChange:C,initialMode:f?"write":"preview",triggerPreview:`#${y.trim()||"name"}`},f?"new-snippet-editor":`snippet-editor:${c?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:Z,children:"Cancel"}),e.jsx(E,{size:"sm",onClick:()=>{ae()},disabled:!U,children:w?"Saving…":f?"Create snippet":"Save changes"})]})]}),!f&&c?e.jsx(Y,{title:"Danger zone",divider:!0,children:e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl border border-dashed border-border/60 bg-muted/20 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Delete snippet"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Permanently remove #",c.name,". This cannot be undone."]})]}),e.jsxs(E,{variant:"destructive",size:"sm",onClick:()=>S(!0),disabled:N,children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(jt,{open:I,onOpenChange:X=>!X&&S(!1),children:e.jsxs(kt,{className:"max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Delete snippet?"}),e.jsxs(St,{children:["This will permanently delete #",c?.name??"",". This cannot be undone."]})]}),e.jsxs(ta,{children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>S(!1),disabled:N,children:"Cancel"}),e.jsx(E,{variant:"destructive",size:"sm",onClick:()=>{fe()},disabled:N,children:N?"Deleting…":"Delete"})]})]})})]})}if(l&&r.length===0)return e.jsx(we,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{G()},disabled:pe,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(R,{name:"refresh",className:H("size-4",pe&&"animate-spin")})})}),children:e.jsx(Y,{title:"Snippets",divider:!1,settingsItem:"snippets.create",children:e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:e.jsx(mi,{count:6})})})});const J=Ce.length===0&&r.length===0;return e.jsx(we,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:ce,onChange:B=>be(B.target.value),placeholder:"Search snippets","aria-label":"Search snippets",className:"h-9 w-[18rem] max-w-full pl-8"}),ce?e.jsx("button",{type:"button",onClick:()=>be(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{G()},disabled:pe,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(R,{name:"refresh",className:H("size-4",pe&&"animate-spin")})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{me()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New snippet"]})]}),children:J?e.jsx(Y,{title:"Snippets",divider:!1,settingsItem:"snippets.create",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"file-text",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No snippets yet"}),e.jsxs("p",{className:"typography-micro max-w-sm text-muted-foreground",children:["Snippets are reusable text. Create one and use it in chat as"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"#my-snippet"}),"."]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{me()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New snippet"]})]})}):e.jsxs(Y,{title:"Snippets",divider:!1,settingsItem:"snippets.create",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="all",onClick:()=>ne("all"),children:["All ",re.all]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="project",onClick:()=>ne("project"),children:["Project ",re.project]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="global",onClick:()=>ne("global"),children:["Global ",re.global]})]}),Ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:ce.trim()?`No snippets match “${ce}”.`:`No ${ie} snippets.`}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>{be(""),ne("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[Ce.map(B=>e.jsx(Id,{snippet:B,onSelect:d,showSourcePill:ie==="all"},`${B.source}:${B.id}`)),e.jsxs("button",{type:"button",onClick:()=>{me()},"aria-label":"Create new snippet",className:H("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New snippet"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Reusable text expansion"})]})]})]})})};function hi(t){let s=0;const a=/\$(\d+)/g;let n;for(;(n=a.exec(t))!==null;){const r=Number.parseInt(n[1]??"",10);Number.isSafeInteger(r)&&r>s&&(s=r)}return s}function Md(t){return`$${hi(t)+1}`}function Ld(t){const s=hi(t);return s<1?null:`\${@:${s+1}}`}function Rd(t){const s=Md(t),a=Ld(t);return[{value:s,label:s,hint:`Insert ${s}, the next argument`},{value:"$@",label:"$@",hint:"Insert $@, all arguments"},...a?[{value:a,label:a,hint:`Insert ${a}, all arguments after the positional ones`}]:[]]}const Dd=async({previousName:t,nextName:s,previousLocation:a,nextLocation:n})=>{const r=Vs.getState(),l=r.projects.find(b=>b.id===r.activeProjectId),d=l?.path?{id:l.id,path:l.path}:null,i=W.getState().globalDraftStarters??[],u=d?await Wo(d):[];if(!(a==="project"?u:i).some(b=>b.type==="prompt"&&b.name===t))return!0;if(n==="project"&&!d)return!1;const h=b=>b.filter(v=>!(v.type==="prompt"&&v.name===t));let c=a==="global"?h(i):i,f=a==="project"?h(u):u;const y={type:"prompt",name:s,scope:n};return n==="project"?f.some(b=>b.type==="prompt"&&b.name===s)||(f=[...f,y]):c.some(b=>b.type==="prompt"&&b.name===s)||(c=[...c,y]),JSON.stringify(c)!==JSON.stringify(i)&&(W.getState().setGlobalDraftStarters(c),await Ke({draftStarters:c})),d&&JSON.stringify(f)!==JSON.stringify(u)?Ho(d,f):!0},_d=()=>{const{isMobile:t}=Ze(),s=Cr(),a=st(U=>U.selectedPromptId),n=st(U=>U.promptDraft),r=st(U=>U.prompts),l=st(U=>U.isLoading),d=st(U=>U.setSelectedPrompt),i=st(U=>U.setPromptDraft),u=st(U=>U.createPrompt),m=st(U=>U.updatePrompt),p=st(U=>U.deletePrompt),h=st(U=>U.loadPrompts),c=o.useMemo(()=>a?r.find(U=>U.id===a)??null:null,[r,a]),f=!!(n&&!c),y=f||c?.editable===!0,b=!f&&c&&c.editable!==!0,[v,L]=o.useState(""),[j,T]=o.useState("global"),[P,A]=o.useState(""),[g,C]=o.useState(""),[w,x]=o.useState(!1),[N,k]=o.useState(!1),[I,S]=o.useState(!1),z=o.useRef(""),_=o.useRef(""),O=o.useRef(""),V=o.useRef("global");o.useEffect(()=>{f&&n?(L(n.name),T(n.location),A(n.description??""),C(n.content??""),z.current=n.name,_.current=n.description??"",O.current=n.content??"",V.current=n.location):c&&(L(c.name),T(c.location==="project"?"project":"global"),A(c.description??""),C(c.content??""),z.current=c.name,_.current=c.description??"",O.current=c.content??"",V.current=c.location==="project"?"project":"global")},[n,f,c]);const K=o.useCallback(()=>{f&&i(null),d(null)},[f,i,d]),Z=o.useCallback(async()=>{const U=v.trim().replace(/\s+/g,"-");if(!U){$.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(U)){$.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!g.trim()){$.error("Prompt content is required");return}if(j==="project"&&!s?.trim()){$.error("Project prompts need an active project directory");return}x(!0);const X=await u(U,g,{description:P,location:j,directory:s});x(!1),X==="busy"?$.info(Zt(`Prompt /${U}`)):X==="deferred"?$.info(Xt(`Prompt /${U}`)):X?$.success(`Prompt /${U} created`):$.error("Failed to create prompt template")},[g,u,P,s,j,v]),ae=o.useCallback(async()=>{if(!c)return;const U=v.trim().replace(/\s+/g,"-");if(!U){$.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(U)){$.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!g.trim()){$.error("Prompt content is required");return}if(j==="project"&&!s?.trim()){$.error("Project prompts need an active project directory");return}x(!0);const X=z.current,he=V.current,je=await m(c.id,{...U!==z.current?{name:U}:{},...P!==_.current?{description:P}:{},...g!==O.current?{content:g}:{},...j!==V.current?{location:j}:{}},s);if(x(!1),je==="busy")$.info(Zt(`Prompt /${U}`));else if(je){let Se=!0;if(X&&(U!==X||j!==he))try{Se=await Dd({previousName:X,nextName:U,previousLocation:he,nextLocation:j})}catch{Se=!1}je==="deferred"?$.info(Xt(`Prompt /${U}`)):$.success(`Prompt /${U} updated`),Se||$.warning("The prompt was updated, but one or more pinned starters could not be updated.")}else $.error("Failed to update prompt template")},[g,P,s,j,v,c,m]),fe=o.useCallback(async()=>{if(!c)return;k(!0);const U=await p(c.id,s);k(!1),U==="busy"?$.info(Zt("Prompt template")):U==="deferred"?($.info(Xt("Prompt template")),S(!1)):U?($.success("Prompt template deleted"),S(!1)):$.error("Failed to delete prompt template")},[p,s,c]),[ce,be]=o.useState(""),[ie,ne]=o.useState("all"),[pe,oe]=o.useState(!1),G=o.useCallback(async()=>{if(!pe){oe(!0);try{Vo(s),await h(s)}finally{oe(!1)}}},[s,h,pe]);o.useEffect(()=>{h(s)},[s,h]);const q=o.useMemo(()=>[...r].sort((U,X)=>U.name.localeCompare(X.name)),[r]),Ce=o.useMemo(()=>{let U=q;ie!=="all"&&(U=U.filter(he=>he.location===ie));const X=ce.trim().toLowerCase();return X?U.filter(he=>he.name.toLowerCase().includes(X)||(he.description??"").toLowerCase().includes(X)||(he.content??"").toLowerCase().includes(X)):U},[ie,ce,q]),re=o.useMemo(()=>{let U=0,X=0;for(const he of r)he.location==="project"?X+=1:he.location==="global"&&(U+=1);return{all:r.length,global:U,project:X}},[r]),me=o.useMemo(()=>Rd(g),[g]),J=o.useCallback(()=>{const U=new Set(r.map(je=>je.name.toLowerCase()));let X="new-prompt",he=1;for(;U.has(X.toLowerCase());)X=`new-prompt-${he++}`;i({name:X,location:"global"}),d(null)},[r,i,d]);if(a!==null||n){if(!c&&!f)return e.jsx(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:K,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:"Not found"})]}),description:"This prompt template no longer exists.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"terminal",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The selected prompt template was not found."}),e.jsx(E,{variant:"outline",size:"sm",onClick:K,children:"Back to prompt templates"})]})});const U=c?.location==="project"?"Project":c?.location==="global"?"Global":c?.location??"Global",he=v.trim().replace(/\s+/g,"-")!==z.current||P!==_.current||g!==O.current||j!==V.current,je=he&&!w&&g.trim().length>0&&v.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",onClick:K,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New prompt template":`/${c?.name??v}`})]}),description:f?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a native Pi command"}):c?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:c.description}):void 0,headerEnd:!f&&c?.editable===!0?e.jsxs(E,{variant:"ghost",size:"xs",onClick:()=>S(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[f?e.jsx(Y,{title:"Identity",divider:!1,settingsItem:"prompt-templates.create",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 @xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"/"}),e.jsx(ee,{value:v,onChange:Se=>L(Se.target.value),placeholder:"review",className:"h-9 flex-1 font-mono",spellCheck:!1,autoComplete:"off"})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Used as"," ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["/",v.trim()||"name"]})," ","in chat. Letters, numbers, dashes and underscores only."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Scope"}),e.jsxs(_e,{value:j,onValueChange:Se=>T(Se),children:[e.jsx(ze,{size:Be,className:"w-full",children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"global",children:"Global"}),e.jsx(ye,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:j==="project"?"Available only in this trusted project.":"Available in every project."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:P,onChange:Se=>A(Se.target.value),placeholder:"What does this command do?",className:"h-9 w-full"})]})]})}):e.jsxs(Y,{title:"Details",divider:!1,settingsItem:"prompt-templates.create",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 typography-micro",children:[e.jsx("span",{className:H("inline-flex items-center rounded-full px-2.5 py-1 font-medium capitalize",c?.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:U}),c?.editable===!0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-[var(--status-success)]/10 px-2.5 py-1 font-medium text-[var(--status-success)]",children:[e.jsx(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]}):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 font-medium text-muted-foreground",children:"Read-only"})]}),b?e.jsx("p",{className:"typography-micro pt-3 text-muted-foreground",children:"This prompt was discovered from a package or path and cannot be edited."}):null,c?.location==="project"?e.jsx("p",{className:"typography-micro pt-2 text-muted-foreground",children:"Project prompts require a trusted project. Untrusted projects cannot create or edit them."}):null,y?e.jsxs("div",{className:"space-y-1.5 pt-4",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Scope"}),e.jsxs(_e,{value:j,onValueChange:Se=>T(Se),children:[e.jsx(ze,{size:Be,className:"w-full","aria-label":"Prompt template scope",children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"global",children:"Global"}),e.jsx(ye,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:j==="project"?"Available only in this trusted project.":"Available in every project."})]}):null,y?e.jsxs("div",{className:"space-y-1.5 pt-4",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"/"}),e.jsx(ee,{value:v,onChange:Se=>L(Se.target.value),className:"h-9 flex-1 font-mono",spellCheck:!1,autoComplete:"off"})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Used as"," ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["/",v.trim()||"name"]})," ","in chat. Letters, numbers, dashes and underscores only."]})]}):null,y?e.jsxs("div",{className:"space-y-1.5 pt-3",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:P,onChange:Se=>A(Se.target.value),className:"h-9 w-full"})]}):null]}),e.jsxs(Y,{title:"Arguments",info:"Pi expands prompt arguments natively. PiChamber only inserts the /name command.",children:[e.jsxs("ul",{className:"typography-micro list-disc space-y-1 pl-5 text-muted-foreground",children:[e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$1"}),","," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$2"})," — positional arguments"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$@"})," — all arguments"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"${1:-default}"})," — defaults when an argument is missing"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"${@:2}"})," — slices such as arguments from position 2 onward"]})]}),e.jsxs("p",{className:"typography-micro pt-2 text-muted-foreground",children:["Example: ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"/review auth tests"})," supplies arguments that Pi substitutes into the template."]})]}),e.jsx(Y,{title:"Content",divider:!0,settingsItem:"prompt-templates.content",info:"Prompt content supports Pi argument syntax such as $1 and $@. Pi expands it when the / command runs.",headerAction:y?e.jsx("span",{className:"typography-micro text-muted-foreground",children:he?"Unsaved changes":"No changes"}):void 0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(la,{value:g,onChange:C,initialMode:f?"write":"preview",contentLabel:"Prompt content",placeholder:"Enter prompt content... Use markdown and Pi argument syntax such as $1 and $@.",triggerPreview:`/${v.trim()||"name"}`,triggerActionLabel:"Runs as",variableChips:me},f?"new-prompt-editor":`prompt-editor:${c?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>{f?K():(L(z.current),T(V.current),A(_.current),C(O.current))},children:"Cancel"}),e.jsx(E,{size:"sm",onClick:()=>{f?Z():ae()},disabled:!je,children:w?"Saving…":f?"Create prompt":"Save changes"})]})]}):e.jsx(e.Fragment,{children:(c?.content??"").trim()?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(en,{content:c?.content??"",stripFrontmatter:!0,className:"max-w-none"})}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"No content."})})}),!f&&c?.editable===!0?e.jsx(Y,{title:"Danger zone",divider:!0,children:e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl border border-dashed border-border/60 bg-muted/20 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Delete prompt"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Permanently remove /",c.name,". This cannot be undone."]})]}),e.jsxs(E,{variant:"destructive",size:"sm",onClick:()=>S(!0),disabled:N,children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(jt,{open:I,onOpenChange:Se=>!Se&&S(!1),children:e.jsxs(kt,{className:"max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(Ct,{children:"Delete prompt?"}),e.jsxs(St,{children:["This will permanently delete /",c?.name??"",". This cannot be undone."]})]}),e.jsxs(ta,{children:[e.jsx(E,{variant:"ghost",size:"sm",onClick:()=>S(!1),disabled:N,children:"Cancel"}),e.jsx(E,{variant:"destructive",size:"sm",onClick:()=>{fe()},disabled:N,children:N?"Deleting…":"Delete"})]})]})})]})}if(l&&r.length===0)return e.jsx(we,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{G()},disabled:pe,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(R,{name:"refresh",className:H("size-4",pe&&"animate-spin")})})}),children:e.jsx(Y,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:e.jsx(mi,{count:6})})})});const B=Ce.length===0&&r.length===0;return e.jsx(we,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name with Pi argument expansion.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:ce,onChange:U=>be(U.target.value),placeholder:"Search prompt templates","aria-label":"Search prompt templates",className:"h-9 w-[18rem] max-w-full pl-8"}),ce?e.jsx("button",{type:"button",onClick:()=>be(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(E,{variant:"ghost",size:"icon",onClick:()=>{G()},disabled:pe,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(R,{name:"refresh",className:H("size-4",pe&&"animate-spin")})}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{J()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New prompt"]})]}),children:B?e.jsx(Y,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"terminal",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No prompt templates yet"}),e.jsxs("p",{className:"typography-micro max-w-sm text-muted-foreground",children:["Prompt templates are native Pi commands. Create one and run it in chat as"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"/my-prompt"}),"."]}),e.jsxs(E,{variant:"outline",size:"sm",onClick:()=>{J()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New prompt"]})]})}):e.jsxs(Y,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="all",onClick:()=>ne("all"),children:["All ",re.all]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="project",onClick:()=>ne("project"),children:["Project ",re.project]}),e.jsxs(E,{variant:"chip",size:"xs","aria-pressed":ie==="global",onClick:()=>ne("global"),children:["Global ",re.global]})]}),Ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:ce.trim()?`No prompt templates match “${ce}”.`:`No ${ie} prompt templates.`}),e.jsx(E,{variant:"ghost",size:"xs",onClick:()=>{be(""),ne("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[Ce.map(U=>{const X=U.editable===!0,he=U.location==="project"?"Project":U.location==="global"?"Global":U.location,je=U.description?.trim()||(U.content??"").replace(/\s+/g," ").trim().slice(0,140)||"No description";return e.jsxs("button",{type:"button",onClick:()=>d(U.id),"aria-label":`${U.name} prompt template, ${he}${X?"":", read-only"}`,className:H("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsxs("div",{className:"flex justify-start gap-1.5",children:[e.jsx("span",{className:H("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 typography-micro font-medium capitalize",U.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:he}),X?null:e.jsx("span",{className:"inline-flex shrink-0 items-center rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:"Read-only"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"truncate typography-ui-label font-medium text-foreground",children:["/",U.name]}),e.jsx("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:je})]})]},U.id)}),e.jsxs("button",{type:"button",onClick:()=>{J()},"aria-label":"Create new prompt template",className:H("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New prompt"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Native / command"})]})]})]})})},xn=()=>{const t=so(),s=W(i=>i.gitChangesViewMode),a=W(i=>i.setGitChangesViewMode),[n,r]=o.useState(!0),l=o.useMemo(()=>[{id:"flat",label:"Flat List"},{id:"tree",label:"Tree View"}],[]);o.useEffect(()=>{(async()=>{try{let u=null;if(!u){const m=Ya()?.settings;if(m)try{const h=(await m.load())?.settings;h&&(u={gitChangesViewMode:h.gitChangesViewMode==="flat"||h.gitChangesViewMode==="tree"?h.gitChangesViewMode:void 0})}catch{}}if(!u){const m=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});m.ok&&(u=await m.json())}u&&(u.gitChangesViewMode==="flat"||u.gitChangesViewMode==="tree")&&a(u.gitChangesViewMode)}catch(u){console.warn("Failed to load git settings:",u)}finally{r(!1)}})()},[a]);const d=o.useCallback(i=>{i!==s&&(a(i),Ke({gitChangesViewMode:i}))},[s,a]);return n?null:e.jsxs(e.Fragment,{children:[e.jsx(Y,{title:"Git Preferences",divider:!1,children:e.jsxs("div",{className:pt,children:[e.jsx(Ft,{settingsItem:"git.changes-view",title:"Changes View",children:e.jsx(ss,{"aria-label":"Git changes view mode",children:l.map(i=>e.jsx(Gs,{selected:s===i.id,onSelect:()=>{d(i.id)},label:i.label,ariaLabel:`Git changes view mode: ${i.label}`},i.id))})}),e.jsx(ke,{settingsItem:"git.gitignored-files",checked:t,onChange:ao,label:"Display Gitignored Files",ariaLabel:"Display gitignored files"})]})}),e.jsx(zd,{})]})},zd=()=>{const s=na().github??null,a=Ta(u=>u.status),n=Ta(u=>u.isLoading),r=Ta(u=>u.refresh);o.useEffect(()=>{s&&r(s)},[s,r]);const l=o.useCallback(()=>{s&&r(s,{force:!0})},[s,r]),d=o.useCallback(u=>{aa(u).then(m=>{$[m.ok?"success":"error"](m.ok?"Command copied":"Failed to copy command")}).catch(()=>$.error("Failed to copy command"))},[]),i=a?.hosts??[];return e.jsx(Y,{title:"GitHub",info:"PiChamber uses the GitHub CLI's active account on the server. There is no sign-in inside PiChamber.",children:e.jsxs("div",{className:vt,children:[s?!a&&n?e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-status",children:"Checking GitHub CLI…"}):a?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{label:"GitHub CLI",info:"Version reported by gh on the machine running PiChamber.",settingsItem:"git.github-status",children:e.jsx("span",{className:"typography-ui text-foreground",children:a.installed?`Installed${a.version?` · ${a.version}`:""}`:"Not installed"})}),i.length===0?e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-account",children:"No signed-in hosts. Run gh auth login on the machine running PiChamber, then check again."}):i.map(u=>e.jsx(Pe,{label:u.host,info:"Token scopes reported by gh for this host.",settingsItem:"git.github-account",children:e.jsxs("span",{className:"typography-ui text-foreground",children:[u.authenticated&&u.login?`@${u.login}`:"Not signed in",u.scopes.length>0?` · ${u.scopes.join(", ")}`:""]})},u.host)),e.jsxs("div",{"data-settings-item":"git.github-scopes",className:"space-y-2",children:[e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Missing scopes show in place with the exact refresh command. Example:"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("code",{className:"rounded bg-[var(--surface-muted)] px-1.5 py-0.5 font-mono typography-micro text-foreground",children:"gh auth refresh -s repo"}),e.jsx("button",{type:"button",onClick:()=>d("gh auth refresh -s repo"),className:"rounded p-1 text-muted-foreground hover:bg-interactive-hover hover:text-foreground",title:"Copy gh auth refresh command","aria-label":"Copy gh auth refresh command",children:e.jsx(R,{name:"file-copy",className:"size-3.5"})})]})]}),e.jsx("div",{"data-settings-item":"git.github-check-again",children:e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:n,children:[e.jsx(R,{name:"refresh",className:"size-3.5"}),n?"Checking…":"Check again"]})})]}):e.jsxs("div",{className:"space-y-2","data-settings-item":"git.github-status",children:[e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Could not reach the GitHub CLI."}),e.jsxs(E,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(R,{name:"refresh",className:"size-3.5"}),"Check again"]})]}):e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-status",children:"GitHub is not available in this runtime."}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"git push uses your normal git credentials. PiChamber never changes git or gh configuration."})]})})},er=()=>{const t=wl();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},Od=()=>{const[t,s]=o.useState(()=>er());return o.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=[window.matchMedia("(display-mode: standalone)"),window.matchMedia("(display-mode: minimal-ui)"),window.matchMedia("(display-mode: fullscreen)"),window.matchMedia("(display-mode: window-controls-overlay)")],n=()=>{s(er())};n();for(const r of a)typeof r.addEventListener=="function"?r.addEventListener("change",n):typeof r.addListener=="function"&&r.addListener(n);return window.addEventListener("appinstalled",n),window.addEventListener("focus",n),()=>{for(const r of a)typeof r.removeEventListener=="function"?r.removeEventListener("change",n):typeof r.removeListener=="function"&&r.removeListener(n);window.removeEventListener("appinstalled",n),window.removeEventListener("focus",n)}},[]),t},Ud=[{value:"system",label:"System",description:"Follow system setting"},{value:"light",label:"Light",description:"Always use light appearance"},{value:"dark",label:"Dark",description:"Always use dark appearance"}],Fd=[{id:"dynamic",label:"Dynamic",description:"New inline, modified side-by-side."},{id:"inline",label:"Always inline",description:"Show as a single unified view."},{id:"side-by-side",label:"Always side-by-side",description:"Compare original and modified files."}],ms="PiChamber - AI Coding Assistant",fi=[{id:"system",label:"Follow system",description:"Respect the device rotation setting."},{id:"portrait",label:"Portrait lock",description:"Install the app locked to portrait."},{id:"landscape",label:"Landscape lock",description:"Install the app locked to landscape."}],gi=[{id:"native",label:"Follow browser",description:"Use the browser default for panning and viewport changes when the keyboard opens."},{id:"resize-content",label:"Resize content",description:"Ask supported browsers to shrink the app layout instead of relying only on panning."}],Bd=[{value:"default",label:"Old"},{value:"new",label:"New"}],Ga=t=>t==="portrait"||t==="landscape"?t:"system",xi=[{id:"auto",label:"Auto",description:"Use system locale preference."},{id:"24h",label:"24-hour",description:"Show time as 14:15."},{id:"12h",label:"12-hour",description:"Show time as 02:15 PM."}],vi=[{id:"auto",label:"Auto",description:"Use locale week start."},{id:"monday",label:"Monday"},{id:"sunday",label:"Sunday"}],$d=[{id:"workspace",label:"Workspace"},{id:"folder",label:"By folder"},{id:"timeline",label:"Timeline"}],Kd=[{id:"steer",label:"Steering"},{id:"queue",label:"Follow-up"}],Rs=o.memo(function({theme:s}){return e.jsxs("div",{"data-theme-preview":s.metadata.id,className:"flex h-full w-full",style:{backgroundColor:s.colors.surface.background},children:[e.jsxs("div",{className:"flex w-[38%] shrink-0 flex-col gap-[4px] overflow-hidden border-r p-[5px]",style:{backgroundColor:s.colors.surface.muted,borderColor:s.colors.interactive.border},children:[e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",style:{backgroundColor:s.colors.interactive.selection},children:e.jsx("div",{className:"h-[3px] w-[70%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})}),e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",children:e.jsx("div",{className:"h-[3px] w-[85%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})}),e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",children:e.jsx("div",{className:"h-[3px] w-[55%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})})]}),e.jsxs("div",{className:"flex min-w-[0px] flex-1 flex-col gap-[4px] overflow-hidden p-[6px]",children:[e.jsx("div",{className:"h-[3px] w-[80%] rounded-full opacity-70",style:{backgroundColor:s.colors.surface.foreground}}),e.jsx("div",{className:"h-[3px] w-[55%] rounded-full opacity-40",style:{backgroundColor:s.colors.surface.foreground}}),e.jsxs("div",{className:"flex items-center gap-[3px]",children:[e.jsx("div",{className:"h-[3px] w-[18%] rounded-full",style:{backgroundColor:s.colors.syntax.base.keyword}}),e.jsx("div",{className:"h-[3px] w-[30%] rounded-full",style:{backgroundColor:s.colors.syntax.base.string}}),e.jsx("div",{className:"h-[3px] w-[22%] rounded-full",style:{backgroundColor:s.colors.syntax.base.function}})]}),e.jsx("div",{className:"mt-auto flex h-[11px] items-center justify-end rounded-[3px] border px-[2px]",style:{backgroundColor:s.colors.surface.elevated,borderColor:s.colors.interactive.border},children:e.jsx("div",{className:"h-[5px] w-[9px] rounded-full",style:{backgroundColor:s.colors.primary.base}})})]})]})}),Vd=({mode:t,lightTheme:s,darkTheme:a})=>e.jsxs("div",{"data-color-mode-preview":t,className:"relative h-full w-full",children:[t==="light"&&s&&e.jsx(Rs,{theme:s}),t==="dark"&&a&&e.jsx(Rs,{theme:a}),t==="system"&&e.jsxs(e.Fragment,{children:[s&&e.jsx(Rs,{theme:s}),a&&e.jsx("div",{className:"absolute inset-0 [clip-path:polygon(100%_0,100%_100%,0_100%)]",children:e.jsx(Rs,{theme:a})})]})]}),Ds=({theme:t})=>e.jsxs("span",{"aria-hidden":!0,"data-theme-swatch":t.metadata.id,className:"inline-flex h-[16px] w-[30px] shrink-0 items-center justify-center gap-[3px] rounded-[4px] border",style:{backgroundColor:t.colors.surface.background,borderColor:t.colors.interactive.border},children:[e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.primary.base}}),e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.syntax.base.keyword}}),e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.syntax.base.string}})]}),Wd=({themeMode:t,setThemeMode:s,showMobileLayoutSetting:a,mobileLayoutPreference:n,onMobileLayoutPreferenceChange:r,selectedLightTheme:l,setLightThemePreference:d,lightThemes:i,selectedDarkTheme:u,setDarkThemePreference:m,darkThemes:p,formatThemeLabel:h,customThemesLoading:c,themesReloading:f,setThemesReloading:y,reloadCustomThemes:b,dockBadgeSupported:v,dockBadgeEnabled:L,setDockBadgeEnabled:j})=>e.jsxs(Y,{title:"Color mode & Theme",divider:!1,contentClassName:"space-y-4",children:[e.jsx(Ft,{title:"Color mode",children:e.jsx(ss,{"aria-label":"Color Mode",className:"grid max-w-[30rem] grid-cols-3 gap-2 space-y-0 @xl:gap-3",children:Ud.map(T=>e.jsx(Er,{selected:t===T.value,onSelect:()=>s(T.value),label:T.label,ariaLabel:T.label,preview:e.jsx(Vd,{mode:T.value,lightTheme:l,darkTheme:u})},T.value))})}),a&&e.jsx(Ie,{label:"Mobile Layout",children:e.jsx(tn,{value:n,options:Bd.map(T=>({value:T.value,label:T.label})),onChange:r,"aria-label":"Mobile Layout"})}),e.jsxs(zt,{className:"gap-4 @md:grid-cols-2 @md:gap-8 @3xl:gap-10",children:[e.jsx(Ie,{label:"Light Theme",settingsItem:"appearance.light-theme",children:e.jsxs(_e,{value:l?.metadata.id??"",onValueChange:d,children:[e.jsx(ze,{"aria-label":"Select light theme",size:Be,className:bt,children:e.jsx(Oe,{placeholder:"Select theme",children:l?e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Ds,{theme:l}),e.jsx("span",{className:"truncate",children:h(l.metadata.name,"light")})]}):void 0})}),e.jsx(Ue,{children:i.map(T=>e.jsx(ye,{value:T.metadata.id,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Ds,{theme:T}),e.jsx("span",{className:"truncate",children:h(T.metadata.name,"light")})]})},T.metadata.id))})]})}),e.jsx(Ie,{label:"Dark Theme",settingsItem:"appearance.dark-theme",children:e.jsxs(_e,{value:u?.metadata.id??"",onValueChange:m,children:[e.jsx(ze,{"aria-label":"Select dark theme",size:Be,className:bt,children:e.jsx(Oe,{placeholder:"Select theme",children:u?e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Ds,{theme:u}),e.jsx("span",{className:"truncate",children:h(u.metadata.name,"dark")})]}):void 0})}),e.jsx(Ue,{children:p.map(T=>e.jsx(ye,{value:T.metadata.id,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Ds,{theme:T}),e.jsx("span",{className:"truncate",children:h(T.metadata.name,"dark")})]})},T.metadata.id))})]})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{type:"button",disabled:c||f,onClick:()=>{const T=Date.now();y(!0),b().finally(()=>{const P=Date.now()-T;if(P<500){window.setTimeout(()=>{y(!1)},500-P);return}y(!1)})},className:"typography-settings-link inline-flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:[e.jsx(R,{name:"restart",className:H("h-3.5 w-3.5",f&&"animate-spin")}),f?"Reloading themes...":"Reload themes"]}),e.jsx(ys,{children:"Import custom themes from ~/.config/pichamber/themes/"})]}),v&&e.jsx(sn,{settingsItem:"appearance.dock-badge",children:e.jsx(ke,{checked:L,onChange:j,label:"Dock badge",info:"Show a count of chats with unseen activity on the macOS dock icon.",ariaLabel:"Dock badge"})})]}),Hd=({shouldShowTimeFormat:t,shouldShowWeekStart:s,timeFormatPreference:a,selectedTimeFormatLabel:n,onTimeFormatPreferenceChange:r,weekStartPreference:l,selectedWeekStartLabel:d,onWeekStartPreferenceChange:i})=>e.jsx(Y,{title:"Localization",children:e.jsxs(zt,{className:"gap-4 @md:grid-cols-2 @md:gap-8 @3xl:gap-10",children:[t&&e.jsx(Ie,{label:"Time Format",settingsItem:"appearance.time-format",children:e.jsxs(_e,{value:a,onValueChange:u=>r(u),children:[e.jsx(ze,{"aria-label":"Select time format",size:Be,className:bt,children:e.jsx(Oe,{children:n})}),e.jsx(Ue,{children:xi.map(u=>e.jsx(ye,{value:u.id,children:u.label},u.id))})]})}),s&&e.jsx(Ie,{label:"Week Starts On",settingsItem:"appearance.week-start",children:e.jsxs(_e,{value:l,onValueChange:u=>i(u),children:[e.jsx(ze,{"aria-label":"Select week start",size:Be,className:bt,children:e.jsx(Oe,{children:d})}),e.jsx(Ue,{children:vi.map(u=>e.jsx(ye,{value:u.id,children:u.label},u.id))})]})})]})}),Gd=({showPwaInstallNameSetting:t,pwaInstallName:s,setPwaInstallName:a,onApplyPwaInstallName:n,showPwaOrientationSetting:r,pwaOrientation:l,selectedPwaOrientationLabel:d,onApplyPwaOrientation:i,showMobileKeyboardModeSetting:u,mobileKeyboardMode:m,selectedMobileKeyboardModeLabel:p,onSetMobileKeyboardMode:h})=>e.jsxs(Y,{title:"App install",divider:!1,className:"pb-0",contentClassName:vt,children:[t&&e.jsxs(Pe,{label:"Install App Name",info:"Used by PWA installation process.",settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:es,children:[e.jsx(ee,{value:s,onChange:c=>a(c.target.value),onBlur:()=>{n(s)},onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),n(s))},className:"min-w-0 flex-1",maxLength:64,"aria-label":"PWA install app name"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>{a(ms),n("")},className:Qe,"aria-label":"Reset install app name",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),r&&e.jsxs(Pe,{label:"Install Orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:es,children:[e.jsxs(_e,{value:l,onValueChange:c=>{const f=Ga(c);i(f)},children:[e.jsx(ze,{"aria-label":"PWA install orientation",size:Be,className:Ln,children:e.jsx(Oe,{placeholder:"Select orientation",children:d})}),e.jsx(Ue,{children:fi.map(c=>e.jsx(ye,{value:c.id,children:c.label},c.id))})]}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>{i("system")},disabled:l==="system",className:Qe,"aria-label":"Reset install orientation",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),u&&e.jsxs(Pe,{label:"Mobile Keyboard Behavior",info:"Default browser behavior is safest. Resize content asks supported browsers to shrink the app when the on-screen keyboard opens.",settingsItem:"appearance.mobile-keyboard-mode",alignEnd:!1,controlClassName:es,children:[e.jsxs(_e,{value:m,onValueChange:c=>{const f=fr(c);h(f)},children:[e.jsx(ze,{"aria-label":"Mobile keyboard behavior",size:Be,className:Ln,children:e.jsx(Oe,{placeholder:"Select keyboard behavior",children:p})}),e.jsx(Ue,{children:gi.map(c=>e.jsx(ye,{value:c.id,children:c.label},c.id))})]}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>{h("native")},disabled:m==="native",className:Qe,"aria-label":"Reset mobile keyboard behavior",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})]});function tr(t,s,a){return Math.min(a,Math.max(s,t))}function qd(t){if(!Number.isFinite(t))return 0;const s=String(t);if(s.includes("e-")){const[,n]=s.split("e-");return Number(n)||0}const a=s.split(".");return a.length===2?a[1].length:0}function sr(t,s){const a=qd(s);return a<=0?t:Number(t.toFixed(a))}const xt=D.forwardRef(({value:t,onValueChange:s,min:a=-1/0,max:n=1/0,step:r=1,className:l,containerClassName:d,onBlur:i,disabled:u,fallbackValue:m,onClear:p,emptyLabel:h="—",...c},f)=>{const[y,b]=D.useState(()=>t==null?"":String(t)),{isMobile:v}=Ze(),L=D.useRef(!1),j=D.useRef(null),T=D.useCallback(()=>{if(typeof document>"u"||typeof window>"u")return;j.current?.();const _=K=>{K.preventDefault(),K.stopPropagation(),K.stopImmediatePropagation?.(),j.current?.()},O=window.setTimeout(()=>{j.current?.()},700),V=()=>{window.clearTimeout(O),document.removeEventListener("click",_,!0),j.current=null};j.current=V,document.addEventListener("click",_,!0)},[]);D.useEffect(()=>()=>{j.current?.()},[]),D.useEffect(()=>{b(t==null?"":String(t))},[t]);const P=D.useMemo(()=>t!==void 0?t:m!==void 0?m:Number.isFinite(a)?a:0,[m,a,t]),A=D.useRef(P);D.useEffect(()=>{A.current=P},[P]);const g=D.useCallback(_=>{const O=tr(_,a,n),V=sr(O,r);A.current=V,s(V)},[n,a,s,r]),C=D.useCallback(_=>{const O=_.target.value;if(b(O),O.trim()===""){p?.();return}const V=Number(O);Number.isFinite(V)&&g(V)},[g,p]),w=D.useCallback(_=>{if(y.trim()===""){p||b(t==null?"":String(t)),i?.(_);return}const O=Number(y);if(!Number.isFinite(O))b(t==null?"":String(t));else{const V=tr(O,a,n),K=sr(V,r);K!==t?g(O):A.current=K,b(String(K))}i?.(_)},[g,y,n,a,i,p,r,t]),x=!!(u||P>=n),N=!!(u||P<=a),k=()=>{N||g(A.current-r)},I=()=>{x||g(A.current+r)},S=_=>O=>{O.preventDefault(),O.stopPropagation(),L.current=!0,T(),_()},z=_=>O=>{if(L.current){L.current=!1,O.preventDefault(),O.stopPropagation();return}_()};return v?e.jsxs("div",{className:H("flex h-8 shrink-0 items-stretch overflow-x-hidden overflow-y-hidden rounded-lg border border-border bg-transparent select-none overscroll-contain","[-webkit-user-select:none] [-webkit-touch-callout:none]","disabled:pointer-events-none disabled:opacity-50",d),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:N,onTouchStart:S(k),onClick:z(k),className:H("grid h-full min-h-0 w-9 shrink-0 place-items-center overflow-x-hidden overflow-y-hidden border-r border-border p-0 leading-none touch-none","text-muted-foreground","disabled:pointer-events-none disabled:opacity-50",!N&&"active:bg-interactive-hover"),children:e.jsx(R,{name:"subtract",className:"block h-4 w-4"})}),e.jsx("div",{className:H("flex h-full min-w-0 flex-1 items-center justify-center bg-transparent px-1.5","text-center text-[16px] leading-none text-foreground [font-variant-numeric:tabular-nums]",l),"aria-live":"polite",children:t==null?h:y}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:x,onTouchStart:S(I),onClick:z(I),className:H("grid h-full min-h-0 w-9 shrink-0 place-items-center overflow-x-hidden overflow-y-hidden border-l border-border p-0 leading-none touch-none","text-muted-foreground","disabled:pointer-events-none disabled:opacity-50",!x&&"active:bg-interactive-hover"),children:e.jsx(R,{name:"add",className:"block h-4 w-4"})})]}):e.jsxs("div",{className:H("flex h-8 shrink-0 items-stretch overflow-x-hidden overflow-y-hidden rounded-md border border-border bg-transparent","disabled:pointer-events-none disabled:opacity-50","transition-[background-color,border-color,box-shadow] duration-150 ease-in-out",d),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:N,onClick:()=>g(A.current-r),className:H("flex h-full w-7 shrink-0 items-center justify-center overflow-x-hidden overflow-y-hidden border-r border-border p-0 leading-none touch-manipulation","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50","transition-colors duration-150 ease-in-out"),children:e.jsx(R,{name:"subtract",className:"block h-3.5 w-3.5"})}),e.jsx("input",{...c,ref:f,type:"text",inputMode:c.inputMode??"numeric",value:y,onChange:C,onBlur:w,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:H("h-full min-w-0 w-10 flex-1 bg-transparent px-1.5 text-center typography-ui-label leading-none text-foreground [font-variant-numeric:tabular-nums]","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","appearance-none outline-none [appearance:textfield] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","disabled:pointer-events-none disabled:cursor-not-allowed",l)}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:x,onClick:()=>g(A.current+r),className:H("flex h-full w-7 shrink-0 items-center justify-center overflow-x-hidden overflow-y-hidden border-l border-border p-0 leading-none touch-manipulation","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50","transition-colors duration-150 ease-in-out"),children:e.jsx(R,{name:"add",className:"block h-3.5 w-3.5"})})]})});xt.displayName="NumberInput";const Qd=({shouldShow:t,uiFont:s,setUiFont:a,monoFont:n,setMonoFont:r,fontSize:l,setFontSize:d,terminalFontSize:i,setTerminalFontSize:u,editorFontSize:m,setEditorFontSize:p,padding:h,setPadding:c,inputBarOffset:f,setInputBarOffset:y,isMobile:b})=>e.jsxs(Y,{title:"Density & type",contentClassName:vt,children:[t("fontSize")||t("terminalFontSize")?e.jsxs(zt,{children:[t("fontSize")&&e.jsxs(Ie,{label:"Interface Font",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[e.jsxs(_e,{value:s,onValueChange:v=>a(v),children:[e.jsx(ze,{"aria-label":"Select interface font",size:Be,className:bt,children:e.jsx(Oe,{children:bn.find(v=>v.id===s)?.label})}),e.jsx(Ue,{children:bn.map(v=>e.jsx(ye,{value:v.id,children:e.jsx("span",{style:{fontFamily:v.stack},children:v.label})},v.id))})]}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>a(yn),disabled:s===yn,className:Qe,"aria-label":"Reset interface font",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),t("terminalFontSize")&&e.jsxs(Ie,{label:"Code Font",controlClassName:"w-full",children:[e.jsxs(_e,{value:n,onValueChange:v=>r(v),children:[e.jsx(ze,{"aria-label":"Select code font",size:Be,className:bt,children:e.jsx(Oe,{children:wn.find(v=>v.id===n)?.label})}),e.jsx(Ue,{children:wn.map(v=>e.jsx(ye,{value:v.id,children:e.jsx("span",{style:{fontFamily:v.stack},children:v.label})},v.id))})]}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>r(jn),disabled:n===jn,className:Qe,"aria-label":"Reset code font",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,t("fontSize")||t("terminalFontSize")||t("editorFontSize")?e.jsxs(zt,{children:[t("fontSize")&&e.jsx(Ie,{label:"Interface Font Size",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:l,onValueChange:d,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx("span",{className:Jt,children:"%"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>d(100),disabled:l===100,className:Qe,"aria-label":"Reset font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("terminalFontSize")&&e.jsx(Ie,{label:"Terminal Font Size",settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:i,onValueChange:u,min:9,max:52,step:1}),e.jsx("span",{className:Jt,children:"px"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>u(13),disabled:i===13,className:Qe,"aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("editorFontSize")&&e.jsx(Ie,{label:"Editor Font Size",settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:m,onValueChange:p,min:9,max:32,step:1}),e.jsx("span",{className:Jt,children:"px"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>p(13),disabled:m===13,className:Qe,"aria-label":"Reset editor font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,t("spacing")||t("inputBarOffset")&&b?e.jsxs(zt,{children:[t("spacing")&&e.jsx(Ie,{label:"Spacing Density",settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:h,onValueChange:c,min:50,max:200,step:5}),e.jsx("span",{className:Jt,children:"%"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>c(100),disabled:h===100,className:Qe,"aria-label":"Reset spacing",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("inputBarOffset")&&b&&e.jsx(Ie,{label:"Input Bar Offset",info:"Raise input bar to avoid OS-level screen obstructions like home bars.",settingsItem:"appearance.input-bar-offset",controlClassName:"w-full",children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:f,onValueChange:y,min:0,max:100,step:5}),e.jsx("span",{className:Jt,children:"px"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>y(0),disabled:f===0,className:Qe,"aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),Xs=({width:t,tone:s="bg-foreground/60",className:a})=>e.jsx("div",{className:H("h-[3px] rounded-full",s,t,a)}),qt=({width:t,selected:s=!1,chevron:a=!1})=>e.jsxs("div",{className:H("flex items-center gap-[4px] rounded-[3px] px-[3px] py-[2px]",s&&"bg-interactive-selection"),children:[e.jsx("div",{className:"h-[5px] w-[6px] shrink-0 rounded-[1.5px] bg-foreground/35"}),e.jsx(Xs,{tone:"bg-foreground/60",width:t}),a&&e.jsx("div",{className:"ml-auto h-[3px] w-[3px] shrink-0 rounded-full bg-foreground/20"})]}),us=({title:t,details:s,selected:a=!1})=>e.jsxs("div",{className:H("flex flex-col gap-[3px] rounded-[3px] px-[3px] py-[3px]",a&&"bg-interactive-selection"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(Xs,{tone:"bg-foreground/60",width:t}),e.jsx("div",{className:"ml-auto h-[3px] w-[5px] shrink-0 rounded-full bg-foreground/20"})]}),e.jsx(Xs,{tone:"bg-foreground/20",width:s})]}),Da=({width:t,selected:s=!1})=>e.jsx("div",{className:H("flex items-center rounded-[3px] py-[2px] pl-[13px] pr-[3px]",s&&"bg-interactive-selection"),children:e.jsx(Xs,{tone:s?"bg-foreground/60":"bg-foreground/35",width:t})}),Jd=({mode:t})=>e.jsxs("div",{"data-sidebar-view-preview":t,className:"flex h-full w-full bg-background",children:[e.jsxs("div",{className:"flex w-[58%] shrink-0 flex-col gap-[4px] overflow-hidden border-r border-border bg-sidebar p-[6px]",children:[t==="workspace"&&e.jsxs(e.Fragment,{children:[e.jsx(qt,{width:"w-[55%]",selected:!0}),e.jsx(qt,{width:"w-[70%]"}),e.jsx(qt,{width:"w-[45%]"}),e.jsx("div",{className:"h-px shrink-0 bg-border"}),e.jsx(us,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx(us,{title:"w-[60%]",details:"w-[40%]"})]}),t==="folder"&&e.jsxs(e.Fragment,{children:[e.jsx(qt,{width:"w-[60%]",chevron:!0}),e.jsx(Da,{width:"w-[70%]",selected:!0}),e.jsx(Da,{width:"w-[55%]"}),e.jsx(qt,{width:"w-[45%]",chevron:!0}),e.jsx(Da,{width:"w-[65%]"}),e.jsx(qt,{width:"w-[55%]",chevron:!0})]}),t==="timeline"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-[3px] h-[2px] w-[28%] shrink-0 rounded-full bg-foreground/35"}),e.jsx(us,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx(us,{title:"w-[60%]",details:"w-[45%]"}),e.jsx("div",{className:"mx-[3px] h-[2px] w-[36%] shrink-0 rounded-full bg-foreground/35"}),e.jsx(us,{title:"w-[70%]",details:"w-[40%]"})]})]}),e.jsxs("div",{className:"flex min-w-[0px] flex-1 flex-col gap-[4px] p-[6px]",children:[e.jsx("div",{className:"h-[3px] w-[80%] rounded-full bg-foreground/10"}),e.jsx("div",{className:"h-[3px] w-[55%] rounded-full bg-foreground/10"}),e.jsx("div",{className:"mt-auto h-[10px] rounded-[3px] border border-border"})]})]}),Yd=({shouldShow:t,sidebarViewMode:s,onSidebarViewModeChange:a,fileEditorKeymap:n,setFileEditorKeymap:r,autoSaveEnabled:l,setAutoSaveEnabled:d,expandedEditorToolbar:i,onExpandedEditorToolbarChange:u,wrapLinesByDefault:m,onWrapLinesByDefaultChange:p,showTerminalQuickKeysOnDesktop:h,setShowTerminalQuickKeysOnDesktop:c,showTerminalShellSetting:f,terminalShell:y,setTerminalShell:b,terminalShellOptions:v,terminalShellSupportsLogin:L,terminalLoginShellEnabled:j,setTerminalLoginShellEnabled:T})=>e.jsxs(Y,{title:"Navigation",contentClassName:"space-y-4",children:[t("sidebarViewMode")&&e.jsx(Ft,{title:"Sidebar view",info:"Workspace opens one folder at a time. By folder lists every folder with its sessions underneath. Timeline groups sessions from every folder by when they were last active. Applies to every device connected to this server.",settingsItem:"appearance.sidebar-view",children:e.jsx(ss,{"aria-label":"Sidebar view",className:"grid max-w-[30rem] grid-cols-3 gap-2 space-y-0 @xl:gap-3",children:$d.map(P=>e.jsx(Er,{selected:s===P.id,onSelect:()=>a(P.id),label:P.label,ariaLabel:P.label,preview:e.jsx(Jd,{mode:P.id})},P.id))})}),t("fileEditorKeymap")&&e.jsx(Ft,{title:"File editor keymap",settingsItem:"appearance.file-editor-keymap",children:e.jsx(ss,{"aria-label":"File editor keymap",children:["default","vim"].map(P=>e.jsx(Gs,{selected:n===P,onSelect:()=>r(P),label:P==="default"?"Default":"Vim",ariaLabel:P==="default"?"Default":"Vim"},P))})}),e.jsxs("div",{className:pt,children:[t("autoSaveEnabled")&&e.jsx(ke,{checked:l,onChange:d,label:"Auto-save files",ariaLabel:"Auto-save files",info:"Automatically save file edits after you stop typing. Disable to require manual save.",settingsItem:"appearance.auto-save-enabled"}),t("expandedEditorToolbar")&&e.jsx(ke,{checked:i,onChange:u,label:"Always show editor toolbar (docked under the file tabs)",ariaLabel:"Always show editor toolbar",settingsItem:"appearance.expanded-editor-toolbar"}),t("wrapLinesByDefault")&&e.jsx(ke,{checked:m,onChange:p,label:"Wrap long lines by default",ariaLabel:"Wrap long lines by default",info:"Applies to the file viewer and diffs. The wrap toggle in each view overrides it until reload.",settingsItem:"appearance.wrap-lines-by-default"}),t("terminalQuickKeys")&&e.jsx(ke,{checked:h,onChange:c,label:"Terminal Quick Keys",ariaLabel:"Terminal quick keys",settingsItem:"appearance.terminal-quick-keys",info:"Show Esc, Ctrl, Arrows in terminal view"}),f&&e.jsx(Ie,{label:"Terminal Shell",info:"Restart the terminal to apply this change to the current session.",settingsItem:"appearance.terminal-shell",className:"pt-2",children:e.jsxs(_e,{value:y,onValueChange:P=>{no(P)&&b(P)},children:[e.jsx(ze,{"aria-label":"Select terminal shell",size:Be,className:bt,children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"auto",children:"Auto"}),v.map(P=>e.jsx(ye,{value:P.id,children:P.name},P.id))]})]})}),f&&L&&e.jsx(ke,{checked:j,onChange:T,label:"Start as login shell",ariaLabel:"Start as login shell",settingsItem:"appearance.terminal-login-shell"})]})]}),Xd=({hasBehaviorSettings:t,showBehaviorMessageOptions:s,behaviorSectionDivider:a,shouldShow:n,diffLayoutPreference:r,setDiffLayoutPreference:l,followUpBehavior:d,setFollowUpBehavior:i,draftStartersVisible:u,onDraftStartersVisibleChange:m})=>t?e.jsxs(e.Fragment,{children:[s&&e.jsx(Y,{title:"Message options",divider:a,children:e.jsxs(zt,{className:"lg:gap-y-6",children:[n("diffLayout")&&e.jsx(Ft,{title:"Diff Layout",children:e.jsx(ss,{"aria-label":"Diff layout",children:Fd.map(p=>e.jsx(Gs,{selected:r===p.id,onSelect:()=>l(p.id),label:p.label,ariaLabel:`Diff layout: ${p.label}`},p.id))})}),n("followUpBehavior")&&e.jsx(Ft,{title:"Follow-up behavior",info:"Follow-up waits until the agent finishes, then sends. Steering is delivered at the next supported tool or turn boundary. Follow-ups stay on this device.",settingsItem:"chat.follow-up-behavior",children:e.jsx(ss,{"aria-label":"Follow-up behavior",children:Kd.map(p=>e.jsx(Gs,{selected:d===p.id,onSelect:()=>i(p.id),label:p.label,ariaLabel:`Follow-up behavior: ${p.label}`},p.id))})})]})}),e.jsx(Y,{title:"Features",contentClassName:pt,children:e.jsx(ke,{checked:u,onChange:m,label:"Show Starters on New Session Screen",ariaLabel:"Show starters on the new session screen",settingsItem:"chat.draft-starters-visible"})})]}):null,Zd=({perfHudEnabled:t,onPerfHudEnabledChange:s,processRecordingSupported:a,processRecordingEnabled:n,processRecordingActive:r,processRecordingSaving:l,processRecordingError:d,onProcessRecordingEnabledChange:i})=>e.jsxs(Y,{title:"Diagnostics",contentClassName:pt,children:[e.jsx(ke,{checked:t,onChange:s,label:"Performance overlay",info:"Shows live frame time, long tasks, and render counters. Adds overhead. Stays on this device only, and is not a substitute for profile:idle or profile:session.",ariaLabel:"Performance overlay",settingsItem:"general.performance-overlay"}),a?e.jsx(ke,{checked:n,onChange:i,disabled:l,label:"Record Electron process performance",info:"Samples CPU and memory for Electron processes every 10 seconds and writes a local diagnostics file. Recording continues after restart until disabled.",description:d??(n&&!r?"Recording could not start. Disable it and try again.":void 0),ariaLabel:"Record Electron process performance",settingsItem:"general.process-performance-recording"}):null]}),ca=({visibleSettings:t})=>{const{isMobile:s}=Ze(),{terminal:a}=na(),{browserTab:n}=Od(),r=W(M=>M.expandedEditorToolbar),l=W(M=>M.setExpandedEditorToolbar),d=W(M=>M.wrapLinesByDefault),i=W(M=>M.setWrapLinesByDefault),u=W(M=>M.autoSaveEnabled),m=W(M=>M.setAutoSaveEnabled),p=W(M=>M.fontSize),h=W(M=>M.setFontSize),c=W(M=>M.terminalFontSize),f=W(M=>M.setTerminalFontSize),y=W(M=>M.terminalShell),b=W(M=>M.setTerminalShell),v=W(M=>M.terminalLoginShells),L=W(M=>M.setTerminalLoginShells),j=W(M=>M.editorFontSize),T=W(M=>M.setEditorFontSize),P=W(M=>M.uiFont),A=W(M=>M.setUiFont),g=W(M=>M.monoFont),C=W(M=>M.setMonoFont),w=W(M=>M.padding),x=W(M=>M.setPadding),N=W(M=>M.inputBarOffset),k=W(M=>M.setInputBarOffset),I=W(M=>M.mobileKeyboardMode),S=W(M=>M.setMobileKeyboardMode),z=W(M=>M.diffLayoutPreference),_=W(M=>M.setDiffLayoutPreference),O=W(M=>M.showTerminalQuickKeysOnDesktop),V=W(M=>M.setShowTerminalQuickKeysOnDesktop),K=W(M=>M.fileEditorKeymap),Z=W(M=>M.setFileEditorKeymap),ae=kn(M=>M.followUpBehavior),fe=kn(M=>M.setFollowUpBehavior),ce=W(M=>M.timeFormatPreference),be=W(M=>M.setTimeFormatPreference),ie=W(M=>M.weekStartPreference),ne=W(M=>M.setWeekStartPreference),pe=W(M=>M.sidebarViewMode),oe=W(M=>M.setSidebarViewMode),G=W(M=>M.draftStartersVisible),q=W(M=>M.setDraftStartersVisible),{themeMode:Ce,setThemeMode:re,availableThemes:me,customThemesLoading:J,reloadCustomThemes:B,lightThemeId:U,darkThemeId:X,setLightThemePreference:he,setDarkThemePreference:je}=Go(),[Se,et]=o.useState(!1),F=o.useMemo(()=>Le()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),Q=W(M=>M.dockBadgeEnabled),de=W(M=>M.setDockBadgeEnabled),te=o.useSyncExternalStore(ro,io,()=>!1),ge=Le(),[$e,lt]=o.useState(!1),[We,Xe]=o.useState(!1),[mt,Pt]=o.useState(!1),[ns,Ss]=o.useState(!1),[da,It]=o.useState(null),ua=o.useCallback(M=>{q(M),Ke({draftStartersVisible:M})},[q]),ht=o.useCallback(M=>{l(M),Ke({expandedEditorToolbar:M})},[l]),pa=o.useCallback(M=>{i(M),Ke({wrapLinesByDefault:M})},[i]),ma=o.useCallback(M=>{be(M),Ke({timeFormatPreference:M})},[be]),ha=o.useCallback(M=>{ne(M),Ke({weekStartPreference:M})},[ne]),fa=o.useCallback(M=>{oe(M),Ke({sidebarViewMode:M})},[oe]),Wt=o.useMemo(()=>me.filter(M=>M.metadata.variant==="light").sort((M,le)=>M.metadata.name.localeCompare(le.metadata.name)),[me]),ft=o.useMemo(()=>me.filter(M=>M.metadata.variant==="dark").sort((M,le)=>M.metadata.name.localeCompare(le.metadata.name)),[me]),ga=o.useMemo(()=>Wt.find(M=>M.metadata.id===U)??Wt[0],[Wt,U]),xa=o.useMemo(()=>ft.find(M=>M.metadata.id===X)??ft[0],[ft,X]),va=o.useCallback((M,le)=>{const Ge=le==="dark"?" Dark":" Light";return M.endsWith(Ge)?M.slice(0,-Ge.length):M},[]),ue=M=>t?t.includes(M):!0,Et=ue("perfHud");o.useEffect(()=>{if(!Et||!ge){lt(!1),Xe(!1),Pt(!1),It(null);return}let M=!1;return Nn().then(le=>{M||(lt(le?.supported===!0),Xe(le?.enabled===!0),Pt(le?.active===!0),It(le?.enabled===!0&&le.active!==!0?"Recording could not start. Disable it and try again.":null))}),()=>{M=!0}},[ge,Et]),o.useEffect(()=>{if(!Et||!ge||!We)return;let M=!1;const le=window.setInterval(()=>{Nn().then(Ge=>{M||!Ge?.supported||(Pt(Ge.active),Ge.active||It("Recording stopped after a file write failure. Disable it and try again."))})},1e4);return()=>{M=!0,window.clearInterval(le)}},[ge,We,Et]);const ba=o.useCallback(async M=>{if(!$e||ns)return;const le=We,Ge=mt;Xe(M),Ss(!0),It(null);try{const qe=await oo(M);if(!qe?.supported||qe.enabled!==M||M&&!qe.active)throw new Error("Failed to update process performance recording");Xe(qe.enabled),Pt(qe.active)}catch{Xe(le),Pt(Ge),It("Failed to update process performance recording.")}finally{Ss(!1)}},[mt,We,ns,$e]),ya=ue("theme"),wa=ue("theme")||ue("timeFormat")||ue("weekStart"),Ts=s&&Rt()&&!Le(),se=ue("theme")||Ts||ue("pwaInstallName")||ue("pwaOrientation")||ue("timeFormat")||ue("weekStart"),Ne=ue("fontSize")||ue("terminalFontSize")||ue("editorFontSize")||ue("spacing")||ue("inputBarOffset")&&s,He=ue("sidebarViewMode")||ue("terminalQuickKeys")||ue("terminalShell")||ue("terminalLoginShell")||ue("fileEditorKeymap")||ue("autoSaveEnabled")||ue("expandedEditorToolbar")||ue("wrapLinesByDefault"),xe=ue("diffLayout")||ue("followUpBehavior"),ct=ue("diffLayout")||ue("followUpBehavior"),nt=se||Ne||He,ve=ue("pwaInstallName")&&Rt()&&n&&!Le(),Je=ue("pwaOrientation")&&Rt()&&!Le(),dt=ue("mobileKeyboardMode")&&Rt()&&!Le()&&lo(),rs=ue("terminalShell")||ue("terminalLoginShell"),[is,os]=o.useState([]),[Ps,ja]=o.useState(0);o.useEffect(()=>ea(()=>{os([]),ja(M=>M+1)}),[]),o.useEffect(()=>{let M=!1;if(!(!rs||!a.listShells))return a.listShells().then(le=>{M||os(le)}).catch(()=>{M||os([])}),()=>{M=!0}},[rs,a,Ps]);const ka=o.useMemo(()=>{const M=is.filter(le=>le.id!=="auto");return y==="auto"||M.some(le=>le.id===y)?M:[{id:y,name:y,supportsLogin:!1},...M]},[is,y]),Is=is.find(M=>M.id===y)?.supportsLogin===!0,Ht=v.includes(y),Es=M=>{L(M?[...v.filter(le=>le!==y),y]:v.filter(le=>le!==y))},[ls,Si]=o.useState(()=>hl()),[Ti,Gt]=o.useState(""),[Na,As]=o.useState("system"),Pi=o.useMemo(()=>xi.find(le=>le.id===ce)?.label??"Auto",[ce]),Ii=o.useMemo(()=>vi.find(le=>le.id===ie)?.label??"Auto",[ie]),Ei=o.useMemo(()=>{const M=fi.find(le=>le.id===Na);return M?M.label:void 0},[Na]),Ai=o.useMemo(()=>{const M=gi.find(le=>le.id===I);return M?M.label:void 0},[I]),Mi=o.useCallback(M=>{M!==ls&&(Si(M),fl(M),window.location.reload())},[ls]),Li=o.useCallback(async M=>{if(typeof window>"u")return;const le=window,qe=M.trim().replace(/\s+/g," ").slice(0,64);if(await Ke({pwaAppName:qe}),typeof le.__PICHAMBER_SET_PWA_INSTALL_NAME__=="function"){const vn=le.__PICHAMBER_SET_PWA_INSTALL_NAME__(qe);Gt(vn);return}Gt(qe||ms),le.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Ri=o.useCallback(async M=>{if(typeof window>"u")return;const le=window,Ge=Ga(M);if(await Ke({pwaOrientation:Ge}),typeof le.__PICHAMBER_SET_PWA_ORIENTATION__=="function"){const qe=le.__PICHAMBER_SET_PWA_ORIENTATION__(Ge);As(qe);return}As(Ge),le.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return o.useEffect(()=>{if(typeof window>"u"||!ve&&!Je&&!dt)return;let M=!1;return(async()=>{try{const Ge=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Ge.ok){M||Gt(ms);return}const qe=await Ge.json().catch(()=>({})),Di=(typeof qe?.pwaAppName=="string"?qe.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),_i=Ga(qe?.pwaOrientation),zi=fr(qe?.mobileKeyboardMode);M||(ve&&Gt(Di||ms),Je&&As(_i),dt&&S(zi))}catch{M||(ve&&Gt(ms),Je&&As("system"),dt&&S("native"))}})(),()=>{M=!0}},[S,dt,ve,Je]),e.jsxs(e.Fragment,{children:[se&&ya&&e.jsx(Wd,{themeMode:Ce,setThemeMode:re,showMobileLayoutSetting:Ts,mobileLayoutPreference:ls,onMobileLayoutPreferenceChange:Mi,selectedLightTheme:ga,setLightThemePreference:he,lightThemes:Wt,selectedDarkTheme:xa,setDarkThemePreference:je,darkThemes:ft,formatThemeLabel:va,customThemesLoading:J,themesReloading:Se,setThemesReloading:et,reloadCustomThemes:B,dockBadgeSupported:F,dockBadgeEnabled:Q,setDockBadgeEnabled:de}),He&&e.jsx(Yd,{shouldShow:ue,sidebarViewMode:pe,onSidebarViewModeChange:fa,fileEditorKeymap:K,setFileEditorKeymap:Z,autoSaveEnabled:u,setAutoSaveEnabled:m,expandedEditorToolbar:r,onExpandedEditorToolbarChange:ht,wrapLinesByDefault:d,onWrapLinesByDefaultChange:pa,showTerminalQuickKeysOnDesktop:O,setShowTerminalQuickKeysOnDesktop:V,showTerminalShellSetting:rs,terminalShell:y,setTerminalShell:b,terminalShellOptions:ka,terminalShellSupportsLogin:Is,terminalLoginShellEnabled:Ht,setTerminalLoginShellEnabled:Es}),se&&wa&&e.jsx(Hd,{shouldShowTimeFormat:ue("timeFormat"),shouldShowWeekStart:ue("weekStart"),timeFormatPreference:ce,selectedTimeFormatLabel:Pi,onTimeFormatPreferenceChange:ma,weekStartPreference:ie,selectedWeekStartLabel:Ii,onWeekStartPreferenceChange:ha}),Ne&&e.jsx(Qd,{shouldShow:ue,uiFont:P,setUiFont:A,monoFont:g,setMonoFont:C,fontSize:p,setFontSize:h,terminalFontSize:c,setTerminalFontSize:f,editorFontSize:j,setEditorFontSize:T,padding:w,setPadding:x,inputBarOffset:N,setInputBarOffset:k,isMobile:s}),e.jsx(Xd,{hasBehaviorSettings:xe,showBehaviorMessageOptions:ct,behaviorSectionDivider:nt,shouldShow:ue,diffLayoutPreference:z,setDiffLayoutPreference:_,followUpBehavior:ae,setFollowUpBehavior:fe,draftStartersVisible:G,onDraftStartersVisibleChange:ua}),ue("perfHud")&&e.jsx(Zd,{perfHudEnabled:te,onPerfHudEnabledChange:co,processRecordingSupported:$e,processRecordingEnabled:We,processRecordingActive:mt,processRecordingSaving:ns,processRecordingError:da,onProcessRecordingEnabledChange:ba}),se&&(ve||Je||dt)&&e.jsx(Pr,{label:"Show legacy options",children:e.jsx(Gd,{showPwaInstallNameSetting:ve,pwaInstallName:Ti,setPwaInstallName:Gt,onApplyPwaInstallName:Li,showPwaOrientationSetting:Je,pwaOrientation:Na,selectedPwaOrientationLabel:Ei,onApplyPwaOrientation:Ri,showMobileKeyboardModeSetting:dt,mobileKeyboardMode:I,selectedMobileKeyboardModeLabel:Ai,onSetMobileKeyboardMode:M=>{S(M),Ke({mobileKeyboardMode:M})}})})]})},eu=[{value:"system",label:"System browser"},{value:"pichamber",label:"PiChamber browser"}],tu=()=>{const t=W(i=>i.chatLinkTarget),s=W(i=>i.setChatLinkTarget),[a,n]=o.useState(!1),[r,l]=o.useState(!1),d=async()=>{l(!0);try{await il(),$.success("Browsing data cleared"),n(!1)}catch(i){$.error(i instanceof Error?i.message:"Could not clear browsing data")}finally{l(!1)}};return e.jsx(Y,{title:"Web browser",children:e.jsxs("div",{className:vt,children:[e.jsx(Pe,{settingsItem:"general.chat-link-target",label:"Open chat links in",info:"Applies to a plain click. Cmd-click, Ctrl-click, and middle-click still use the system browser.",children:e.jsx(tn,{value:t,onChange:s,options:eu})}),e.jsx(Pe,{settingsItem:"general.browser-data",label:"Browsing data",info:"Pages loaded through the server keep their cookies and sign-ins on the server, shared by every device.",children:a?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:`${at} max-w-sm [text-wrap:pretty]`,children:"This signs you out of every site in the server browser. Pages open on any device reload, signed out."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(E,{type:"button",size:"sm",variant:"destructive",disabled:r,onClick:()=>{d()},children:"Clear browsing data"}),e.jsx(E,{type:"button",size:"sm",variant:"ghost",disabled:r,onClick:()=>n(!1),children:"Cancel"})]})]}):e.jsx(E,{type:"button",size:"sm",variant:"outline",onClick:()=>n(!0),children:"Clear"})})]})})},su=1,au=365,ar=30,nu=[{value:"archive",label:"Archive"},{value:"delete",label:"Delete"}],bi=()=>{const t=W(c=>c.autoDeleteEnabled),s=W(c=>c.autoDeleteAfterDays),a=W(c=>c.sessionRetentionAction),n=W(c=>c.setAutoDeleteEnabled),r=W(c=>c.setAutoDeleteAfterDays),l=W(c=>c.setSessionRetentionAction),{candidates:d,isRunning:i,runCleanup:u,action:m}=qo({autoRun:!1}),p=d.length,h=o.useCallback(async()=>{const c=await u({force:!0});if(c.completedIds.length===0&&c.failedIds.length===0){$.message(c.action==="archive"?"No sessions eligible for archiving":"No sessions eligible for deletion");return}c.completedIds.length>0&&$.success(c.action==="archive"?`Archived ${c.completedIds.length} session(s)`:`Deleted ${c.completedIds.length} session(s)`),c.failedIds.length>0&&$.error(c.action==="archive"?`Failed to archive ${c.failedIds.length} session(s)`:`Failed to delete ${c.failedIds.length} session(s)`)},[u]);return e.jsxs(Y,{title:"Session Retention",info:"Automatically archive or delete inactive sessions based on last activity. Keeps the 5 most recent sessions.",children:[e.jsx(ke,{settingsItem:"sessions.auto-cleanup",checked:t,onChange:n,label:"Enable Auto-Cleanup",ariaLabel:"Enable auto-cleanup"}),e.jsxs(sn,{className:"space-y-0",children:[e.jsxs(Pe,{settingsItem:"sessions.retention-period",label:"Retention Period",children:[e.jsx(xt,{value:s,onValueChange:r,min:su,max:au,step:1,"aria-label":"Retention period in days",className:"w-20 tabular-nums"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days"}),e.jsx(E,{size:"sm",type:"button",variant:"ghost",onClick:()=>r(ar),disabled:s===ar,className:Qe,"aria-label":"Reset retention period",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),e.jsx(Pe,{settingsItem:"sessions.retention-action",label:"When sessions expire",children:e.jsx(tn,{value:a,onChange:l,options:nu.map(c=>({value:c.value,label:c.label}))})})]}),e.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[e.jsx(Pe,{label:"Manual Cleanup",children:e.jsx(E,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:i,className:"!font-normal",children:i?"Cleaning up...":"Run cleanup now"})}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:m==="archive"?`Eligible for archiving right now: ${p}`:`Eligible for deletion right now: ${p}`})]})]})},ru=t=>{if(!t)return;const s=t.providerId.trim(),a=t.modelId.trim();if(!(!s||!a))return`${s}/${a}`},_a=t=>{const s=Qo(t??void 0);return s?{providerId:s.providerId,modelId:s.modelId}:null},iu=(t,s={})=>{if(!t)return{};const a={};if(!s.defaultModel){const n=_a(typeof t.defaultModel=="string"?t.defaultModel:void 0);n&&(a.defaultModel=n)}if(!s.smallModel&&t.smallModelUseDefault===!1){const n=_a(typeof t.smallModelOverride=="string"?t.smallModelOverride:void 0);n&&(a.smallModel=n)}if(!s.walkthroughModel){const n=_a(typeof t.walkthroughModelOverride=="string"?t.walkthroughModelOverride:void 0);n&&(a.walkthroughModel=n)}return a},ou=t=>!!(t.defaultModel||t.smallModel||t.walkthroughModel),za=()=>({runtimeKey:Ve()}),_s="__pi_fallback__",lu=(t,s)=>{const a=[...t];return s&&!a.includes(s)&&a.push(s),a},yi=()=>{const t=Fe(x=>x.providers),s=Fe(x=>x.modelsMetadata),a=Fe(x=>x.loadProviders),n=Fe(x=>x.setProvider),r=Fe(x=>x.setModel),l=Fe(x=>x.setSettingsDefaultModel),d=Fe(x=>x.setSettingsDefaultThinking),i=Fe(x=>x.setSettingsDefaultThinkingByModel),u=W(x=>x.showDeletionDialog),m=W(x=>x.setShowDeletionDialog),[p,h]=o.useState(null),[c,f]=o.useState("loading"),y=o.useCallback(x=>{h(x),l(ru(x.defaultModel)),d(x.defaultThinking),i(x.defaultThinkingByModel??{})},[l,d,i]);o.useEffect(()=>{a({source:"sessionsDefaults"}),Fe.getState().ensureModelMetadata()},[a]),o.useEffect(()=>{let x=!0;return(async()=>{try{const k=await Me.getSettings(za());if(!x)return;let I=k.pichamber;if(!I.defaultModel&&!I.smallModel&&!I.walkthroughModel){const S=Ya()?.settings;if(S)try{const z=await S.load(),_=iu(z?.settings,I);if(ou(_)){const O=await Me.setPiChamberDefaults(_,za());if(!x)return;I=O.pichamber,await Ke({defaultModel:"",smallModelOverride:"",walkthroughModelOverride:""})}}catch{}}if(!x)return;y(I),f("ready")}catch{x&&f("failed")}})(),()=>{x=!1}},[y]);const b=o.useCallback(async x=>{it("saving");try{const N=await Me.setPiChamberDefaults(x,za());y(N.pichamber),it("saved")}catch{it("error")}},[y]),v=o.useCallback((x,N)=>{const k=t.find(S=>S.id===x);return(Array.isArray(k?.models)?k.models:[]).find(S=>S.id===N)},[t]),L=o.useCallback(x=>{x&&t.find(k=>k.id===x.providerId)&&(n(x.providerId),r(x.modelId)),b({defaultModel:x})},[b,t,r,n]),j=o.useCallback((x,N)=>{const k=Hs(x);k&&b({defaultThinkingByModel:{[k]:N}})},[b]),T=o.useCallback((x,N)=>s.get(`${x}/${N}`)?.structured_output!==!1,[s]);if(c==="loading")return null;if(c==="failed"&&!p)return e.jsx(Y,{title:"Session Defaults",divider:!1,children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Session defaults are unavailable."})});const P=Hs(p?.defaultModel),A=p?.defaultModel?v(p.defaultModel.providerId,p.defaultModel.modelId):void 0,g=jr(A),C=!!(p?.defaultModel&&kr(g)),w=P?p?.defaultThinkingByModel?.[P]:void 0;return e.jsx(Y,{title:"Session Defaults",divider:!1,info:"New sessions use these models. Leave a picker on its fallback to keep Pi's own default.",children:e.jsxs("div",{className:vt,children:[e.jsx(Pe,{settingsItem:"sessions.default-model",label:"Default Model",info:"The model new sessions start with. Unset keeps Pi's default.",children:e.jsx(Pa,{value:p?.defaultModel??null,noneLabel:"Default",ariaLabel:"Default model",onChange:L})}),C&&p?.defaultModel?e.jsx(Pe,{settingsItem:"sessions.default-thinking",label:"Default Thinking",info:"Thinking level for new sessions that start with the default model. Unset keeps Pi's default for that model.",children:e.jsxs(_e,{value:w??_s,onValueChange:x=>{j(p.defaultModel,x===_s?null:x)},children:[e.jsx(ze,{size:Be,className:ra,"aria-label":"Default thinking",children:e.jsx(Oe,{children:x=>x===_s?"Default":x?Ws[x]??x:""})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:_s,children:"Default"}),lu(g,w).map(x=>e.jsx(ye,{value:x,children:Ws[x]},x))]})]})}):null,e.jsx(Pe,{settingsItem:"sessions.small-model",label:"Small Model",info:"A cheap model for quick utility tasks like short recaps and summaries.",children:e.jsx(Pa,{value:p?.smallModel??null,noneLabel:"Use default small model",ariaLabel:"Small model",onChange:x=>{b({smallModel:x})}})}),e.jsx(Pe,{settingsItem:"sessions.walkthrough-model",label:"Changes Walkthrough Model",info:"The AI review of your changes needs structured output and room for a whole diff, which a cheap small model often cannot give. Models the catalog reports as unable to produce structured output are hidden from this picker. Leave it unset and the small model is used.",children:e.jsx(Pa,{value:p?.walkthroughModel??null,noneLabel:"Small model",ariaLabel:"Changes walkthrough model",isModelAllowed:T,onChange:x=>{b({walkthroughModel:x})}})}),e.jsx(Pe,{settingsItem:"sessions.default-retry-limit",label:"Default retry limit",info:"How many times Pi automatically retries a failed agent turn before stopping. Applies to new sessions when no per-run limit is set. Set to 0 to disable automatic retries. Existing sessions keep their own limit until you change it.",children:e.jsx("div",{className:es,children:e.jsxs("div",{className:Qt,children:[e.jsx(xt,{value:p?.defaultRetryLimit??3,min:0,max:10,step:1,"aria-label":"Default retry limit",onValueChange:x=>{if(!Number.isFinite(x))return;const N=Math.max(0,Math.min(10,Math.round(x)));b({defaultRetryLimit:N})}}),e.jsx("span",{className:Jt,children:"retries"})]})})}),e.jsx(sn,{className:pt,children:e.jsx(ke,{settingsItem:"sessions.deletion-dialog",checked:u,onChange:m,label:"Show Deletion Dialog",ariaLabel:"Show deletion dialog"})})]})})},cu=()=>{const t=o.useMemo(()=>Le(),[]),s=o.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),a=!t&&!s,n=W(j=>j.nativeNotificationsEnabled),r=W(j=>j.setNativeNotificationsEnabled),l=W(j=>j.notificationMode),d=W(j=>j.setNotificationMode),i=W(j=>j.notifyOnCompletion),u=W(j=>j.setNotifyOnCompletion),m=W(j=>j.notifyOnError),p=W(j=>j.setNotifyOnError),h=W(j=>j.notifyOnInputNeeded),c=W(j=>j.setNotifyOnInputNeeded),[f,y]=o.useState("default");o.useEffect(()=>{a&&typeof Notification<"u"&&y(Notification.permission)},[a]);const b=async j=>{if(t){r(j);return}if(!a){r(j);return}if(j&&typeof Notification<"u"&&Notification.permission==="default")try{const T=await Notification.requestPermission();y(T),T==="granted"?r(!0):$.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(T){console.error("Failed to request notification permission:",T),$.error("Failed to request notification permission")}else r(!!(j&&f==="granted"))},v=t||s||a&&typeof Notification<"u"&&Notification.permission==="granted",L=async()=>{const j=Ya();if(!j?.notifications){$.error("Notifications API not available");return}try{await j.notifications.notify({title:"Test notification",body:"Notifications are working.",tag:"pichamber-test"})?$.success("Test notification sent successfully"):$.error("Failed to send test notification")}catch(T){console.error("Test notification failed:",T),$.error("Failed to send test notification")}};return e.jsxs(e.Fragment,{children:[e.jsxs(Y,{settingsItem:"notifications.delivery",title:"Notification delivery",divider:!1,children:[e.jsxs("div",{className:pt,children:[e.jsx(ke,{checked:n&&v,onChange:j=>{b(j)},label:"Enable notifications",info:a?"Your browser may ask for permission the first time.":void 0,ariaLabel:"Enable notifications"}),n&&v&&!s&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{checked:l==="always",onChange:j=>d(j?"always":"hidden-only"),label:"Notify while app is focused",ariaLabel:"Notify while app is focused"}),e.jsx("div",{className:"py-2",children:e.jsx(E,{type:"button",variant:"outline",size:"sm",onClick:()=>{L()},children:"Send test notification"})})]})]}),a&&e.jsxs("div",{className:"mt-1",children:[f==="denied"&&e.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:"Notification permission denied. Enable it in your browser settings."}),f==="granted"&&!n&&e.jsx("p",{className:"typography-meta text-muted-foreground/70 mt-1",children:"Permission granted, but notifications are disabled."})]})]}),n&&v&&e.jsx(e.Fragment,{children:e.jsx(Y,{settingsItem:"notifications.events",title:"Notification events",children:e.jsxs("div",{className:pt,children:[e.jsx(ke,{checked:i,onChange:u,label:"Work completed",ariaLabel:"Notify when work is completed"}),e.jsx(ke,{checked:m,onChange:p,label:"Errors",ariaLabel:"Notify when work fails"}),e.jsx(ke,{checked:h,onChange:c,label:"Input needed",ariaLabel:"Notify when an extension is waiting for your answer",info:"When an extension is waiting for your answer."})]})})})]})},Fs=[{value:"1800000",label:"30m",ms:1800*1e3},{value:"180000",label:"3m",ms:180*1e3},{value:"7200000",label:"2h",ms:7200*1e3},{value:"28800000",label:"8h",ms:480*60*1e3},{value:"86400000",label:"24h",ms:1440*60*1e3}],Bs=[{value:"3600000",label:"1h",ms:3600*1e3},{value:"28800000",label:"8h",ms:480*60*1e3},{value:"43200000",label:"12h",ms:720*60*1e3},{value:"86400000",label:"24h",ms:1440*60*1e3},{value:"604800000",label:"1w",ms:10080*60*1e3},{value:"2592000000",label:"30d",ms:720*60*60*1e3}],du="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",uu="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",qa=[{value:"managed-remote",label:"Managed Remote",tooltip:"Managed Remote uses your Cloudflare account and hostname for long-lived access."},{value:"managed-local",label:"Managed Local",tooltip:"Managed Local uses your local cloudflared configuration file."}],pu=[".yml",".yaml",".json"],mu="Config file must use .yml, .yaml, or .json extension.",hs=t=>{const s=t.trim().toLowerCase();return pu.some(a=>s.endsWith(a))},hu=()=>"cloudflared",wi=()=>{if(typeof window<"u"&&typeof window.__PICHAMBER_PLATFORM__=="string"){const s=window.__PICHAMBER_PLATFORM__;if(s==="win32"||s==="darwin"||s==="linux")return s}const t=typeof navigator<"u"?`${navigator.platform||""} ${navigator.userAgent||""}`.toLowerCase():"";return t.includes("win")?"win32":t.includes("mac")?"darwin":"linux"},fu=(t=wi())=>t==="win32"?"winget install --id Cloudflare.cloudflared":t==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",Oa=(t,s)=>{const a=typeof s?.provider=="string"&&s.provider.trim().length>0?s.provider.trim().toLowerCase():t,n=typeof s?.dependency=="string"&&s.dependency.trim().length>0?s.dependency.trim():hu(),r=typeof s?.platform=="string"&&s.platform.trim().length>0?s.platform.trim():wi(),l=typeof s?.installCommand=="string"&&s.installCommand.trim().length>0?s.installCommand.trim():fu(r);return{provider:a,dependency:n,installCommand:l}},gu=t=>t==="cloudflare"?"Cloudflare":t,At=t=>t==="managed-local"?"managed-local":"managed-remote",Qa=(t,s,a)=>t.find(r=>r.ms===s)?.value||a,nr=(t,s,a)=>{const n=Qa(t,s,a);return t.find(r=>r.value===n)?.label||n},ji=t=>{const s=Math.max(0,t),a=Math.floor(s/1e3),n=Math.floor(a/3600),r=Math.floor(a%3600/60),l=a%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${l}s`:`${l}s`},xu=(t,s)=>Jo(t,s,{hour:"2-digit",precision:"second"}),Zs=t=>{const s=t.trim();if(!s)return"";try{return(s.includes("://")?new URL(s):new URL(`https://${s}`)).hostname.trim().toLowerCase()}catch{return s.toLowerCase()}},vu=t=>{if(!Array.isArray(t))return[];const s=new Set,a=new Set,n=[];for(const r of t){if(!r||typeof r!="object")continue;const l=r,d=typeof l.id=="string"?l.id.trim():"",i=typeof l.name=="string"?l.name.trim():"",u=Zs(typeof l.hostname=="string"?l.hostname:"");!d||!i||!u||s.has(d)||a.has(u)||(s.add(d),a.add(u),n.push({id:d,name:i,hostname:u}))}return n},bu=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,yu=({provider:t})=>{const s=gu(t),a=t==="cloudflare";return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"cloud",className:H("size-4 shrink-0",a?"text-[var(--status-warning)]":"text-muted-foreground")}),e.jsx("span",{children:s})]})},wu=({records:t,timeFormatPreference:s})=>t.length===0?null:e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)]/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(R,{name:"information",className:"size-4 text-[var(--status-info)]"}),e.jsx("p",{className:Ar,children:"Redeemed access links"})]}),e.jsx("div",{className:"space-y-1",children:t.map(a=>{const n=a.mode==="managed-remote",r=n?"border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)]":"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",l=a.isActive?n?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",d=n?"REMOTE":"LOCAL";return e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded border border-[var(--surface-subtle)] bg-[var(--surface-elevated)] px-2 py-1.5",children:[e.jsx(R,{name:"checkbox-blank-circle-fill",className:H("size-2.5 shrink-0",l)}),e.jsx("span",{className:H("typography-micro rounded border px-1.5 py-0.5 uppercase",r),children:d}),e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:`Redeemed ${xu(a.createdAt,s)}`}),e.jsx("span",{className:"typography-meta text-foreground",children:a.isActive?`Expires in ${a.remainingTextForSession}`:a.inactiveLabel==="Inactive"?"Inactive":`Inactive (${a.inactiveLabel})`})]},a.sessionId)})})]})}),ju=({installInfo:t})=>e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning)]/30 bg-[var(--status-warning)]/5 p-3",children:[e.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:Ar,children:`${t.dependency} was not found.`}),e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Install it to enable remote tunnel access:"}),e.jsx("code",{className:"typography-code block rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.installCommand})]})]})}),ku=({bootstrapTtlMs:t,sessionTtlMs:s,disabled:a,onBootstrapTtlChange:n,onSessionTtlChange:r})=>e.jsxs("div",{"data-settings-item":"tunnel.ttl",className:"mt-2 grid grid-cols-1 gap-2 py-1.5 md:grid-cols-[14rem_auto] md:gap-x-8 md:gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:H(Ae,"shrink-0"),children:"Connect link TTL"}),e.jsxs(_e,{value:Qa(Fs,t,"1800000"),onValueChange:n,disabled:a,children:[e.jsx(ze,{size:Be,className:"max-w-[11rem] min-w-0",children:e.jsx(Oe,{className:"truncate",children:nr(Fs,t,"1800000")})}),e.jsx(Ue,{children:Fs.map(l=>e.jsx(ye,{value:l.value,children:l.label},l.value))})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:H(Ae,"shrink-0"),children:"Tunnel session TTL"}),e.jsxs(_e,{value:Qa(Bs,s,"28800000"),onValueChange:r,disabled:a,children:[e.jsx(ze,{size:Be,className:"max-w-[11rem] min-w-0",children:e.jsx(Oe,{className:"truncate",children:nr(Bs,s,"28800000")})}),e.jsx(Ue,{children:Bs.map(l=>e.jsx(ye,{value:l.value,children:l.label},l.value))})]})]})]}),Nu=({suggestedConnectorPort:t,managedRemoteTunnelPresets:s,expandedManagedRemoteTunnels:a,sessionTokensByPresetId:n,savedTokenPresetIds:r,disabled:l,isAddingPreset:d,newPresetName:i,newPresetHostname:u,newPresetToken:m,managedRemoteValidationError:p,selectedPreset:h,onToggleAddPreset:c,onCancelAddPreset:f,onNewPresetNameChange:y,onNewPresetHostnameChange:b,onNewPresetTokenChange:v,onSaveNewPreset:L,onTogglePresetCollapse:j,onRemovePreset:T,onPresetTokenChange:P,onPersistToken:A})=>e.jsxs("div",{"data-settings-item":"tunnel.managed-remote",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[typeof t=="number"&&e.jsx("div",{className:"rounded-md border border-[var(--status-info-border)] bg-[var(--status-info-background)]/35 px-2 py-1.5",children:e.jsxs("p",{className:"typography-meta text-[var(--status-info)]",children:["Cloudflare connector target:"," ",e.jsxs("code",{children:["http://localhost:",t]})]})}),e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[e.jsx(Ir,{children:"Saved managed remote tunnels"}),e.jsxs(E,{variant:"ghost",size:"xs",className:"!font-normal",onClick:c,disabled:l,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Create"]})]}),s.length>0?e.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:s.map((g,C)=>{const w=n[g.id]||"",x=r.has(g.id),N=a[g.id]??!1;return e.jsx("div",{className:H(C<s.length-1&&"border-b border-[var(--surface-subtle)]"),children:e.jsxs(gl,{open:N,onOpenChange:k=>j(g.id,k),className:"py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3",children:[e.jsxs(xl,{type:"button",className:"group flex-1 justify-start gap-2 rounded-md px-0 py-1 pr-1 text-left hover:bg-[var(--interactive-hover)]",disabled:l,children:[N?e.jsx(R,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):e.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label min-w-0 flex-1 truncate text-foreground",children:g.name})]}),e.jsx(E,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":`Remove ${g.name}`,onClick:()=>T(g.id),disabled:l,children:e.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsx(vl,{className:"pt-1.5",children:e.jsxs("div",{className:"space-y-1 px-3 pb-2",children:[e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["Hostname:"," ",e.jsx("code",{children:g.hostname})]}),e.jsx(ee,{type:"password",value:w,onChange:k=>P(g.id,k.target.value),onBlur:k=>{const I=k.currentTarget.value.trim();I&&A({presetId:g.id,presetName:g.name,hostname:g.hostname,token:I})},placeholder:x?"Saved token available (optional to replace)":"Paste token for this tunnel",className:"h-7",disabled:l}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(E,{variant:"ghost",size:"xs",className:"!font-normal",disabled:l||w.trim().length===0,onClick:()=>{A({presetId:g.id,presetName:g.name,hostname:g.hostname,token:w})},children:"Save token"})})]})})]})},g.id)})}):e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"No managed remote tunnels saved yet."}),d&&e.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[e.jsx(ee,{value:i,onChange:g=>y(g.target.value),placeholder:"Tunnel name (e.g. Production)",className:"h-7",disabled:l}),e.jsx(ee,{value:u,onChange:g=>b(g.target.value),placeholder:"Hostname (e.g. oc.example.com)",className:"h-7",disabled:l}),e.jsx(ee,{type:"password",value:m,onChange:g=>v(g.target.value),placeholder:"Token",className:"h-7",disabled:l}),typeof t=="number"&&e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["For Cloudflare connector target, use"," ",e.jsxs("code",{children:["http://localhost:",t]}),"."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(E,{variant:"ghost",size:"xs",className:"!font-normal",onClick:L,disabled:l,children:"Save Changes"}),e.jsx(E,{variant:"ghost",size:"xs",className:"!font-normal",onClick:f,disabled:l,children:"Cancel"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Tokens are saved per tunnel and reused from disk."}),e.jsx(ys,{children:"Tokens are saved in ~/.config/pichamber/cloudflare-managed-remote-tunnels.json."})]}),!h&&p&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:p})]}),Cu=({managedLocalConfigPath:t,isManagedLocalConfigPathInvalid:s,managedLocalConfigExtensionError:a,disabled:n,fileInputRef:r,onInputChange:l,onInputBlur:d,onBrowse:i,onClear:u,onFileSelected:m})=>e.jsx("div",{"data-settings-item":"tunnel.managed-local-config",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:Ae,children:"Configuration file"}),e.jsx("input",{ref:r,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:m}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{value:t||"",onChange:p=>l(p.target.value),onBlur:d,placeholder:"Using default cloudflared config",className:"h-7",disabled:n}),e.jsx(E,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":"Browse config file",onClick:i,disabled:n,children:e.jsx(R,{name:"folder",className:"size-3.5"})}),t&&e.jsx(E,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":"Clear config file",onClick:u,disabled:n,children:e.jsx(R,{name:"close",className:"size-3.5"})})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t?"Custom config file will be used when starting the tunnel.":"When empty, cloudflared uses its default config (~/.cloudflared/config.yml)."}),s&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:a})]})}),Su=({tunnelMode:t,selectedPresetId:s,managedRemoteTunnelPresets:a,selectedPreset:n,willReplaceActiveTunnel:r,state:l,isSavingMode:d,isManagedLocalConfigPathInvalid:i,primaryCtaClass:u,onSelectPreset:m,onStart:p,onOpenDocUrl:h})=>e.jsxs("div",{"data-settings-item":"tunnel.start",className:"space-y-6",children:[e.jsx("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)] p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(R,{name:"information",className:"mt-0.5 size-4 shrink-0 text-[var(--status-info)]"}),e.jsxs("div",{className:"space-y-1",children:[t==="managed-remote"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed remote tunnels require a purchased domain in your Cloudflare account."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{h(du)},children:["Check documentation on how to configure a managed remote tunnel",e.jsx(R,{name:"external-link",className:"size-3.5"})]})]}),t==="managed-local"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed local tunnels use your local cloudflared configuration file."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{h(uu)},children:["Check documentation on managed local tunnel configuration",e.jsx(R,{name:"external-link",className:"size-3.5"})]})]}),e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:`Start a ${qa.find(c=>c.value===t)?.label??"Managed Remote"} tunnel and generate a one-time connect link. Do not close the app while this tunnel is in use.`})]})]})}),t==="managed-remote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:Ae,children:"Managed remote tunnel to connect"}),e.jsxs(_e,{value:s||(a[0]?.id??""),onValueChange:m,disabled:d||l==="starting"||l==="stopping"||a.length<=1,children:[e.jsx(ze,{size:Be,children:e.jsx(Oe,{placeholder:"Select saved tunnel",children:n?.name})}),e.jsx(Ue,{fitContent:!0,children:a.map(c=>e.jsx(ye,{value:c.id,children:c.name},c.id))})]})]}),r&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:"Starting this tunnel replaces the active tunnel and revokes existing connect links and remote sessions."})]})}),e.jsx(E,{size:"sm",variant:"outline",onClick:p,disabled:l==="starting"||d||t==="managed-remote"&&!n||t==="managed-local"&&i,className:H(u,l==="starting"&&"opacity-70"),children:l==="starting"?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Starting tunnel..."]}):"Start Tunnel"})]}),Tu=({tunnelInfo:t,isConnectLinkLive:s,copied:a,onCopyUrl:n,remainingText:r,qrDataUrl:l,onNewConnectLink:d,onStop:i,stopping:u,isSavingMode:m,isManagedLocalConfigPathInvalid:p,tunnelMode:h,primaryCtaClass:c})=>e.jsxs("section",{"data-settings-item":"tunnel.start",className:"space-y-4 px-2 pb-2 pt-0",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"size-2 shrink-0 rounded-full bg-[var(--status-success)]"}),e.jsx("p",{className:"typography-meta font-medium text-foreground",children:"Tunnel ready"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:"Public URL (not accessible without a token)"}),e.jsx("code",{className:"typography-code block truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.url})]}),s&&t.connectUrl&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:"Connect link"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"typography-code flex-1 truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.connectUrl}),e.jsxs(E,{size:"sm",variant:"ghost",onClick:n,className:"shrink-0 gap-1.5",children:[a?e.jsx(R,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):e.jsx(R,{name:"file-copy",className:"size-3.5"}),a?"Copied":"Copy all"]})]}),e.jsxs("p",{className:"typography-meta mt-1 text-muted-foreground/70",children:["Expires",": ",t.bootstrapExpiresAt?r:"Never"]})]}),e.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border border-border/50 bg-[var(--surface-elevated)] p-4",children:[l?e.jsx("img",{src:l,alt:"Tunnel connect QR code",className:"size-48"}):e.jsx("div",{className:"size-48 rounded bg-muted/30"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Scan with your phone to connect."})]})]})]}),e.jsx("div",{className:"pt-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(E,{size:"sm",variant:"outline",onClick:d,disabled:u||m||h==="managed-local"&&p,className:c,children:[e.jsx(R,{name:"restart",className:"size-3.5"}),"New connect link"]}),e.jsx(E,{size:"sm",variant:"ghost",onClick:i,disabled:u||m,className:"gap-2 text-[var(--status-error)]",children:u?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Stopping..."]}):"Stop Tunnel"})]})})]});function Pu({saveTunnelSettings:t,setManagedRemoteValidationError:s}){const[a,n]=o.useState([]),[r,l]=o.useState({}),[d,i]=o.useState(""),[u,m]=o.useState({}),[p,h]=o.useState(new Set),[c,f]=o.useState(!1),[y,b]=o.useState(""),[v,L]=o.useState(""),[j,T]=o.useState(""),P=o.useMemo(()=>a.find(N=>N.id===d)||a[0]||null,[a,d]),A=o.useCallback(async N=>{const k=N.token.trim();if(k)try{const I={...u,[N.presetId]:k};await Ke({managedRemoteTunnelPresetTokens:I}),h(S=>{const z=new Set(S);return z.add(N.presetId),z})}catch{$.error("Failed to save managed remote tunnel token")}},[u]),g=o.useCallback(async(N,k)=>{try{await Ke({managedRemoteTunnelPresets:k})}catch{$.error("Failed to save selected managed remote tunnel")}},[]),C=o.useCallback(N=>{const k=a.find(I=>I.id===N);k&&(i(k.id),s(null),g(k,a))},[a,g,s]),w=o.useCallback(async()=>{const N=y.trim(),k=Zs(v),I=j.trim();if(!N){$.error("Tunnel name is required");return}if(!k){$.error("Managed remote tunnel hostname is required");return}if(!I){$.error("Managed remote tunnel token is required");return}if(a.some(_=>_.hostname===k)){$.error("This hostname already exists");return}const S={id:bu(),name:N,hostname:k},z=[...a,S];n(z),i(S.id),l(_=>({..._,[S.id]:!0})),m(_=>({..._,[S.id]:I})),s(null),f(!1),b(""),L(""),T(""),await t({tunnelMode:"managed-remote",managedRemoteTunnelPresets:z,managedRemoteTunnelPresetTokens:{...u,[S.id]:I}}),await A({presetId:S.id,presetName:S.name,hostname:S.hostname,token:I}),$.success("Managed remote tunnel saved")},[a,v,y,j,A,t,u,s]),x=o.useCallback(async N=>{const k=a.find(O=>O.id===N);if(!k)return;const I=a.filter(O=>O.id!==k.id),S=I[0]?.id||"",z=d===k.id?S:d,_=Object.fromEntries(Object.entries(u).filter(([O,V])=>O!==k.id&&V.trim().length>0));n(I),i(z),l(O=>{const V={...O};return delete V[k.id],V}),m(O=>{const V={...O};return delete V[k.id],V}),h(O=>{const V=new Set(O);return V.delete(k.id),V}),s(null),await t({managedRemoteTunnelPresets:I,managedRemoteTunnelPresetTokens:_}),$.success("Managed remote tunnel removed")},[a,t,d,u,s]);return{managedRemoteTunnelPresets:a,setManagedRemoteTunnelPresets:n,expandedManagedRemoteTunnels:r,setExpandedManagedRemoteTunnels:l,selectedPresetId:d,setSelectedPresetId:i,sessionTokensByPresetId:u,setSessionTokensByPresetId:m,savedTokenPresetIds:p,setSavedTokenPresetIds:h,isAddingPreset:c,setIsAddingPreset:f,newPresetName:y,setNewPresetName:b,newPresetHostname:v,setNewPresetHostname:L,newPresetToken:j,setNewPresetToken:T,selectedPreset:P,persistManagedRemoteTunnelToken:A,handleSelectPreset:C,handleSaveNewPreset:w,handleRemovePreset:x}}function Iu({saveTunnelSettings:t}){const[s,a]=o.useState(null),n=mu,r=o.useRef(null),l=o.useMemo(()=>s?!hs(s):!1,[s]),d=o.useCallback(async()=>{const h=await uo({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(h.success&&typeof h.path=="string"&&h.path.trim().length>0){const c=h.path.trim();if(!hs(c)){$.error(n);return}a(c),await t({managedLocalTunnelConfigPath:c});return}r.current?.click()},[n,t]),i=o.useCallback(h=>{const c=h.trim();a(c.length>0?c:null)},[]),u=o.useCallback(async()=>{if(s&&!hs(s)){$.error(n);return}await t({managedLocalTunnelConfigPath:s})},[n,s,t]),m=o.useCallback(async()=>{a(null),await t({managedLocalTunnelConfigPath:null})},[t]),p=o.useCallback(async h=>{const c=h.target.files?.[0];if(!c)return;const f=c.name.trim();if(f.length!==0){if(!hs(f)){$.error(n);return}a(f),await t({managedLocalTunnelConfigPath:f}),h.target.value=""}},[n,t]);return{managedLocalConfigPath:s,setManagedLocalConfigPath:a,managedLocalConfigExtensionError:n,managedLocalConfigFileInputRef:r,isManagedLocalConfigPathInvalid:l,handleBrowseManagedLocalConfig:d,handleManagedLocalConfigInputChange:i,handleManagedLocalConfigInputBlur:u,handleManagedLocalConfigClear:m,handleManagedLocalConfigFileSelected:p}}function Eu(){const[t,s]=o.useState(18e5),[a,n]=o.useState(480*60*1e3),[r,l]=o.useState(!1),d=o.useCallback(async(m,p)=>{l(!0);try{await Ke({tunnelBootstrapTtlMs:m,tunnelSessionTtlMs:p})}catch{$.error("Failed to save tunnel TTL settings")}finally{l(!1)}},[]),i=o.useCallback(async m=>{const p=Fs.find(h=>h.value===m);p&&(s(p.ms),await d(p.ms,a))},[d,a]),u=o.useCallback(async m=>{const p=Bs.find(h=>h.value===m);!p||p.ms===null||(n(p.ms),await d(t,p.ms))},[t,d]);return{bootstrapTtlMs:t,setBootstrapTtlMs:s,sessionTtlMs:a,setSessionTtlMs:n,isSavingTtl:r,saveTtlSettings:d,handleBootstrapTtlChange:i,handleSessionTtlChange:u}}function Au({tunnelInfo:t,state:s,setSessionRecords:a,setSavedTokenPresetIds:n,setLocalPort:r}){const[l,d]=o.useState(null),[i,u]=o.useState(""),[m,p]=o.useState(()=>Date.now());return o.useEffect(()=>{if(!t?.connectUrl){d(null);return}let h=!1;return Mr.toDataURL(t.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(c=>{h||d(c)}).catch(()=>{h||d(null)}),()=>{h=!0}},[t?.connectUrl]),o.useEffect(()=>{if(!t?.bootstrapExpiresAt){u("No expiry");return}let h=null,c=Date.now();const f=()=>{const v=t.bootstrapExpiresAt?t.bootstrapExpiresAt-Date.now():0;v<=0?u("Expired"):u(ji(v))},y=()=>{const v=Date.now();v-c>=1e3&&(f(),c=v),h=requestAnimationFrame(y)};f(),(typeof document>"u"||document.visibilityState==="visible")&&(h=requestAnimationFrame(y));const b=()=>{document.visibilityState==="visible"&&h===null?h=requestAnimationFrame(y):document.visibilityState!=="visible"&&h!==null&&(cancelAnimationFrame(h),h=null)};return document.addEventListener("visibilitychange",b),()=>{document.removeEventListener("visibilitychange",b),h!==null&&cancelAnimationFrame(h)}},[t?.bootstrapExpiresAt]),o.useEffect(()=>{let h=null,c=Date.now();const f=()=>{const b=Date.now();b-c>=1e3&&(p(b),c=b),h=requestAnimationFrame(f)};(typeof document>"u"||document.visibilityState==="visible")&&(h=requestAnimationFrame(f));const y=()=>{document.visibilityState==="visible"&&h===null?h=requestAnimationFrame(f):document.visibilityState!=="visible"&&h!==null&&(cancelAnimationFrame(h),h=null)};return document.addEventListener("visibilitychange",y),()=>{document.removeEventListener("visibilitychange",y),h!==null&&cancelAnimationFrame(h)}},[]),o.useEffect(()=>{if(s==="starting"||s==="stopping"||s==="checking")return;let h=!1;const c=async()=>{try{const y=await Te("/api/pichamber/tunnel/status");if(!y.ok||h)return;const b=await y.json();if(h)return;a(Array.isArray(b.activeSessions)?b.activeSessions:[]),n(()=>new Set(Array.isArray(b.managedRemoteTunnelTokenPresetIds)?b.managedRemoteTunnelTokenPresetIds:[])),r(typeof b.localPort=="number"?b.localPort:null)}catch{}},f=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||c()},5e3);return()=>{h=!0,window.clearInterval(f)}},[r,n,a,s]),{qrDataUrl:l,remainingText:i,nowTs:m}}function Mu(){const t=W(se=>se.timeFormatPreference),[s,a]=o.useState("checking"),[n,r]=o.useState(null),[l,d]=o.useState(null),[i,u]=o.useState(null),[m,p]=o.useState(null),[h,c]=o.useState(!1),[f,y]=o.useState(!1),[b,v]=o.useState("cloudflare"),[L,j]=o.useState(()=>Oa("cloudflare")),[T,P]=o.useState([]),[A,g]=o.useState("managed-remote"),[C,w]=o.useState([]),[x,N]=o.useState(null),{bootstrapTtlMs:k,setBootstrapTtlMs:I,sessionTtlMs:S,setSessionTtlMs:z,isSavingTtl:_,handleBootstrapTtlChange:O,handleSessionTtlChange:V}=Eu(),K=o.useCallback(async se=>{y(!0);try{await Ke(se),Object.prototype.hasOwnProperty.call(se,"tunnelMode")&&se.tunnelMode&&g(se.tunnelMode),Object.prototype.hasOwnProperty.call(se,"tunnelProvider")&&typeof se.tunnelProvider=="string"&&v(se.tunnelProvider)}catch{$.error("Failed to save tunnel settings")}finally{y(!1)}},[]),Z=Pu({saveTunnelSettings:K,setManagedRemoteValidationError:p}),{managedRemoteTunnelPresets:ae,setManagedRemoteTunnelPresets:fe,expandedManagedRemoteTunnels:ce,setExpandedManagedRemoteTunnels:be,selectedPresetId:ie,setSelectedPresetId:ne,sessionTokensByPresetId:pe,setSessionTokensByPresetId:oe,savedTokenPresetIds:G,setSavedTokenPresetIds:q,isAddingPreset:Ce,setIsAddingPreset:re,newPresetName:me,setNewPresetName:J,newPresetHostname:B,setNewPresetHostname:U,newPresetToken:X,setNewPresetToken:he,selectedPreset:je,persistManagedRemoteTunnelToken:Se,handleSelectPreset:et,handleSaveNewPreset:F,handleRemovePreset:Q}=Z,de=Iu({saveTunnelSettings:K}),{managedLocalConfigPath:te,setManagedLocalConfigPath:ge,managedLocalConfigExtensionError:$e,managedLocalConfigFileInputRef:lt,isManagedLocalConfigPathInvalid:We,handleBrowseManagedLocalConfig:Xe,handleManagedLocalConfigInputChange:mt,handleManagedLocalConfigInputBlur:Pt,handleManagedLocalConfigClear:ns,handleManagedLocalConfigFileSelected:Ss}=de,da=o.useCallback(se=>{q(se)},[q]),{qrDataUrl:It,remainingText:ua,nowTs:ht}=Au({tunnelInfo:n,state:s,setSessionRecords:w,setSavedTokenPresetIds:da,setLocalPort:N}),pa=o.useMemo(()=>C.map(se=>{const Ne=se.expiresAt<=ht,He=se.status==="active"&&!Ne,xe=He?ji(se.expiresAt-ht):se.inactiveReason==="expired"||Ne?"expired":"inactive",ct=xe==="expired"?"Expired":se.inactiveReason==="tunnel-revoked"?"Revoked":"Inactive",nt=At(se.mode);return{...se,isActive:He,mode:nt,remainingTextForSession:xe,inactiveLabel:ct}}),[ht,C]),ma=o.useMemo(()=>n?.connectUrl?n.bootstrapExpiresAt===null?!0:n.bootstrapExpiresAt>ht:!1,[ht,n?.bootstrapExpiresAt,n?.connectUrl]),ha=o.useMemo(()=>!n||s!=="active"&&s!=="stopping"?!1:l===A,[l,s,n,A]),fa=o.useMemo(()=>!n||s!=="active"||!l?!1:l!==A,[l,s,n,A]),Wt=o.useMemo(()=>{if(typeof x=="number"&&Number.isFinite(x)&&x>0)return x;if(typeof window>"u")return null;const Ne=ot()||window.location.href;let He=0;try{He=Number(new URL(Ne).port)}catch{He=Number(window.location.port)}return Number.isFinite(He)&&He>0?He:null},[x]),ft=o.useMemo(()=>T.find(se=>se.provider===b)??null,[T,b]),ga=o.useMemo(()=>{const se=new Set(ft?.modes?.map(Ne=>Ne.key).filter(Ne=>Ne==="managed-remote"||Ne==="managed-local"));return se.size===0?qa:qa.filter(Ne=>se.has(Ne.value))},[ft]),xa=o.useMemo(()=>L.provider===b?L:Oa(b),[L,b]),va=o.useCallback(async se=>{await fs(se)},[]),ue=o.useCallback((se,Ne)=>(j(Oa(Ne,se)),se.available===!0),[]),Et=o.useCallback(async se=>{try{const[Ne,He,xe,ct]=await Promise.all([Te("/api/pichamber/tunnel/check",{signal:se}),Te("/api/pichamber/tunnel/status",{signal:se}),Te("/api/pi/ui-settings",{signal:se,headers:{Accept:"application/json"}}),Te("/api/pichamber/tunnel/providers",{signal:se})]),nt=await Ne.json(),ve=await He.json(),Je=xe.ok?await xe.json():{},dt=ct.ok?await ct.json():{},rs=ve.ttlConfig?.bootstrapTtlMs??(Je?.tunnelBootstrapTtlMs===null?null:typeof Je?.tunnelBootstrapTtlMs=="number"?Je.tunnelBootstrapTtlMs:1800*1e3),is=typeof ve.ttlConfig?.sessionTtlMs=="number"?ve.ttlConfig.sessionTtlMs:typeof Je?.tunnelSessionTtlMs=="number"?Je.tunnelSessionTtlMs:480*60*1e3,os=At(ve.mode??Je?.tunnelMode),Ps="cloudflare",ja=typeof Je?.managedLocalTunnelConfigPath=="string"&&Je.managedLocalTunnelConfigPath.trim()||null,ka=ue(nt,Ps),Is=vu(ve?.managedRemoteTunnelPresets),Ht=typeof ve.managedRemoteTunnelHostname=="string"?ve.managedRemoteTunnelHostname:"",Es=Is.length>0?Is:Ht?[{id:`legacy-${Zs(Ht)}`,name:Ht,hostname:Zs(Ht)}]:[],ls=Es[0]?.id||"";if(I(rs),z(is),v(Ps),P(Array.isArray(dt?.providers)?dt.providers:[]),g(os),ge(ja),fe(Es),ne(ls),w(Array.isArray(ve.activeSessions)?ve.activeSessions:[]),d(ve.activeTunnelMode?At(ve.activeTunnelMode):ve.active&&ve.mode?At(ve.mode):null),q(new Set(Array.isArray(ve.managedRemoteTunnelTokenPresetIds)?ve.managedRemoteTunnelTokenPresetIds:[])),N(typeof ve.localPort=="number"?ve.localPort:null),ve.active&&ve.url){r({url:ve.url,connectUrl:null,bootstrapExpiresAt:typeof ve.bootstrapExpiresAt=="number"?ve.bootstrapExpiresAt:null}),a("active");return}a(ka?"idle":"not-available")}catch{se.aborted||(a("error"),u("Failed to check tunnel availability"))}},[ue,I,ge,fe,q,ne,z]);o.useEffect(()=>{const se=new AbortController;return Et(se.signal),()=>se.abort()},[Et]);const ba=o.useCallback(async()=>{if(u(null),p(null),A==="managed-local"&&te&&!hs(te)){u($e),$.error($e);return}a("starting");try{let se="",Ne="";if(A==="managed-remote"){if(!je){a("idle"),p("Select or add a managed remote tunnel first"),$.error("Select or add a managed remote tunnel first");return}se=je.hostname,Ne=(pe[je.id]||"").trim(),await K({tunnelMode:"managed-remote",managedRemoteTunnelPresets:ae})}const He=await Te("/api/pichamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,mode:A,...A==="managed-remote"&&je?{managedRemoteTunnelPresetId:je.id,managedRemoteTunnelPresetName:je.name}:{},...A==="managed-remote"&&se?{managedRemoteTunnelHostname:se}:{},...A==="managed-remote"&&Ne?{managedRemoteTunnelToken:Ne}:{},...A==="managed-local"&&te?{configPath:te}:{}})}),xe=await He.json();if(!He.ok||!xe.ok){if(A==="managed-remote"&&typeof xe.error=="string"&&xe.error.includes("Managed remote tunnel token is required")){a("idle"),p("Managed remote tunnel token is required before starting"),$.error("Add a managed remote tunnel token before starting");return}a("error"),u(xe.error||"Failed to start tunnel"),$.error(xe.error||"Failed to start tunnel");return}const ct=typeof xe.url=="string"?xe.url:"";if(!ct){a("error"),u("Tunnel started but no public URL was returned"),$.error("Tunnel started but no public URL was returned");return}if(r({url:ct,connectUrl:typeof xe.connectUrl=="string"?xe.connectUrl:null,bootstrapExpiresAt:typeof xe.bootstrapExpiresAt=="number"?xe.bootstrapExpiresAt:null}),d(xe.activeTunnelMode?At(xe.activeTunnelMode):xe.mode?At(xe.mode):A),w(Array.isArray(xe.activeSessions)?xe.activeSessions:[]),Array.isArray(xe.managedRemoteTunnelTokenPresetIds)&&q(new Set(xe.managedRemoteTunnelTokenPresetIds)),typeof xe.localPort=="number"&&N(xe.localPort),typeof xe.mode=="string"&&g(At(xe.mode)),a("active"),xe.replacedTunnel){const nt=typeof xe.revokedBootstrapCount=="number"?xe.revokedBootstrapCount:0,ve=typeof xe.invalidatedSessionCount=="number"?xe.invalidatedSessionCount:0;nt===1&&ve===1?$.warning("Replaced previous tunnel: revoked 1 link, invalidated 1 session."):nt===1?$.warning(`Replaced previous tunnel: revoked 1 link, invalidated ${ve} sessions.`):ve===1?$.warning(`Replaced previous tunnel: revoked ${nt} links, invalidated 1 session.`):$.warning(`Replaced previous tunnel: revoked ${nt} links, invalidated ${ve} sessions.`)}else $.success("Tunnel link ready")}catch{a("error"),u("Failed to start tunnel"),$.error("Failed to start tunnel")}},[$e,te,ae,K,je,pe,p,q,A,b]),ya=o.useCallback(async()=>{a("stopping");try{await Te("/api/pichamber/tunnel/stop",{method:"POST"});const se=await Te("/api/pichamber/tunnel/status");if(se.ok){const Ne=await se.json();w(Array.isArray(Ne.activeSessions)?Ne.activeSessions:[]),q(new Set(Array.isArray(Ne.managedRemoteTunnelTokenPresetIds)?Ne.managedRemoteTunnelTokenPresetIds:[])),N(typeof Ne.localPort=="number"?Ne.localPort:null)}r(null),d(null),a("idle"),$.success("Tunnel stopped")}catch{a("error"),u("Failed to stop tunnel"),$.error("Failed to stop tunnel")}},[q]),wa=o.useCallback(async()=>{if(n?.connectUrl)try{await navigator.clipboard.writeText(n.connectUrl),c(!0),$.success("Connect link copied"),setTimeout(()=>c(!1),2e3)}catch{$.error("Failed to copy URL")}},[n?.connectUrl]),Ts=o.useCallback(async se=>{p(null),u(null),s!=="active"&&s!=="stopping"&&s!=="starting"&&a("idle"),await K({tunnelMode:se,managedRemoteTunnelPresets:ae})},[ae,K,p,s]);return{timeFormatPreference:t,state:s,tunnelInfo:n,activeTunnelMode:l,qrDataUrl:It,errorMessage:i,managedRemoteValidationError:m,setManagedRemoteValidationError:p,copied:h,isSavingTtl:_,isSavingMode:f,tunnelProvider:b,dependencyInstallInfo:L,providerCapabilities:T,tunnelMode:A,managedLocalConfigPath:te,managedRemoteTunnelPresets:ae,expandedManagedRemoteTunnels:ce,setExpandedManagedRemoteTunnels:be,selectedPresetId:ie,sessionTokensByPresetId:pe,setSessionTokensByPresetId:oe,savedTokenPresetIds:G,isAddingPreset:Ce,setIsAddingPreset:re,newPresetName:me,setNewPresetName:J,newPresetHostname:B,setNewPresetHostname:U,newPresetToken:X,setNewPresetToken:he,bootstrapTtlMs:k,sessionTtlMs:S,remainingText:ua,sessionRecords:C,nowTs:ht,localPort:x,managedLocalConfigExtensionError:$e,managedLocalConfigFileInputRef:lt,isManagedLocalConfigPathInvalid:We,selectedPreset:je,renderedSessionRecords:pa,isConnectLinkLive:ma,isSelectedModeTunnelReady:ha,willReplaceActiveTunnel:fa,suggestedConnectorPort:Wt,selectedProviderCapability:ft,tunnelModeOptions:ga,displayedDependencyInstallInfo:xa,openExternal:va,handleBrowseManagedLocalConfig:Xe,handleManagedLocalConfigInputChange:mt,handleManagedLocalConfigInputBlur:Pt,handleManagedLocalConfigClear:ns,handleManagedLocalConfigFileSelected:Ss,handleStart:ba,handleStop:ya,handleCopyUrl:wa,handleBootstrapTtlChange:O,handleSessionTtlChange:V,handleModeChange:Ts,handleSelectPreset:et,handleSaveNewPreset:F,handleRemovePreset:Q,persistManagedRemoteTunnelToken:Se}}const Lu=()=>{const{timeFormatPreference:t,state:s,tunnelInfo:a,qrDataUrl:n,errorMessage:r,managedRemoteValidationError:l,setManagedRemoteValidationError:d,copied:i,isSavingTtl:u,isSavingMode:m,tunnelMode:p,managedLocalConfigPath:h,managedRemoteTunnelPresets:c,expandedManagedRemoteTunnels:f,setExpandedManagedRemoteTunnels:y,selectedPresetId:b,sessionTokensByPresetId:v,setSessionTokensByPresetId:L,savedTokenPresetIds:j,isAddingPreset:T,setIsAddingPreset:P,newPresetName:A,setNewPresetName:g,newPresetHostname:C,setNewPresetHostname:w,newPresetToken:x,setNewPresetToken:N,bootstrapTtlMs:k,sessionTtlMs:I,remainingText:S,managedLocalConfigExtensionError:z,managedLocalConfigFileInputRef:_,isManagedLocalConfigPathInvalid:O,selectedPreset:V,renderedSessionRecords:K,isConnectLinkLive:Z,isSelectedModeTunnelReady:ae,willReplaceActiveTunnel:fe,suggestedConnectorPort:ce,tunnelModeOptions:be,displayedDependencyInstallInfo:ie,openExternal:ne,handleBrowseManagedLocalConfig:pe,handleManagedLocalConfigInputChange:oe,handleManagedLocalConfigInputBlur:G,handleManagedLocalConfigClear:q,handleManagedLocalConfigFileSelected:Ce,handleStart:re,handleStop:me,handleCopyUrl:J,handleBootstrapTtlChange:B,handleSessionTtlChange:U,handleModeChange:X,handleSelectPreset:he,handleSaveNewPreset:je,handleRemovePreset:Se,persistManagedRemoteTunnelToken:et}=Mu(),F="gap-2 border-[var(--primary-base)] bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)] hover:text-[var(--primary-foreground)]";return s==="checking"?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-busy-pulse","aria-label":"Loading"})}):e.jsx(Y,{title:"External Tunnel",info:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{children:"Configure secure remote access with your own managed Cloudflare tunnel."}),e.jsx("p",{children:"Secure tunnel access is enforced server-side."}),e.jsx("p",{children:"Connect links are one-time and are revoked when tunnel stops or connect-link TTL expires."})]}),divider:!1,children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(wu,{records:K,timeFormatPreference:t}),s==="not-available"&&e.jsx(ju,{installInfo:ie}),e.jsxs("section",{className:"space-y-4 px-2 pb-2 pt-0",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{"data-settings-item":"tunnel.provider",className:"space-y-1.5",children:[e.jsx("p",{className:Ae,children:"Provider"}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-foreground",children:e.jsx(yu,{provider:"cloudflare"})})]}),e.jsxs("div",{"data-settings-item":"tunnel.type",className:"space-y-1.5",children:[e.jsx("p",{className:Ae,children:"Tunnel type"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1",children:be.map(Q=>e.jsxs(Sr,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(E,{variant:"chip",size:"xs","aria-pressed":p===Q.value,className:"!font-normal",onClick:()=>{X(Q.value)},disabled:m||s==="starting"||s==="stopping",children:Q.label})}),e.jsx(Yo,{sideOffset:8,className:"max-w-xs",children:Q.tooltip})]},Q.value))})]})]}),e.jsx(ku,{bootstrapTtlMs:k,sessionTtlMs:I,disabled:u||m||s==="starting"||s==="stopping",onBootstrapTtlChange:Q=>{B(Q)},onSessionTtlChange:Q=>{U(Q)}}),p==="managed-remote"&&e.jsx(Nu,{suggestedConnectorPort:ce,managedRemoteTunnelPresets:c,expandedManagedRemoteTunnels:f,sessionTokensByPresetId:v,savedTokenPresetIds:j,disabled:s==="starting"||s==="stopping"||m,isAddingPreset:T,newPresetName:A,newPresetHostname:C,newPresetToken:x,managedRemoteValidationError:l,selectedPreset:V,onToggleAddPreset:()=>P(Q=>!Q),onCancelAddPreset:()=>{P(!1),g(""),w(""),N("")},onNewPresetNameChange:g,onNewPresetHostnameChange:w,onNewPresetTokenChange:N,onSaveNewPreset:()=>{je()},onTogglePresetCollapse:(Q,de)=>{y(te=>({...te,[Q]:de})),de&&he(Q)},onRemovePreset:Q=>{Se(Q)},onPresetTokenChange:(Q,de)=>{d(null),L(te=>({...te,[Q]:de}))},onPersistToken:Q=>{et(Q)}}),p==="managed-local"&&e.jsx(Cu,{managedLocalConfigPath:h,isManagedLocalConfigPathInvalid:O,managedLocalConfigExtensionError:z,disabled:s==="starting"||s==="stopping"||m,fileInputRef:_,onInputChange:oe,onInputBlur:()=>{G()},onBrowse:()=>{pe()},onClear:()=>{q()},onFileSelected:Q=>{Ce(Q)}}),!ae&&e.jsx(Su,{tunnelMode:p,selectedPresetId:b,managedRemoteTunnelPresets:c,selectedPreset:V,willReplaceActiveTunnel:fe,state:s,isSavingMode:m,isManagedLocalConfigPathInvalid:O,primaryCtaClass:F,onSelectPreset:Q=>{he(Q)},onStart:re,onOpenDocUrl:Q=>{ne(Q)}})]}),ae&&a&&e.jsx(Tu,{tunnelInfo:a,isConnectLinkLive:Z,copied:i,onCopyUrl:J,remainingText:S,qrDataUrl:n,onNewConnectLink:re,onStop:me,stopping:s==="stopping",isSavingMode:m,isManagedLocalConfigPathInvalid:O,tunnelMode:p,primaryCtaClass:F}),s==="error"&&r&&e.jsxs("section",{className:"space-y-3 px-2 pb-2 pt-0",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:r}),e.jsx(E,{size:"sm",variant:"ghost",onClick:re,children:"Retry"})]})]})})},ki=()=>{const t=Le(),s=t&&Kt(),a=s&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[n,r]=D.useState(!0),[l,d]=D.useState(!1),[i,u]=D.useState(!1),[m,p]=D.useState(!1),[h,c]=D.useState(!1),[f,y]=D.useState(!1),[b,v]=D.useState(!1),[L,j]=D.useState(!1),[T,P]=D.useState(!1),[A,g]=D.useState(!0),[C,w]=D.useState(!1),[x,N]=D.useState(!0),[k,I]=D.useState(!0),[S,z]=D.useState(!1),[_,O]=D.useState(!1),[V,K]=D.useState(!1),[Z,ae]=D.useState(null);D.useEffect(()=>{if(!s){r(!1);return}let G=!1;return(async()=>{try{const q=await Te("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!q.ok)throw new Error("Failed to load desktop settings");const Ce=await q.json().catch(()=>null);if(G)return;const re=Ce?.desktopMacMenuBarEnabled!==!1;N(re),I(re),ae(null)}catch(q){G||ae(q instanceof Error?q.message:"Failed to load desktop settings")}finally{G||r(!1)}})(),()=>{G=!0}},[s]),D.useEffect(()=>{if(!t){u(!1);return}let G=!1;return(async()=>{const q=await po();G||(u(q?.supported===!0),p(q?.enabled===!0))})(),()=>{G=!0}},[t]),D.useEffect(()=>{if(!t){y(!1);return}let G=!1;return(async()=>{const q=await mo();G||(y(q?.supported===!0),v(q?.enabled===!0))})(),()=>{G=!0}},[t]),D.useEffect(()=>{if(!t){P(!1);return}let G=!1;return(async()=>{const q=await ho();G||(P(q?.supported===!0),g(q?.enabled===!0))})(),()=>{G=!0}},[t]),D.useEffect(()=>{if(!t){z(!1);return}let G=!1;return(async()=>{const q=await fo();G||(z(q?.supported===!0),O(q?.enabled===!0))})(),()=>{G=!0}},[t]);const fe=k!==x,ce=n||l||!fe,be=D.useCallback(async()=>{if(!i||h)return;const G=!m;p(G),c(!0),ae(null);try{const q=await go(G);if(!q?.supported)throw new Error("Launch at login is not supported on this system");p(q.enabled)}catch(q){p(!G),ae(q instanceof Error?q.message:"Failed to update launch at login setting")}finally{c(!1)}},[h,m,i]),ie=D.useCallback(async()=>{if(!f||L)return;const G=!b;v(G),j(!0),ae(null);try{const q=await xo(G);if(!q)throw new Error("Failed to update system tray setting");if(!q.supported)throw new Error("System tray background mode is not supported on this system");v(q.enabled)}catch(q){v(!G),ae(q instanceof Error?q.message:"Failed to update system tray setting")}finally{j(!1)}},[L,b,f]),ne=D.useCallback(async()=>{if(!T||C)return;const G=!A;g(G),w(!0),ae(null);try{const q=await vo(G);if(!q)throw new Error("Failed to update close behavior");if(!q.supported)throw new Error("Closing to the system tray is not supported on this system");g(q.enabled)}catch(q){g(!G),ae(q instanceof Error?q.message:"Failed to update close behavior")}finally{w(!1)}},[A,T,C]),pe=D.useCallback(async()=>{if(!S||V)return;const G=!_;O(G),K(!0),ae(null);try{const q=await bo(G);if(!q?.supported)throw new Error("Preventing sleep is not supported on this system");O(q.enabled)}catch(q){O(!G),ae(q instanceof Error?q.message:"Failed to update keep awake setting")}finally{K(!1)}},[V,_,S]),oe=D.useCallback(async()=>{if(fe){d(!0),ae(null);try{if(!(await Te("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopMacMenuBarEnabled:k})})).ok)throw new Error("Failed to save desktop settings");if(N(k),!await hr())throw new Error("Saved, but failed to restart app")}catch(G){ae(G instanceof Error?G.message:"Failed to save desktop settings"),d(!1)}}},[k,fe]);return t?e.jsx(Y,{title:"Desktop",children:e.jsxs("div",{className:"space-y-3",children:[i||a||f||T||S?e.jsxs("div",{className:pt,children:[i?e.jsx(ke,{settingsItem:"sessions.desktop-launch-at-login",checked:m,onChange:G=>{G!==m&&be()},disabled:h,label:"Start PiChamber when you log in",info:"Starts the app in the background without opening a window. Use the desktop status icon to open it.",ariaLabel:"Start PiChamber at login"}):null,a?e.jsx(ke,{settingsItem:"sessions.desktop-mac-menu-bar",checked:k,onChange:I,disabled:n||l,label:"Show PiChamber in the menu bar",info:"Requires an app restart. When off, PiChamber does not create the menu bar item or run its session, approval, and usage updates.",ariaLabel:"Show PiChamber in the macOS menu bar"}):null,f?e.jsx(ke,{settingsItem:"sessions.desktop-minimize-to-tray",checked:b,onChange:G=>{G!==b&&ie()},disabled:L,label:"Minimize to the system tray",info:"Hides PiChamber in the system tray instead of leaving it in the taskbar when you minimize the window.",ariaLabel:"Minimize PiChamber to the system tray"}):null,T?e.jsx(ke,{settingsItem:"sessions.desktop-close-to-tray",checked:A,onChange:G=>{G!==A&&ne()},disabled:C,label:"Close to the system tray",info:"Keeps PiChamber running in the system tray when you close the main window. Turn this off to quit the app when the window closes.",ariaLabel:"Close PiChamber to the system tray"}):null,S?e.jsx(ke,{settingsItem:"sessions.desktop-keep-awake",checked:_,onChange:G=>{G!==_&&pe()},disabled:V,label:"Keep computer awake while PiChamber is running",info:"Prevents system sleep so phones can keep reaching this app. The screen can still turn off.",ariaLabel:"Keep computer awake while PiChamber is running"}):null]}):null,Z?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:Z}):null,s?e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(E,{type:"button",size:"xs",onClick:oe,disabled:ce,className:"shrink-0 !font-normal",children:l?"Saving...":"Save + Restart"})}):null]})}):null},Ni=new Set(["shift","control","alt","meta"]),Ru=t=>{if(Ni.has(t.key.toLowerCase()))return null;const s=[];(t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt");const a=Xa(t.key);return a?(s.push(a),rt(s.join("+"))):null},Du=t=>{const s=[];if((t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt"),Ni.has(t.key.toLowerCase()))return s.length>0?rt(s.join("+")):null;const a=Xa(t.key);return a?(s.push(a),s.length>0?rt(s.join("+")):null):null},_u={add_selection_to_chat:"Add selection to chat",cycle_agent:"Cycle agent",cycle_draft_folder:"Cycle draft folder",cycle_favorite_model_backward:"Cycle favorite model backward",cycle_favorite_model_forward:"Cycle favorite model forward",cycle_session_folder:"Cycle session folder",cycle_theme:"Cycle theme",focus_input:"Focus input",new_chat:"New session",new_mini_chat:"New Mini Chat window",open_command_palette:"Open command palette",open_help:"Open keyboard shortcuts",open_model_selector:"Open model selector",open_right_sidebar:"Open right sidebar",open_settings:"Open settings",open_timeline_dialog:"Open conversation timeline",switch_context_surface:"Switch context panel surface",toggle_services_menu:"Toggle services menu",toggle_sidebar:"Toggle sidebar",toggle_terminal:"Toggle terminal dock"},zu=()=>{const t=W(A=>A.shortcutOverrides),s=W(A=>A.setShortcutOverride),a=W(A=>A.clearShortcutOverride),n=W(A=>A.resetAllShortcutOverrides),r=o.useMemo(()=>yo(),[]),l=o.useCallback((A,g)=>_u[A]??g,[]),[d,i]=o.useState(null),[u,m]=o.useState({}),[p,h]=o.useState(""),[c,f]=o.useState(""),[y,b]=o.useState(null),v=o.useCallback(A=>{Ke({shortcutOverrides:A})},[]),L=o.useCallback((A,g)=>{const C=rt(g);for(const w of r){if(w.id===A)continue;const x=Cn(w.id,t);if(rt(x)===C)return w.id}return null},[r,t]),j=o.useCallback((A,g)=>{const C=rt(g),w=L(A,C);if(w){b({actionId:A,combo:C,conflictActionId:w}),h("");return}const x={...t,[A]:C};s(A,C),v(x),b(null),h(""),f(Sn(C)?"This shortcut can conflict with browser defaults. It is still saved.":""),m(N=>{const k={...N};return delete k[A],k})},[L,v,s,t]),T=o.useCallback(()=>{if(!y)return;const A={...t,[y.conflictActionId]:Ca,[y.actionId]:y.combo};s(y.conflictActionId,Ca),s(y.actionId,y.combo),v(A),b(null),h(""),f(Sn(y.combo)?"This shortcut can conflict with browser defaults. It is still saved.":""),m(g=>{const C={...g};return delete C[y.actionId],C})},[y,v,s,t]),P=o.useCallback(A=>{const g={...t};delete g[A],a(A),v(g),m(C=>{const w={...C};return delete w[A],w}),b(null),h(""),f("")},[a,v,t]);return e.jsxs(Y,{settingsItem:"shortcuts.keyboard-shortcuts",title:"Keyboard Shortcuts",divider:!1,info:"Capture a new key combo, save it, and bindings will update immediately.",headerAction:e.jsx(E,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{n(),v({}),m({}),b(null),h(""),f("")},children:"Reset All"}),children:[(p||c||y)&&e.jsxs("div",{className:"mb-2 space-y-2",children:[y&&e.jsxs("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 flex flex-col @xl:flex-row @xl:items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-foreground",children:"This combo is already used by another shortcut. Overwrite and clear that other mapping?"}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx(E,{type:"button",size:"xs",className:"!font-normal",onClick:T,children:"Overwrite"}),e.jsx(E,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>b(null),children:"Cancel"})]})]}),p&&e.jsx("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3 typography-meta text-foreground",children:p}),c&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 typography-meta text-foreground",children:c})]}),e.jsx("div",{children:r.map((A,g)=>{const C=A.id==="switch_context_surface",w=C?wo(A.id,t):Cn(A.id,t),x=u[A.id],N=x??w,k=typeof x=="string"&&rt(x)!==rt(w),I=N===""||rt(N)===Ca,S=d===A.id?"Press keys...":C&&!I?`${Tn(N)} + 1…0`:Tn(N);return e.jsx("div",{className:H("py-1.5",g>0&&"border-t border-border/40"),children:e.jsxs(Pe,{label:l(A.id,A.label),alignEnd:!1,children:[e.jsx(ee,{readOnly:!0,value:S,onFocus:()=>{i(A.id),h("")},onBlur:()=>{d===A.id&&i(null)},onKeyDown:z=>{if(z.preventDefault(),z.stopPropagation(),z.key==="Escape"){i(null);return}const _=C?Du(z):Ru(z);_&&(m(O=>({...O,[A.id]:_})),i(null),b(null),h(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),e.jsx(E,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const z=u[A.id];if(!z){h("Capture a shortcut first.");return}j(A.id,z)},disabled:!k,children:"Save Changes"}),e.jsx(E,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>P(A.id),children:"Reset"})]})},A.id)})})]})},Ou=new Set(["shift","control","alt","meta"]),Uu=t=>{if(Ou.has(t.key.toLowerCase()))return null;const s=[];(t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt");const a=Xa(t.key);if(!a)return null;s.push(a);const n=rt(s.join("+"));return s.length>1?n:null},Fu=({trigger:t,index:s,onChange:a,onRemove:n})=>{const r="h-9 w-full bg-transparent text-sm";return e.jsxs("div",{className:"flex flex-col gap-2 @xl:flex-row @xl:items-center",children:[e.jsx(ee,{value:t.label,placeholder:"Label","aria-label":`Trigger ${s+1} label`,onChange:l=>a({...t,label:l.target.value}),className:H(r,"@xl:w-36")}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/"}),e.jsx(ee,{value:t.command,placeholder:"command","aria-label":`Trigger ${s+1} command`,onChange:l=>a({...t,command:l.target.value}),className:H(r,"w-40")})]}),e.jsx(ee,{value:t.args??"",placeholder:"Arguments (optional)","aria-label":`Trigger ${s+1} arguments`,onChange:l=>a({...t,args:l.target.value}),className:H(r,"flex-1")}),e.jsx("input",{value:t.combo?t.combo.replace(/\+/g,"+"):"",placeholder:"Keybinding","aria-label":`Trigger ${s+1} keybinding`,readOnly:!0,onKeyDown:l=>{const d=Uu(l);d&&(l.preventDefault(),a({...t,combo:d}))},className:H(r,"w-32 rounded-md border")}),e.jsx(E,{variant:"ghost",size:"icon",onClick:n,"aria-label":`Remove trigger ${t.label}`,children:e.jsx(R,{name:"close",className:"size-4"})})]})},Bu=()=>{const t=W(l=>l.commandTriggers),s=o.useCallback(async l=>{W.setState({commandTriggers:l});try{await Ke({commandTriggers:l})}catch{it("error")}},[]),a=(l,d)=>{const i=t.map((u,m)=>m===l?d:u);s(jo(i)??[])},n=l=>{const d=t.filter((i,u)=>u!==l);s(d)},r=()=>{t.length>=Pn||s([...t,{id:`trigger-${Date.now().toString(36)}`,label:"",command:""}])};return e.jsxs(Y,{title:"Command triggers",divider:!1,settingsItem:"shortcuts.command-triggers",children:[e.jsx(Pe,{label:"Quick actions",info:"Buttons above the composer and optional keybindings that run a slash command in the current session. Keybindings must include a modifier and never shadow built-in shortcuts.",children:e.jsx(E,{size:"sm",variant:"outline",onClick:r,disabled:t.length>=Pn,children:"Add trigger"})}),t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 pb-1",children:t.map((l,d)=>e.jsx(Fu,{trigger:l,index:d,onChange:i=>a(d,i),onRemove:()=>n(d)},l.id))}),t.length===0&&e.jsx("p",{className:"pb-2 text-sm text-muted-foreground",children:"No command triggers yet. Add one to pin a slash command as a button."})]})},$u=({section:t})=>{const{isMobile:s}=Ze(),a=s&&Rt(),n=Le();if(!t)return e.jsxs(we,{className:"pichamber-page-body space-y-3 sm:space-y-6",children:[e.jsx(ca,{}),e.jsx(yi,{}),n&&e.jsx(ki,{}),e.jsx(bi,{}),a&&e.jsx(ni,{})]});const r=()=>{switch(t){case"general":return e.jsx(Vu,{});case"visual":return e.jsx(Wu,{});case"chat":return e.jsx(Hu,{});case"sessions":return e.jsx(Gu,{});case"shortcuts":return e.jsx(Ku,{});case"git":return e.jsx(qu,{});case"github":return e.jsx(Qu,{});case"notifications":return e.jsx(Ju,{});case"tunnel":return e.jsx(Yu,{});default:return null}},l={general:"General",visual:"Appearance",chat:"Chat",sessions:"Sessions",shortcuts:"Shortcuts",git:"Git",github:"Git",notifications:"Notifications",tunnel:"External Tunnel"}[t],d={general:"App startup, security, connection, privacy, and diagnostics.",visual:"Customize how PiChamber looks and feels.",chat:"Configure how messages and tools are displayed.",sessions:"Set defaults and retention for sessions.",shortcuts:"Customize keyboard shortcuts.",git:void 0,github:void 0,notifications:"Choose when and how you get notified.",tunnel:"Expose this instance over a remote tunnel."}[t];return e.jsx(we,{title:s?void 0:l,description:s?void 0:d,className:"pichamber-page-body",children:r()})},Ku=()=>e.jsxs(e.Fragment,{children:[e.jsx(zu,{}),e.jsx(Bu,{})]}),Vu=()=>{const t=Le();return e.jsxs(e.Fragment,{children:[t&&e.jsx(ki,{}),e.jsx(ca,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar","terminalQuickKeys","terminalShell","terminalLoginShell","perfHud"]}),e.jsx(tu,{})]})},Wu=()=>e.jsx(ca,{visibleSettings:["theme","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat","weekStart","sidebarViewMode","fontSize","terminalFontSize","editorFontSize","wrapLinesByDefault","spacing","inputBarOffset"]}),Hu=()=>e.jsx(ca,{visibleSettings:["diffLayout","followUpBehavior"]}),Gu=()=>e.jsxs(e.Fragment,{children:[e.jsx(yi,{}),e.jsx(bi,{})]}),qu=()=>e.jsx(xn,{}),Qu=()=>e.jsx(xn,{}),Ju=()=>e.jsx(cu,{}),Yu=()=>e.jsx(Lu,{}),ps="openai-compatible",Xu=t=>`${Math.round(t/1024/1024)} MB`;function Zu(){const[t,s]=o.useState(null),[a,n]=o.useState(null),[r,l]=o.useState(""),[d,i]=o.useState(""),[u,m]=o.useState(""),[p,h]=o.useState(null),[c,f]=o.useState(!1),y=o.useCallback(async T=>{const P=await Xo(T);s(P),s(P),n(null);const A=P.config.providers.find(g=>g.id===ps);A&&(l(A.baseUrl),i(A.model))},[]);o.useEffect(()=>{y().catch(T=>n(T.message))},[y]),o.useEffect(()=>{if(!t?.models.some(P=>P.downloading))return;const T=window.setInterval(()=>{y({fresh:!0}).catch(()=>{})},1500);return()=>window.clearInterval(T)},[y,t?.models]);const b=o.useCallback(async T=>{it("saving");try{const P=await Te("/api/stt/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!P.ok)throw new Error((await P.json().catch(()=>null))?.error||"Could not save dictation settings");const A=await P.json();s(g=>g&&{...g,config:A.config}),it("saved")}catch(P){throw it("error"),P}},[]),v=async(T,P)=>{h(T);try{const A=P==="POST"?"/download":"",g=await Te(`/api/stt/models/${encodeURIComponent(T)}${A}`,{method:P});if(!g.ok)throw new Error((await g.json().catch(()=>null))?.error||"Model action failed");await y({fresh:!0})}catch(A){n(A instanceof Error?A.message:String(A))}finally{h(null)}},L=async()=>{f(!0);try{await b({remoteProvider:{id:ps,label:"OpenAI-compatible",baseUrl:r,model:d,apiKey:u||void 0},providerConfigId:ps}),m("")}catch(T){n(T instanceof Error?T.message:String(T))}finally{f(!1)}};if(!t)return e.jsx(we,{title:"Dictation",children:e.jsx("div",{className:"py-8 typography-ui text-muted-foreground",children:a||"Loading dictation settings..."})});const j=t.config.providers.find(T=>T.id===ps);return e.jsxs(we,{title:"Dictation",description:"Record speech and insert the final transcript into the composer.",children:[e.jsxs(Y,{title:"Recording",divider:!1,settingsItem:"dictation.enabled",contentClassName:"space-y-4",children:[e.jsx(ke,{checked:t.config.enabled,onChange:T=>{b({enabled:T}).catch(P=>n(P.message))},label:"Enable dictation",ariaLabel:"Enable dictation",info:"Audio streams to the active PiChamber server. PiChamber inserts text only after you choose Done and never sends it automatically."}),e.jsx(Pe,{label:"Transcription provider",settingsItem:"dictation.provider",children:e.jsxs(_e,{value:t.config.providerConfigId,onValueChange:T=>{b({providerConfigId:T}).catch(P=>n(P.message))},children:[e.jsx(ze,{size:Be,className:ra,"aria-label":"Transcription provider",children:e.jsx(Oe,{})}),e.jsxs(Ue,{children:[e.jsx(ye,{value:"local",children:"Local model"}),e.jsx(ye,{value:ps,disabled:!j,children:"OpenAI-compatible"})]})]})}),e.jsx(Pe,{label:"Language",info:"Optional language code such as en or fr. Leave blank for automatic detection.",settingsItem:"dictation.language",children:e.jsx(ee,{value:t.config.language,onChange:T=>s(P=>P&&{...P,config:{...P.config,language:T.target.value}}),onBlur:()=>{b({language:t.config.language}).catch(T=>n(T.message))},placeholder:"Auto-detect",className:"h-8 w-full max-w-48","aria-label":"Dictation language"})})]}),e.jsx(Y,{title:"Local models",info:"Models run only on the active PiChamber server. Downloads use pinned checksums and install atomically.",settingsItem:"dictation.models",contentClassName:"space-y-1",children:t.models.map(T=>e.jsxs("div",{className:"flex min-h-10 items-center gap-3 py-1.5",children:[e.jsx(ol,{checked:t.config.localModelId===T.id,onChange:()=>{b({localModelId:T.id,providerConfigId:"local"}).catch(P=>n(P.message))},ariaLabel:`Use ${T.description}`}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{b({localModelId:T.id,providerConfigId:"local"}).catch(P=>n(P.message))},children:[e.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:T.description}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Xu(T.sizeBytes)})]}),T.downloading?e.jsx("span",{className:"typography-meta tabular-nums text-muted-foreground",children:T.downloadProgress===null?"Downloading...":`Downloading ${T.downloadProgress}%`}):T.installed?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"check",className:"size-4 text-[var(--status-success)]","aria-label":"Installed"}),e.jsx(E,{className:Qe,variant:"ghost",size:"icon",disabled:p===T.id,onClick:()=>{v(T.id,"DELETE")},title:"Delete model","aria-label":`Delete ${T.description}`,children:e.jsx(R,{name:"delete-bin",className:"size-4"})})]}):e.jsx(E,{variant:"outline",size:"sm",disabled:p===T.id,onClick:()=>{v(T.id,"POST")},children:T.corrupt||T.downloadError?"Retry":"Download"})]},T.id))}),e.jsxs(Y,{title:"OpenAI-compatible provider",info:"The server stores this configuration. Dictation sockets receive only its ID, never the URL or API key.",settingsItem:"dictation.remote",contentClassName:"space-y-4",children:[e.jsx(Ie,{label:"Server URL",children:e.jsx(ee,{value:r,onChange:T=>l(T.target.value),placeholder:"https://api.openai.com/v1",className:"h-8"})}),e.jsx(Ie,{label:"Model",children:e.jsx(ee,{value:d,onChange:T=>i(T.target.value),placeholder:"whisper-1",className:"h-8"})}),e.jsx(Ie,{label:"API key",info:j?.apiKeyConfigured?"A key is already stored. Leave this blank to keep it.":"Optional for servers that do not require authentication.",children:e.jsx(ee,{type:"password",value:u,onChange:T=>m(T.target.value),placeholder:j?.apiKeyConfigured?"Stored key":"Optional",className:"h-8",autoComplete:"off"})}),e.jsx("div",{className:es,children:e.jsx(E,{onClick:()=>{L()},disabled:c||!r.trim()||!d.trim(),children:c?"Saving...":"Save Provider"})})]}),a?e.jsx("p",{role:"alert",className:"pb-6 typography-meta text-[var(--status-error)]",children:a}):null]})}const rr=256,ir=280,ep=["general","appearance","chat","dictation","notifications","sessions","shortcuts","about","projects","remote-access","servers","tunnel","git","providers","behavior","snippets","prompt-templates","skills.installed"];function Ci(t,s){return t.isAvailable?.(s)??!0}function tp(t,s,a=!1){return{isWeb:!t&&Rt(),isDesktop:t,isMobile:s,isCapacitor:a}}function or(t,s){const a=new Set(s);let n=t,r=1;for(;a.has(n);)n=`${t}-${r}`,r+=1;return n}function sp(){return e.jsx("div",{className:"flex h-full items-center justify-center px-6",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:ll,children:"Not available"}),e.jsx("p",{className:"typography-ui text-muted-foreground mt-1",children:"This settings page is not available in this runtime."})]})})}function zs({slug:t,isMobile:s,runtimeCtx:a,openChamberSectionBySlug:n,onActiveConnectionDeleted:r}){const l=gs(t);if(l&&!Ci(l,a))return e.jsx(sp,{});switch(t){case"projects":return e.jsx(dc,{});case"remote-access":return e.jsx(Yn,{});case"servers":return e.jsx(td,{onActiveConnectionDeleted:r});case"remote-instances":return e.jsx(Yn,{});case"behavior":return e.jsx(rc,{});case"skills.installed":return e.jsx(lc,{});case"providers":return e.jsx(Pd,{});case"about":return e.jsx(we,{title:s?void 0:"About",children:e.jsx(ni,{})});case"snippets":return e.jsx(Ad,{});case"prompt-templates":return e.jsx(_d,{});case"dictation":return e.jsx(Zu,{});case"git":return e.jsx(we,{title:s?void 0:"Git",children:e.jsx(xn,{})});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"tunnel":{const d=n[t]??"visual";return e.jsx($u,{section:d})}default:return null}}const ap=["general","projects","agent"];function np({isMobile:t,isMobileSettingsSearchOpen:s,settingsSearchQuery:a,setSettingsSearchQuery:n,handleSettingsSearchKeyDown:r,settingsSearchResults:l,groupedSettingsSearchResults:d,activeSearchResultIndex:i,setActiveSearchResultIndex:u,searchResultRefs:m,keyboardSearchNavigationRef:p,openSearchResult:h,sortedFilteredPages:c,settingsSlug:f,mobileStage:y,openPage:b,getPageTitle:v,activeRemoteLabel:L,mobileAppActions:j}){const T=a.trim().length>0,P=t?s&&T:T;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[t?P?null:e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>{if(j?.openInstances){j.openInstances();return}b("servers")},className:H("flex w-full items-center justify-between gap-3 rounded-xl border px-4 py-3.5 text-left shadow-sm hover:bg-interactive-hover/50 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",L?"border-[var(--status-success)]/30 bg-[var(--status-success)]/10":"border-border bg-card"),children:[e.jsx("div",{className:"min-w-0 flex-1",children:L?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground truncate",children:L}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-[var(--status-success)] animate-pulse","aria-hidden":!0}),e.jsx("span",{className:"text-[var(--status-success)]",children:"Connected"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground truncate",children:"Not connected"}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"text-muted-foreground",children:"Select a server"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]})}),e.jsx(R,{name:"arrow-right-s",className:"size-4 shrink-0 text-muted-foreground"})]})}):e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("div",{className:"flex h-10 items-center gap-1.5 rounded-md border border-border bg-transparent px-2 text-muted-foreground focus-within:ring-2 focus-within:ring-primary/40 sm:h-8",children:[e.jsx(R,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{value:a,onChange:A=>n(A.target.value),onKeyDown:r,placeholder:"Search settings","aria-label":"Search settings",className:"typography-ui-label min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground/70"}),T&&e.jsx("button",{type:"button",onClick:()=>n(""),"aria-label":"Clear settings search",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground sm:h-5 sm:w-5",children:e.jsx(R,{name:"close",className:"h-3.5 w-3.5"})})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden",children:e.jsx("div",{className:"flex flex-col gap-0.5 px-3 pt-3 pb-2",children:P?l.length>0?(()=>{let A=0;return d.map(g=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"px-2 pb-0.5 pt-2 typography-micro font-medium text-muted-foreground/70",children:g.pageTitle}),g.results.map(C=>{const w=A;A+=1;const x=w===i,N=!!C.description;return e.jsxs("button",{type:"button",ref:k=>{m.current[w]=k},onMouseMove:()=>{p.current=!1,u(w)},onClick:()=>h(C),className:H("flex w-full flex-col rounded-md px-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",N?"min-h-11 py-1.5":"py-2",x?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:C.title}),N&&e.jsx("span",{className:"typography-micro text-muted-foreground/70 line-clamp-2",children:C.description})]},C.id)})]},g.page))})():e.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:"No matching settings"}):(()=>{const A=new Map;for(const C of c){const w=C.group,x=A.get(w);x?x.push(C):A.set(w,[C])}return ap.map(C=>({group:C,pages:A.get(C)??[]})).filter(C=>C.pages.length>0).map(({group:C,pages:w},x)=>{const N=C==="projects"?"Workspace":C==="agent"?"Agent":null;return e.jsxs("div",{className:"space-y-0.5",children:[N?e.jsx("div",{className:H("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",x===0?"pt-1":"pt-4 sm:pt-3"),children:N}):null,w.map(k=>{const I=f===k.slug&&!(t&&y==="nav"),S=cl(k.slug);return S?e.jsx(Sr,{children:e.jsx(Tr,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>b(k.slug),"aria-current":I?"page":void 0,className:H("flex h-11 w-full items-center gap-2.5 rounded-md px-3 overflow-hidden sm:h-8 sm:gap-2 sm:px-2",I?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[e.jsx(R,{name:S,className:"h-[18px] w-[18px] shrink-0 sm:h-4 sm:w-4"}),e.jsxs("span",{className:"flex items-center gap-1.5 whitespace-nowrap overflow-hidden transition-opacity duration-150 opacity-100",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate",children:v(k.slug)}),k.slug==="tunnel"&&e.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]})]})})},k.slug):null})]},C)})})()})})]})}function rp(t){const[s,a]=o.useState(null);return o.useEffect(()=>{const n=async()=>{try{const{loadMobileConnections:d,isActiveRuntimeConnection:i}=await Ot(async()=>{const{loadMobileConnections:p,isActiveRuntimeConnection:h}=await Promise.resolve().then(()=>Hl);return{loadMobileConnections:p,isActiveRuntimeConnection:h}},void 0),m=(await d().catch(()=>[])).find(p=>i(p));if(m){a(m.label);return}}catch{}if(t){a(t);return}try{const{desktopHostsGet:d}=await Ot(async()=>{const{desktopHostsGet:y}=await import("./index-C2ISrmRR.js").then(b=>b.cJ);return{desktopHostsGet:y}},__vite__mapDeps([4,5,1,6,2,7,8,9])),{buildLocalDesktopHost:i,getLocalDesktopOrigin:u,resolveCurrentDesktopHost:m}=await Ot(async()=>{const{buildLocalDesktopHost:y,getLocalDesktopOrigin:b,resolveCurrentDesktopHost:v}=await import("./index-C2ISrmRR.js").then(L=>L.cK);return{buildLocalDesktopHost:y,getLocalDesktopOrigin:b,resolveCurrentDesktopHost:v}},__vite__mapDeps([4,5,1,6,2,7,8,9])),p=await d().catch(()=>({hosts:[]})),c=[i(u()),...p.hosts],f=m(c);if(f&&f.label&&f.label!=="Instance"){a(f.label);return}}catch{}const r=ot(),l=Ve();if(l==="local"){a("Local");return}if(l.startsWith("relay:")){const d=l.split(":")[1]?.split("@")[0];a(d?`Relay ${d.slice(0,8)}`:"Private relay");return}if(l.startsWith("host:")){a(l.replace("host:",""));return}if(r)try{const d=new URL(r);a(d.host);return}catch{a(r);return}a(null)};return n(),ea(()=>{n()})},[t]),s}const ip=[{id:"appearance.time-format",page:"appearance",title:"Time Format",keywords:["clock","12h","24h"]},{id:"appearance.week-start",page:"appearance",title:"Week Starts On",keywords:["calendar","monday","sunday"]},{id:"appearance.sidebar-view",page:"appearance",title:"Sidebar view",keywords:["sidebar","sessions","folders","workspace","timeline","layout","group"]},{id:"appearance.light-theme",page:"appearance",title:"Light Theme",keywords:["theme","color","light mode"]},{id:"appearance.dark-theme",page:"appearance",title:"Dark Theme",keywords:["theme","color","dark mode"]},{id:"appearance.dock-badge",page:"appearance",title:"Dock badge",description:"Show a count of chats with unseen activity on the macOS dock icon.",keywords:["dock","badge","unread","unseen","counter","count","notification","macos"],isAvailable:t=>t.isMac},{id:"appearance.pwa-install-name",page:"appearance",title:"Install App Name",description:"Used by PWA installation process.",keywords:["pwa","installed app"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.pwa-orientation",page:"appearance",title:"Install Orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",keywords:["pwa","portrait","landscape"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.mobile-keyboard-mode",page:"appearance",title:"Mobile Keyboard Behavior",description:"Default browser behavior is safest. Resize content asks supported browsers to shrink the app when the on-screen keyboard opens.",keywords:["mobile","keyboard","resize"],isAvailable:t=>t.isMobile&&t.isWeb&&!t.isDesktop},{id:"appearance.interface-font-size",page:"appearance",title:"Interface Font Size",keywords:["font","text size","ui scale"]},{id:"appearance.terminal-font-size",page:"appearance",title:"Terminal Font Size",keywords:["terminal","font","text size"]},{id:"appearance.terminal-shell",page:"general",title:"Terminal Shell",description:"Restart the terminal to apply this change to the current session.",keywords:["terminal","shell","bash","zsh","fish","pwsh","powershell"]},{id:"appearance.editor-font-size",page:"appearance",title:"Editor Font Size",keywords:["editor","font","text size","code"]},{id:"appearance.spacing-density",page:"appearance",title:"Spacing Density",keywords:["density","compact","comfortable","spacing"]},{id:"appearance.input-bar-offset",page:"appearance",title:"Input Bar Offset",description:"Raise input bar to avoid OS-level screen obstructions like home bars.",keywords:["input","home bar","offset"],isAvailable:t=>t.isMobile},{id:"appearance.auto-save-enabled",page:"general",title:"Auto-save files",description:"Automatically save file edits after you stop typing. Disable to require manual save.",keywords:["editor","autosave","auto-save","files","save"]},{id:"appearance.expanded-editor-toolbar",page:"general",title:"Always show editor toolbar (docked under the file tabs)",keywords:["editor","toolbar","tabs","docked","files"]},{id:"appearance.wrap-lines-by-default",page:"appearance",title:"Wrap long lines by default",description:"Applies to the file viewer and diffs. The wrap toggle in each view overrides it until reload.",keywords:["word wrap","wrap","line wrap","soft wrap","wrap lines","diff","editor"]},{id:"appearance.file-editor-keymap",page:"general",title:"File editor keymap",keywords:["editor","vim","keymap"]},{id:"appearance.terminal-quick-keys",page:"general",title:"Terminal Quick Keys",description:"Show Esc, Ctrl, Arrows in terminal view",keywords:["terminal","keyboard","esc","ctrl","arrows"]},{id:"dictation.enabled",page:"dictation",title:"Enable dictation",description:"Record speech and insert the final transcript at the composer caret.",keywords:["voice","speech","microphone","stt"]},{id:"dictation.provider",page:"dictation",title:"Transcription provider",keywords:["local","remote","openai","whisper","parakeet"]},{id:"dictation.language",page:"dictation",title:"Dictation language",keywords:["language","locale","auto-detect"]},{id:"dictation.models",page:"dictation",title:"Local speech models",keywords:["download","delete","whisper","parakeet"]},{id:"dictation.remote",page:"dictation",title:"OpenAI-compatible transcription",keywords:["api key","server url","audio transcriptions"]},{id:"about.desktop-update-channel",page:"about",title:"Desktop app update channel",description:"Choose stable desktop releases only, or check stable releases before desktop release candidates. Switching channels does not downgrade the installed app.",keywords:["updates","release candidate","rc","electron","prerelease"],isAvailable:t=>t.isDesktop},{id:"about.server-update-channel",page:"about",title:"Server update channel",description:"Choose stable server releases only, or check stable releases before server release candidates. Switching channels does not downgrade the installed server.",keywords:["updates","release candidate","rc","server","remote","prerelease"],isAvailable:t=>t.isDesktop&&!t.isDesktopLocalOrigin},{id:"general.chat-link-target",page:"general",title:"Open chat links in",description:"Open web links clicked in chat in the PiChamber browser or the system browser.",keywords:["browser","links","url","web","open","external","system browser"]},{id:"general.browser-data",page:"general",title:"Clear browsing data",description:"Sign out of every site in the server browser by deleting its cookies and site data.",keywords:["browser","cookies","logins","sign in","saved","clear","cache","web"]},{id:"general.performance-overlay",page:"general",title:"Performance overlay",description:"Show a live frame-time overlay for debugging jank. Adds overhead and stays on this device only.",keywords:["fps","performance","hud","diagnostics","debug","jank","frame"]},{id:"general.process-performance-recording",page:"general",title:"Record Electron process performance",description:"Record Electron process CPU and memory samples to a local diagnostics file.",keywords:["performance","diagnostics","memory","cpu","electron","process","recording"],isAvailable:t=>t.isDesktop},{id:"chat.draft-starters-visible",page:"chat",title:"Show Starters on New Session Screen",keywords:["starter","starters","new session","welcome","suggestions"]},{id:"chat.follow-up-behavior",page:"chat",title:"Follow-up behavior",description:"Choose what happens when you send a follow-up while the agent is still responding. Follow-up waits until the agent finishes; Steering is delivered at the next supported tool or turn boundary. Follow-ups stay on this device.",keywords:["follow up","follow-up","queue","steer","steering","send immediately","send now"]},{id:"sessions.default-model",page:"sessions",title:"Default Model",keywords:["model","provider","new sessions","picker"]},{id:"sessions.default-thinking",page:"sessions",title:"Default Thinking",keywords:["thinking","reasoning","variant","new sessions","per model"]},{id:"sessions.default-retry-limit",page:"sessions",title:"Default retry limit",description:"How many times Pi automatically retries a failed agent turn for new sessions.",keywords:["retry","retries","retry limit","auto retry","max retries","agent run"]},{id:"sessions.thinking-defaults",page:"sessions",title:"Thinking defaults",description:"Per-model thinking for new sessions and composer model changes.",keywords:["thinking","reasoning","per model","default thinking"]},{id:"sessions.deletion-dialog",page:"sessions",title:"Show Deletion Dialog",keywords:["delete","confirmation"]},{id:"sessions.small-model",page:"sessions",title:"Small Model",description:"A cheap model for quick utility tasks like short recaps and summaries.",keywords:["small model","utility","summary","recap","cheap","override","picker"]},{id:"sessions.walkthrough-model",page:"sessions",title:"Changes Walkthrough Model",description:"The AI review of your changes needs structured output and room for a whole diff, which a cheap small model often cannot give. Models the catalog reports as unable to produce structured output are hidden from this picker. Leave it unset and the small model is used.",keywords:["walkthrough","diff","review","changes","structured output","model","override","picker"]},{id:"sessions.auto-cleanup",page:"sessions",title:"Enable Auto-Cleanup",description:"Automatically archive or delete inactive sessions based on last activity. Keeps the 5 most recent sessions.",keywords:["retention","archive","delete"]},{id:"sessions.retention-period",page:"sessions",title:"Retention Period",keywords:["days","cleanup","retention"]},{id:"sessions.retention-action",page:"sessions",title:"When sessions expire",keywords:["archive","delete","expire"]},{id:"sessions.desktop-launch-at-login",page:"general",title:"Start PiChamber when you log in",description:"Starts the app in the background without opening a window. Use the desktop status icon to open it.",keywords:["desktop","startup","login","launch","background","autostart"],isAvailable:t=>t.isDesktop},{id:"sessions.desktop-mac-menu-bar",page:"general",title:"Show PiChamber in the menu bar",description:"Requires an app restart. When off, PiChamber does not create the menu bar item or run its session, approval, and usage updates.",keywords:["desktop","menu bar","tray","status item","macos","background"],isAvailable:t=>t.isDesktopLocalOrigin&&t.isMac},{id:"sessions.desktop-minimize-to-tray",page:"general",title:"Minimize to the system tray",description:"Hides PiChamber in the system tray instead of leaving it in the taskbar when you minimize the window.",keywords:["desktop","tray","system tray","minimize","taskbar","background","windows","linux"],isAvailable:t=>t.isDesktop&&(t.isWindows||t.isLinux)},{id:"sessions.desktop-close-to-tray",page:"general",title:"Close to the system tray",description:"Keeps PiChamber running in the system tray when you close the main window. Turn this off to quit the app when the window closes.",keywords:["desktop","tray","system tray","close","quit","exit","background","windows","linux"],isAvailable:t=>t.isDesktop&&(t.isWindows||t.isLinux)},{id:"sessions.desktop-keep-awake",page:"general",title:"Keep computer awake while PiChamber is running",description:"Prevents system sleep so phones can keep reaching this app. The screen can still turn off.",keywords:["desktop","sleep","awake","server","mobile","phone"],isAvailable:t=>t.isDesktop},{id:"sessions.desktop-ui-password",page:"remote-access",title:"Desktop UI Password",description:"PiChamber asks after restart, then when the login session expires: after 12 hours, or 7 days with Trust this device. Leave empty to disable login.",keywords:["desktop","password","auth","login","remote access","security"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-lan-access",page:"remote-access",title:"Let other devices on your local network open this app",description:"Restarts the app so phones, tablets, and other computers on your Wi-Fi can open it. On Windows, allow PiChamber through the firewall if a phone still cannot connect.",keywords:["desktop","lan","network","phone","tablet","wifi","firewall","remote access","local network"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"git.github-status",page:"git",title:"GitHub CLI status",description:"Installed version and signed-in hosts.",keywords:["github","gh","cli","version","installed"]},{id:"git.github-account",page:"git",title:"GitHub account",description:"Signed-in account per host from the GitHub CLI (read-only).",keywords:["github","account","login","gh auth","prs","issues"]},{id:"git.github-scopes",page:"git",title:"GitHub token scopes",description:"Missing scopes with the gh auth refresh command.",keywords:["github","scopes","token","permissions","gh auth refresh"]},{id:"git.github-check-again",page:"git",title:"Check GitHub again",keywords:["github","refresh","retry","check again"]},{id:"git.changes-view",page:"git",title:"Changes View",keywords:["changes","flat list","tree view"]},{id:"git.gitignored-files",page:"git",title:"Display Gitignored Files",keywords:["ignored","files","gitignore"]},{id:"projects.name",page:"projects",title:"Name",keywords:["label","display name","project metadata","project name"]},{id:"projects.default-model",page:"projects",title:"Default model",keywords:["model","provider","new chat","session default","project metadata"]},{id:"projects.worktree",page:"projects",title:"Worktree",keywords:["worktree","branch","repository"]},{id:"projects.worktree.setup.wait",page:"projects",title:"Wait for setup commands before creating or sending a session",keywords:["worktree","setup commands","bootstrap","wait"]},{id:"remote-access.client-auth",page:"remote-access",title:"Add a device",description:"Create a one-time QR code so the PiChamber app on another device can connect to this server.",keywords:["pairing link","pair","qr","device","devices","mobile","phone","remote access","relay","connect from anywhere"]},{id:"remote-access.ways",page:"remote-access",title:"Ways to connect",description:"Local network and Tailscale routes other devices can use to reach this computer.",keywords:["connect","route","routes","remote access","lan","tailscale"]},{id:"remote-access.lan",page:"remote-access",title:"Local network",description:"Phones and computers on your Wi-Fi reach this computer directly.",keywords:["lan","network","wifi","local network","remote access"]},{id:"remote-access.tailscale",page:"remote-access",title:"Tailscale",description:"Private tailnet or public Funnel address for this computer.",keywords:["tailscale","funnel","vpn","tailnet","private","public","remote access","serve"]},{id:"remote-access.tailscale-port",page:"remote-access",title:"Tailscale HTTPS port",description:"HTTPS port for the Tailscale address.",keywords:["port","443","8443","10000","https","conflict"]},{id:"remote-access.devices",page:"remote-access",title:"Devices with access",description:"Paired devices and pending pairings. Revoking removes a device immediately.",keywords:["device","devices","paired","revoke","remove device","remote access"]},{id:"remote-access.security",page:"remote-access",title:"Remote access security",description:"The password protects browser sign-in and is required for Local network and Tailscale access.",keywords:["security","password","passkey","remote access","sign-in","login"]},{id:"remote-access.passkeys",page:"remote-access",title:"Passkeys",description:"Sign in with a passkey instead of the UI password.",keywords:["passkey","passkeys","webauthn","password","remote access","security"],isAvailable:t=>t.isWeb&&!t.isDesktop&&!t.isMobile},{id:"servers.direct-hosts",page:"servers",title:"Other PiChamber servers",description:"Servers this app can switch to. Import a pairing link from the other server, or add one by address.",keywords:["server","servers","instance","server url","connection token","import link","host switcher","switch","connect","additional headers","request headers","cloudflare access","service token"],isAvailable:t=>t.isDesktop||t.isMobile&&t.isCapacitor===!0},{id:"behavior.system-prompt",page:"behavior",title:"Global AGENTS.md",description:"Global rules are combined with project rules",keywords:["agents.md","global instructions","system prompt"]},{id:"behavior.response-style",page:"behavior",title:"Response style",description:"When enabled, these instructions guide how the assistant responds in each new conversation. They are sent with your first message and do not change your global AGENTS.md rules.",keywords:["tone","concise","detailed","custom instructions"]},{id:"snippets.create",page:"snippets",title:"Create snippet",keywords:["add","new snippet"]},{id:"snippets.content",page:"snippets",title:"Content",keywords:["markdown","text expansion"]},{id:"prompt-templates.create",page:"prompt-templates",title:"Create prompt template",keywords:["add","new prompt","slash command"]},{id:"prompt-templates.content",page:"prompt-templates",title:"Content",keywords:["markdown","prompt","template","arguments"]},{id:"providers.connect",page:"providers",title:"Connect Provider",keywords:["add provider","connect provider","credentials"]},{id:"providers.custom",page:"providers",title:"Custom provider",description:"Add an OpenAI-compatible provider with a base URL, credentials, and model list. Saved to Pi so it is available in chat like any other provider.",keywords:["other","custom","openai-compatible","base url","api key"]},{id:"providers.auth",page:"providers",title:"Authentication",keywords:["api key","oauth","credentials"]},{id:"providers.connection-details",page:"providers",title:"Connection Details",keywords:["config","source","disconnect"]},{id:"providers.models",page:"providers",title:"Available Models",description:"Hide models you do not want in the composer or session default pickers.",keywords:["models","hide","show"]},{id:"skills.discovery",page:"skills.installed",title:"Skills",keywords:["skills","agent skills","project resources"]},{id:"shortcuts.keyboard-shortcuts",page:"shortcuts",title:"Keyboard Shortcuts",description:"Capture a new key combo, save it, and bindings will update immediately.",keywords:["keyboard","hotkeys","bindings"]},{id:"shortcuts.command-triggers",page:"shortcuts",title:"Command triggers",description:"Quick-action buttons above the composer and optional keybindings that run slash commands.",keywords:["quick actions","slash commands","toolbar buttons","triggers"]},{id:"tunnel.provider",page:"tunnel",title:"Provider",description:"Configure secure remote access with your own managed Cloudflare tunnel.",keywords:["managed remote","managed local","cloudflare"]},{id:"tunnel.type",page:"tunnel",title:"Tunnel type",keywords:["managed remote","managed local"]},{id:"tunnel.ttl",page:"tunnel",title:"Connect link TTL",description:"Tunnel session TTL",keywords:["expiry","expiration","session ttl","connect link ttl"]},{id:"tunnel.managed-remote",page:"tunnel",title:"Saved managed remote tunnels",keywords:["cloudflare","hostname","token","managed remote"]},{id:"tunnel.managed-local-config",page:"tunnel",title:"Configuration file",description:"Managed local tunnels use your local cloudflared configuration file.",keywords:["cloudflared","config","yaml","json","managed local"]},{id:"tunnel.start",page:"tunnel",title:"Start Tunnel",description:"Connect links are one-time and are revoked when tunnel stops or connect-link TTL expires.",keywords:["connect link","qr code","public url","remote access"]},{id:"notifications.delivery",page:"notifications",title:"Notification delivery",keywords:["desktop notifications","mobile notifications","system notifications"]},{id:"notifications.events",page:"notifications",title:"Notification events",keywords:["completion","finished","errors","failed","input needed","approval","waiting","extension"]}];function lr(t){return t.trim().toLocaleLowerCase()}function op({query:t,runtimeCtx:s,visiblePageSlugs:a,getPageTitle:n}){const r=lr(t);if(!r)return[];const l=a?new Set(a):null,d=r.split(/\s+/).filter(Boolean);return ip.flatMap(i=>{if(l&&!l.has(i.page))return[];const u=gs(i.page);if(!u||u.isAvailable&&!u.isAvailable(s)||i.isAvailable&&!i.isAvailable(s))return[];const m=i.title,p=i.description??null,h=lr([m,p,n(i.page),...i.keywords??[]].filter(Boolean).join(" "));return d.every(c=>h.includes(c))?[{...i,title:m,description:p,pageTitle:n(i.page)}]:[]})}function lp({runtimeCtx:t,visiblePageSlugs:s,getPageTitle:a,openPage:n,isMobile:r,setMobileStage:l,containerRef:d,settingsSlug:i}){const[u,m]=o.useState(""),[p,h]=o.useState(!1),c=o.useRef(null),[f,y]=o.useState(null),[b,v]=o.useState(0),L=o.useRef([]),j=o.useRef(0),T=o.useRef(!1),P=o.useMemo(()=>op({query:u,runtimeCtx:t,visiblePageSlugs:s,getPageTitle:a}),[a,t,u,s]),A=o.useCallback(x=>{if(x.id.startsWith("snippets.")){const N=tt.getState(),k=or("new-snippet",N.snippets.map(I=>I.name));return N.setSnippetDraft({name:k,scope:"global"}),N.setSelectedSnippet(null),x.id==="snippets.create"?"snippets.content":x.id}if(x.id.startsWith("prompt-templates.")){const N=st.getState(),k=or("new-prompt",N.prompts.map(I=>I.name));return N.setPromptDraft({name:k,location:"global"}),N.setSelectedPrompt(null),x.id==="prompt-templates.create"?"prompt-templates.content":x.id}return x.id==="providers.connect"&&Ha.getState().setSelectedProviderId(null),x.id},[]),g=o.useMemo(()=>{const x=[],N=new Map;for(const k of P){let I=N.get(k.page);I||(I={page:k.page,pageTitle:k.pageTitle,results:[]},N.set(k.page,I),x.push(I)),I.results.push(k)}return x},[P]);o.useEffect(()=>{v(0),j.current=0,T.current=!1},[u]),o.useEffect(()=>{j.current=b},[b]),o.useEffect(()=>{L.current[b]?.scrollIntoView({block:"nearest"})},[b]),o.useEffect(()=>{b>=P.length&&v(Math.max(0,P.length-1)),L.current.length=P.length},[b,P.length]);const C=o.useCallback(x=>{const N=A(x);y(N),n(x.page),r&&l("page-content")},[r,n,A,l]),w=o.useCallback(x=>{if(x.key==="Escape"){if(x.preventDefault(),u.trim()){m("");return}r&&p&&h(!1);return}if(u.trim()&&P.length!==0){if(x.key==="ArrowDown"){x.preventDefault(),T.current=!0,v(N=>(N+1)%P.length);return}if(x.key==="ArrowUp"){x.preventDefault(),T.current=!0,v(N=>(N-1+P.length)%P.length);return}if(x.key==="Enter"){x.preventDefault();const N=(j.current%P.length+P.length)%P.length,k=P[N]??P[0];k&&C(k)}}},[r,p,C,u,P]);return o.useEffect(()=>{const x=f;if(!x)return;let N=!1;const k=window.requestAnimationFrame(()=>{if(N)return;const I=typeof CSS<"u"&&CSS.escape?CSS.escape(x):x.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),S=d.current?.querySelector(`[data-settings-item="${I}"]`);if(S){y(null);for(let z=S.closest("details");z;z=z.parentElement?.closest("details")??null)z.open=!0;S.scrollIntoView({block:"center",behavior:"smooth"}),S.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{S.removeAttribute("data-settings-search-highlight")},1600)}});return()=>{N=!0,window.cancelAnimationFrame(k)}},[d,f,i]),{settingsSearchQuery:u,setSettingsSearchQuery:m,isMobileSettingsSearchOpen:p,setIsMobileSettingsSearchOpen:h,mobileSettingsSearchInputRef:c,activeSearchResultIndex:b,setActiveSearchResultIndex:v,searchResultRefs:L,keyboardSearchNavigationRef:T,settingsSearchResults:P,groupedSettingsSearchResults:g,openSearchResult:C,handleSettingsSearchKeyDown:w}}const cp=({mobileStage:t,activePageMeta:s,getPageTitle:a,showBackButton:n,mobileBackButtonLabel:r,onBack:l,showOpenPageSidebarButton:d,onOpenPageSidebar:i,isMobileSettingsSearchOpen:u,setIsMobileSettingsSearchOpen:m,mobileSettingsSearchInputRef:p,settingsSearchQuery:h,setSettingsSearchQuery:c,handleSettingsSearchKeyDown:f,onClose:y,shortcutKey:b})=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:H("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",t!=="nav"&&"border-b","bg-background"),style:t!=="nav"?{borderColor:"var(--interactive-border)"}:void 0,children:[n?e.jsx("button",{type:"button",onClick:l,"aria-label":r,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):null,e.jsx("div",{className:"min-w-0 flex-1 px-2 typography-ui-label font-medium text-foreground truncate",children:t==="nav"?"Settings":s?a(s.slug):"Settings"}),d&&e.jsx("button",{type:"button",onClick:i,"aria-label":"Open section list",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"list-unordered",className:"h-5 w-5"})}),t==="nav"?e.jsx("button",{type:"button",onClick:()=>{const v=!u;m(v),v?window.setTimeout(()=>p.current?.focus(),0):c("")},"aria-label":u?"Close search":"Search settings","aria-expanded":u,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:u?"close":"search",className:"h-5 w-5"})}):null,y&&e.jsx("button",{type:"button",onClick:y,"aria-label":"Close settings",title:`Close Settings (${b}+,)`,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"close",className:"h-5 w-5"})})]}),t==="nav"&&u?e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b bg-background px-3 py-2",style:{borderColor:"var(--interactive-border)"},children:e.jsxs("div",{className:"flex h-10 min-w-0 flex-1 items-center gap-1.5 rounded-md border border-border bg-transparent px-2 text-muted-foreground focus-within:ring-2 focus-within:ring-primary/40",children:[e.jsx(R,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{ref:p,value:h,onChange:v=>c(v.target.value),onKeyDown:f,placeholder:"Search settings","aria-label":"Search settings",className:"typography-ui-label min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground/70"}),h.trim().length>0?e.jsx("button",{type:"button",onClick:()=>c(""),"aria-label":"Clear settings search",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})}):null]}),dp=({onClose:t,forceMobile:s,isWindowed:a,visiblePageSlugs:n,initialMobileStage:r="nav",onActiveConnectionDeleted:l})=>{const d=Ze(),i=s??d.isMobile,u=Zo(),m=rp(u?.instanceLabel),p=W(te=>te.settingsPage),h=W(te=>te.isSettingsDialogOpen),c=W(te=>te.setSettingsPage),f=dl(p),[y,b]=o.useState(r),v=o.useRef(r==="nav"?f:null);o.useEffect(()=>{!i&&f==="home"&&c("general")},[i,c,f]);const L=o.useRef(null),[j,T]=o.useState(0);o.useEffect(()=>ea(()=>{T(te=>te+1)}),[]);const P=o.useMemo(()=>Le(),[]),A=o.useMemo(()=>Le()&&Kt(),[j]),g=o.useMemo(()=>Le()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),C=o.useMemo(()=>Le()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="win32",[]),w=o.useMemo(()=>Le()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="linux",[]),x=o.useMemo(()=>ko(),[]),N=o.useMemo(()=>Ee(),[]),k=o.useMemo(()=>tp(P,i,N),[P,i,N]),I=o.useMemo(()=>{const te=n?new Set(n):null;return ul.filter(ge=>ge.slug!=="home").filter(ge=>!te||te.has(ge.slug)).filter(ge=>Ci(ge,k)).filter(ge=>!(i&&(ge.slug==="remote-access"||ge.slug==="remote-instances"||ge.slug==="servers"&&!N)))},[N,i,k,n]),S=o.useMemo(()=>{const te=new Map(ep.map((ge,$e)=>[ge,$e]));return I.slice().sort((ge,$e)=>(te.get(ge.slug)??999)-(te.get($e.slug)??999))},[I]),z=Vs(te=>te.activeProjectId);o.useEffect(()=>{!h&&!a||f==="skills.installed"&&Mt.getState().loadSkills()},[z,h,a,f]);const _=o.useCallback(te=>{if(c(te),v.current=te,!i)return;const ge=gs(te);if(!ge||ge.slug==="home"){b("nav");return}b(ge.kind==="split"?"page-sidebar":"page-content")},[i,c]),O=o.useMemo(()=>gs(f),[f]),V=o.useMemo(()=>({general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",tunnel:"tunnel"}),[]),K=o.useCallback(te=>{switch(te){case"general":return"General";case"projects":return"Projects";case"remote-access":return"Remote Access";case"servers":return"Servers";case"remote-instances":return"Remote Access";case"providers":return"Providers";case"behavior":return"Behavior";case"skills.installed":return"Skills";case"git":return"Git";case"appearance":return"Appearance";case"chat":return"Chat";case"dictation":return"Dictation";case"shortcuts":return"Shortcuts";case"sessions":return"Sessions";case"snippets":return"Snippets";case"prompt-templates":return"Prompt templates";case"notifications":return"Notifications";case"tunnel":return"External Tunnel";case"about":return"About";default:return"Settings"}},[]),Z=o.useMemo(()=>({...k,isDesktopLocalOrigin:A,isMac:g,isWindows:C,isLinux:w,isWindowsArm64:x}),[A,w,g,C,x,k]),{settingsSearchQuery:ae,setSettingsSearchQuery:fe,isMobileSettingsSearchOpen:ce,setIsMobileSettingsSearchOpen:be,mobileSettingsSearchInputRef:ie,activeSearchResultIndex:ne,setActiveSearchResultIndex:pe,searchResultRefs:oe,keyboardSearchNavigationRef:G,settingsSearchResults:q,groupedSettingsSearchResults:Ce,openSearchResult:re,handleSettingsSearchKeyDown:me}=lp({runtimeCtx:Z,visiblePageSlugs:n,getPageTitle:K,openPage:_,isMobile:i,setMobileStage:b,containerRef:L,settingsSlug:f});o.useEffect(()=>{if(!i||y!=="nav"||f==="home"||v.current===f)return;const te=gs(f);!te||te.slug==="home"||(v.current=f,b(te.kind==="split"?"page-sidebar":"page-content"))},[i,y,f]);const J=i&&y!=="nav",B=y==="page-content"&&O?.kind==="split",U=J?"Back to Settings":"Close settings",X=No(),he=o.useCallback(()=>{b("page-content")},[]),je=o.useCallback(()=>{b("nav")},[]),Se=o.useCallback(()=>{b("page-sidebar")},[]);o.useEffect(()=>{(!i||y!=="nav")&&be(!1)},[i,y,be]);const et=o.useCallback((te,ge)=>null,[]),F=()=>e.jsx(np,{isMobile:i,isMobileSettingsSearchOpen:ce,settingsSearchQuery:ae,setSettingsSearchQuery:fe,handleSettingsSearchKeyDown:me,settingsSearchResults:q,groupedSettingsSearchResults:Ce,activeSearchResultIndex:ne,setActiveSearchResultIndex:pe,searchResultRefs:oe,keyboardSearchNavigationRef:G,openSearchResult:re,sortedFilteredPages:S,settingsSlug:f,mobileStage:y,openPage:_,getPageTitle:K,activeRemoteLabel:m,mobileAppActions:u}),Q=()=>{if(y==="nav")return e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden bg-background",children:e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx(gt,{children:F()})})});if(!O)return e.jsx("div",{className:"flex-1 bg-background"});if(y==="page-sidebar"){if(O.kind!=="split"){const te=e.jsx(zs,{slug:f,isMobile:i,runtimeCtx:k,openChamberSectionBySlug:V,onActiveConnectionDeleted:l});return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(gt,{children:te})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(gt,{children:et(f,{onItemSelect:he})})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(gt,{children:e.jsx(zs,{slug:f,isMobile:i,runtimeCtx:k,openChamberSectionBySlug:V,onActiveConnectionDeleted:l})})})},de=()=>!O||f==="home"?null:O.kind==="split"?e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[e.jsx("div",{className:H("border-r","bg-sidebar"),style:{width:ir,minWidth:ir,borderColor:"var(--interactive-border)"},children:e.jsx(gt,{children:et(f,{})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(gt,{children:e.jsx(zs,{slug:f,isMobile:i,runtimeCtx:k,openChamberSectionBySlug:V,onActiveConnectionDeleted:l})})})]}):e.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(gt,{children:e.jsx(zs,{slug:f,isMobile:i,runtimeCtx:k,openChamberSectionBySlug:V,onActiveConnectionDeleted:l})})});return e.jsxs("div",{ref:L,"data-settings-view":"true",className:H("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),children:[i?e.jsx(cp,{mobileStage:y,activePageMeta:O,getPageTitle:K,showBackButton:J,mobileBackButtonLabel:U,onBack:je,showOpenPageSidebarButton:!!B,onOpenPageSidebar:Se,isMobileSettingsSearchOpen:ce,setIsMobileSettingsSearchOpen:be,mobileSettingsSearchInputRef:ie,settingsSearchQuery:ae,setSettingsSearchQuery:fe,handleSettingsSearchKeyDown:me,onClose:t,shortcutKey:X}):e.jsx(e.Fragment,{children:J&&e.jsx("div",{className:H("absolute left-3 z-50",a?"top-2":"top-3"),children:e.jsx("button",{type:"button",onClick:je,"aria-label":"Back",className:"inline-flex h-9 w-9 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})})})}),e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:i?Q():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:H("relative flex h-full min-h-0 flex-col overflow-hidden border-r","bg-sidebar"),style:{width:`${rr}px`,minWidth:`${rr}px`,borderColor:"var(--interactive-border)"},children:e.jsx(gt,{children:F()})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:de()})]})})]})},jp=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:dp},Symbol.toStringTag,{value:"Module"}));export{ni as A,ec as M,dp as S,tc as a,Zl as b,Ut as c,Aa as d,Zc as e,Bl as f,Fl as g,jp as h,Ql as i,Xl as m,ti as p,Qr as r,Jl as s,Xr as u};