@pi-chamber/web 0.7.2 → 0.8.0
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.
- package/README.md +1 -1
- package/dist/assets/{DiagramEditor-TeJ1G_NN.js → DiagramEditor-YPSKccgo.js} +1 -1
- package/dist/assets/DiagramView-C-PbBHce.js +1 -0
- package/dist/assets/DiffView-DfltyfN2.js +18 -0
- package/dist/assets/FilesView-BEjbLiK2.js +6 -0
- package/dist/assets/GitView-B_zTaXX4.js +8 -0
- package/dist/assets/JsonTreeView-9p4txyB_.js +1 -0
- package/dist/assets/MarkdownRendererImpl-CbRPLK2x.js +12 -0
- package/dist/assets/PatchDiff-rKjeUBRl.js +1 -0
- package/dist/assets/SessionSwitcherContent-C_VxKFJy.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-_k4P32o9.js +2 -0
- package/dist/assets/SessionUnreadDot-bT_0MixU.js +1 -0
- package/dist/assets/SettingsView-CqZ1ZAWG.js +2 -0
- package/dist/assets/SettingsWindow-C7vVE35-.js +1 -0
- package/dist/assets/ToolOutputDialog-GBbzATa6.js +8 -0
- package/dist/assets/ToolPartDiffPreview-Bdb9p5uS.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-sRc4lN0B.js → VirtualizedFileDiff-CA8hQyz9.js} +4 -4
- package/dist/assets/{Virtualizer-BxW2CJGB.js → Virtualizer-BSHVMKgK.js} +1 -1
- package/dist/assets/{appThemeRegistry-BK0dHKa6.js → appThemeRegistry-gegrE2dq.js} +1 -1
- package/dist/assets/collapsible-uwSKBy-K.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-9LNCLvAG.js +3 -0
- package/dist/assets/contextFileOpenGuard-CZSqdEHk.js +1 -0
- package/dist/assets/gitStatusPredicates-CRmbLl-x.js +134 -0
- package/dist/assets/index-BeJEipxi.js +1 -0
- package/dist/assets/index-CaP8oFLB.js +8 -0
- package/dist/assets/index-Dq8CnRYM.css +1 -0
- package/dist/assets/isDiffPlainText-YYyZNTdb.js +1 -0
- package/dist/assets/isFilePlainText-C70Z71bG.js +1 -0
- package/dist/assets/main-CsdVAKy_.js +135 -0
- package/dist/assets/main-GMQIZjuQ.js +2 -0
- package/dist/assets/{markdownCore-BfuFM7mg.js → markdownCore-BgVcDt0q.js} +2 -2
- package/dist/assets/miniChat-W6YsdiWR.js +2 -0
- package/dist/assets/mobile-BFR9CR5w.js +2 -0
- package/dist/assets/{permissionStore-BRcQ9Jgt.js → permissionStore-iKN1K2_x.js} +1 -1
- package/dist/assets/registerCustomTheme-DmolaWWZ.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-B8ZiW-3E.js +2 -0
- package/dist/assets/renderMobileApp-C5CdsYP6.js +11 -0
- package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +54 -0
- package/dist/assets/{runtimeSurface-DF3VwUlO.js → runtimeSurface-B818u-_c.js} +1 -1
- package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
- package/dist/assets/{WindowsWindowControls-CCnU0ckO.js → useAppFontEffects-CYzYRbLp.js} +126 -499
- package/dist/assets/useFilesViewSearch-C--GWtn-.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-D9lajdAc.js +10 -0
- package/dist/assets/useSwitcherItems-DOoi3x_8.js +1 -0
- package/dist/assets/vendor-base-ui-vkqQ2P9o.js +1 -0
- package/dist/assets/{vendor-beautiful-mermaid-r4GK_usS.js → vendor-beautiful-mermaid-DneUawHp.js} +1 -1
- package/dist/assets/{vendor-cmdk-BCEUzcHE.js → vendor-cmdk-zXx6sGnS.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-BS2SpSAZ.js → vendor-codemirror-autocomplete-wd6iRebq.js} +1 -1
- package/dist/assets/{vendor-codemirror-commands-RrgJ8H_6.js → vendor-codemirror-commands-DYppkHEk.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-ADhO_TUK.js → vendor-codemirror-lang-angular-DU_4KiiW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-BGCWj7Om.js → vendor-codemirror-lang-cpp-CmIT9Z5_.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-Ba8JZ6fp.js → vendor-codemirror-lang-css-djiuoTi8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-DyTiHXo4.js → vendor-codemirror-lang-go-COZSwZYW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DK27qQri.js → vendor-codemirror-lang-html-CKHqhW5R.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CvFfnhPQ.js → vendor-codemirror-lang-java-CNMP5hyC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-BUlYhQ3o.js → vendor-codemirror-lang-javascript-DuOEwJ3f.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-wBMtAEvT.js → vendor-codemirror-lang-jinja-DaKn_b1k.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-CqayksDf.js → vendor-codemirror-lang-json-CZ07HmNC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-Ct3-H1PB.js → vendor-codemirror-lang-less-wJdQiDBf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-XspREksq.js → vendor-codemirror-lang-liquid-0z48Roi8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-CvO36Y1p.js → vendor-codemirror-lang-markdown-DtcZDGqe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BlUF9cCe.js → vendor-codemirror-lang-php-W8plS-JQ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-_2bIYTiJ.js → vendor-codemirror-lang-python-DzzokVau.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-BdTYih_U.js → vendor-codemirror-lang-rust-C4ulBVpf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-E6MhfOFk.js → vendor-codemirror-lang-sass-BkZJYEwS.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-B1BRhQSF.js → vendor-codemirror-lang-sql-HpQWHJjv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-BYQJRa1Q.js → vendor-codemirror-lang-vue-DiBPljCc.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-D706yuyC.js → vendor-codemirror-lang-wast-DoABsogh.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml--MfWU6Dj.js → vendor-codemirror-lang-xml-BhLJhOCH.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-CRUFIbRX.js → vendor-codemirror-lang-yaml-D95i1Y5R.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-E2vgV9K3.js → vendor-codemirror-language-BByA_dGF.js} +2 -2
- package/dist/assets/{vendor-codemirror-language-data-C7_BPMCr.js → vendor-codemirror-language-data-DS_4W5G4.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-8kyQdB3f.js → vendor-codemirror-search-BV44140v.js} +1 -1
- package/dist/assets/{vendor-codemirror-view-DSzLbZiS.js → vendor-codemirror-view-Ct4T37Ue.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-accessibility-Cv52zwWT.js → vendor-dnd-kit-accessibility-DZKKhs9S.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-core-GipZW2tY.js → vendor-dnd-kit-core-CP8ck10N.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-Ct2QxIHb.js → vendor-dnd-kit-sortable-B-Icjoj4.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-utilities-CrOcp0Bp.js → vendor-dnd-kit-utilities-DTY1C6ST.js} +1 -1
- package/dist/assets/{vendor-elkjs-CRCLNXjf.js → vendor-elkjs-mzfkf0ML.js} +1 -1
- package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
- package/dist/assets/{vendor-floating-ui-react-dom-sVFnuruh.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
- package/dist/assets/{vendor-framer-motion-DJASDzNt.js → vendor-framer-motion-BUygY0oN.js} +1 -1
- package/dist/assets/{vendor-heic2any-L8hyfc24.js → vendor-heic2any-BHsbokcA.js} +1 -1
- package/dist/assets/{vendor-lru_map-B-cPXHXW.js → vendor-lru_map-Cy8fTs3_.js} +1 -1
- package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
- package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
- package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
- package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
- package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
- package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
- package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
- package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
- package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
- package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
- package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
- package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
- package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
- package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
- package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
- package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
- package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
- package/dist/assets/{web-components-BYNCGylQ.js → web-components-C2cMNPqE.js} +2 -2
- package/dist/index.html +6 -6
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +1 -1
- package/server/lib/git/DOCUMENTATION.md +3 -2
- package/server/lib/git/routes.js +27 -0
- package/server/lib/git/routes.test.js +41 -0
- package/server/lib/git/service.js +7 -1
- package/server/lib/git/service.test.js +23 -0
- package/server/lib/pi/routes.js +263 -6
- package/server/lib/pi/routes.test.js +314 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
- package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
- package/server/lib/pi/session-daemon/session-daemon.js +309 -25
- package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
- package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
- package/server/lib/pi/snippets-store.js +400 -0
- package/server/lib/pi/snippets-store.test.js +252 -0
- package/server/lib/relay/host-client.test.js +79 -15
- package/server/lib/server/cors.js +2 -0
- package/server/lib/server/cors.test.js +6 -5
- package/dist/assets/CommitSection-DfAlM30E.js +0 -1
- package/dist/assets/DiagramView-DKLIwNth.js +0 -1
- package/dist/assets/DiffView-CZyqSs5W.js +0 -18
- package/dist/assets/FilesView-rftA7fEL.js +0 -14
- package/dist/assets/GitView-D5LMTT2M.js +0 -6
- package/dist/assets/JsonTreeView-DMI3-Smy.js +0 -1
- package/dist/assets/MarkdownRendererImpl-gdd-5n9J.js +0 -12
- package/dist/assets/PatchDiff-GNB1NlAN.js +0 -1
- package/dist/assets/PierreDiffViewer-DmJv2AoJ.js +0 -136
- package/dist/assets/SessionSwitcherContent-CWdDPll7.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-Cx-Jfmvo.js +0 -2
- package/dist/assets/SessionUnreadDot-CKe4uVcf.js +0 -1
- package/dist/assets/SettingsView-DaxkNy5C.js +0 -4
- package/dist/assets/SettingsWindow-D1M_rRDo.js +0 -1
- package/dist/assets/ToolOutputDialog-CUKcp77A.js +0 -15
- package/dist/assets/ToolPartDiffPreview-CkzwXAC5.js +0 -8
- package/dist/assets/collapsible-B0cIItyf.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-B1uVA58l.js +0 -3
- package/dist/assets/contextFileOpenGuard-BuedQ5EQ.js +0 -1
- package/dist/assets/index-BA67uOfZ.js +0 -1
- package/dist/assets/index-CcbDTf8Q.js +0 -8
- package/dist/assets/index-Cl3XbCeC.css +0 -1
- package/dist/assets/isDiffPlainText-DLDFLL6P.js +0 -1
- package/dist/assets/isFilePlainText-B2wwrpRU.js +0 -1
- package/dist/assets/main-B5k0qpHJ.js +0 -133
- package/dist/assets/main-Bepu8Jr9.js +0 -2
- package/dist/assets/miniChat-Co0Snpgl.js +0 -2
- package/dist/assets/mobile-CSvL_Zyu.js +0 -2
- package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-DrMJ1RXX.js +0 -2
- package/dist/assets/renderMobileApp-B2toAnMW.js +0 -14
- package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
- package/dist/assets/useInlineCommentController-CxMP78jg.js +0 -2
- package/dist/assets/usePanelSlide-DUuoQt5X.js +0 -56
- package/dist/assets/usePushVisibilityBeacon-CSPdFBaA.js +0 -10
- package/dist/assets/useSwitcherItems-zOeC2Cta.js +0 -1
- package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
- package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
- package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
- package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
- /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/useAppFontEffects-CYzYRbLp.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-CaP8oFLB.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-Dq8CnRYM.css","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-B818u-_c.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DS_4W5G4.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-BUygY0oN.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/renderMobileApp-C5CdsYP6.js","assets/vendor-katex-CNckGUMB.js","assets/vendor-katex-Cp579UoJ.css","assets/usePushVisibilityBeacon-D9lajdAc.js","assets/runtimeEndpointReset-D3AZYuoF.js","assets/SessionUnreadDot-bT_0MixU.js","assets/permissionStore-iKN1K2_x.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-capacitor-core-B4EWRrHz.js","assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js","assets/useSwitcherItems-DOoi3x_8.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as a,j as e,r as ge}from"./vendor-react-B5Z1Mdn3.js";import{r as Be,v as Le,w as it,c as J,u as _,H as Ut,af as zt,b as Re,C as es,ag as tn,ah as sn,ai as an,aj as ja,ak as Jt,aa as wr,al as kr,a9 as Nr,am as Cr,an as Sr,ao as Pr,ap as Tr,aq as Ir,ar as Er,a5 as Mr,as as ot,y as ke,Q as Ar,at as Dr,p as Yt,au as nn,av as wa,aw as ka,ax as Na,ay as Ca,az as Lr,P as Rr,aA as Sa,aB as zr,aC as _r,A as bt,aD as Or,a3 as ia,aE as Ur,aF as Fr,B as Br,aG as Hr,aH as Kr,aI as $r,aJ as Gr,aK as Wr,aL as Vr,aM as qr,aN as Qr,aO as Jr,aP as rt,m as Pa,aQ as Ta,aR as Vs,Y as Yr,$ as Ia,aS as oa,aT as Ea,aU as Xr,i as rn,aV as Zr,N as ei}from"./index-CaP8oFLB.js";import{U as S,I as T,aw as on,b9 as Ve,t as F,bx as ti,aQ as lt,aR as ct,bi as dt,bj as ut,bk as mt,bl as Ot,ao as si,aL as la,cu as kt,bg as ie,c as bs,be as ai,ci as Ma,af as ni,j as ln,bC as ri,cv as ii,cw as cn,cx as dn,cy as un,cd as _e,ce as Oe,cf as Ue,cz as mn,cA as vs,cg as Fe,ch as Ee,L as Ae,cB as ys,aB as pn,cC as et,cD as tt,cE as oi,cF as li,cG as ci,D as di,a as ui,b as mi,bm as pi,aN as hi,cH as gi,cI as fi,cJ as xi,cK as bi,cL as vi,cM as qs,cN as Aa,cO as yi,cP as ji,cQ as wi,cR as ki,cS as Ni,cT as Ci,E as hn,F as gn,G as Si,cU as Pi,$ as ft}from"./useAppFontEffects-CYzYRbLp.js";import{q as Ti,P as Ii,U as Da,Q as te,R as He,V as La,W as Ei,X as Mi,Y as Ai,Z as fn,_ as Cs,$ as vt,a0 as ht,a1 as Ra,a2 as Me,a3 as St,a4 as Ge,a5 as ze,a6 as ca,a7 as Ke,a8 as We,a9 as _t,aa as Nt,ab as Ct,ac as ve,L as Vt,C as Di,a as Li,b as Ri,c as zi,ad as yt,ae as js,af as ws,ag as Pt,ah as za,ai as Lt,aj as Rt,ak as Qs,al as xn,am as Xt,an as _i,h as Oi,ao as Ui,g as Fi}from"./runtimeEndpointReset-D3AZYuoF.js";import{_ as Zt}from"./vendor-vite-runtime-DD1OZmLC.js";import{Q as bn}from"./vendor-qrcode-B0KNSajT.js";import{u as vn,c as Bi}from"./vendor-zustand-GVb4H8HE.js";import{g as Hi,s as Ki}from"./runtimeSurface-B818u-_c.js";import{C as $i,a as Gi,b as Wi}from"./collapsible-uwSKBy-K.js";const Vi=["standalone","minimal-ui","fullscreen","window-controls-overlay"],qi=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Qi=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":Vi.find(n=>qi(n))??"browser",_a=()=>{const[t,s]=a.useState(null);a.useEffect(()=>{let i=!1;const o=typeof AbortController<"u"?new AbortController:void 0;return(async()=>{try{const h=await Be("/api/system/info",{signal:o?.signal,headers:{Accept:"application/json"}});if(!h.ok)return;const u=await h.json().catch(()=>null);if(!u||i)return;const d=typeof u.port=="number"&&Number.isFinite(u.port)&&u.port>0?u.port:null,w=typeof u.tunnelUrl=="string"&&u.tunnelUrl.trim().length>0?u.tunnelUrl.trim():null;s({port:d,tunnelUrl:w})}catch{}})(),()=>{i=!0,o?.abort()}},[]);const n=[];return t?.port!==null&&t?.port!==void 0&&n.push({key:"application",label:"Application",url:`http://localhost:${t.port}/`}),t?.tunnelUrl&&n.push({key:"tunnel",label:"Tunnel",url:t.tunnelUrl}),n.length===0?null:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:n.map(i=>e.jsxs(S,{type:"button",variant:"outline",size:"sm",title:i.label,className:"max-w-full gap-1.5 px-2.5",onClick:()=>{on(i.url)},children:[e.jsx(T,{name:"external-link",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"max-w-64 truncate font-mono typography-micro",children:i.url})]},i.key))})},ea="https://github.com/RyderAsKing/PiChamber",ta="https://pi.dev/",Ji=800,yn=({initialUpdateDialogOpen:t=!1})=>{const[s,n]=a.useState(t),[i,o]=a.useState(!1),[p,h]=a.useState(null),u=Ti(vn(r=>({info:r.info,checking:r.checking,available:r.available,error:r.error,downloading:r.downloading,downloaded:r.downloaded,progress:r.progress,runtimeType:r.runtimeType,checkForUpdates:r.checkForUpdates,downloadUpdate:r.downloadUpdate,restartToUpdate:r.restartToUpdate}))),{isMobile:d}=Ve(),w=p||u.info?.currentVersion||"unknown";a.useEffect(()=>{let r=!1;return(async()=>{try{const y=await Be("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!y.ok)return;const b=await y.json().catch(()=>null),j=typeof b?.pichamberVersion=="string"&&b.pichamberVersion.trim().length>0?b.pichamberVersion.trim():null;r||h(j)}catch{r||h(null)}})(),()=>{r=!0}},[]);const c=a.useRef(!1);a.useEffect(()=>{if(u.checking)o(!0),c.current=!0;else if(i){const r=setTimeout(()=>{o(!1),c.current&&!u.available&&!u.error&&(F.success("You are on the latest version"),c.current=!1)},Ji);return()=>clearTimeout(r)}},[u.checking,i,u.available,u.error]);const g=u.checking||i;return d?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(ti,{width:72,height:72}),e.jsx("h2",{className:`mt-4 ${Ii}`,children:"PiChamber"}),e.jsx("div",{className:"mt-2 space-y-1 typography-ui text-muted-foreground",children:e.jsx("p",{children:`PiChamber version ${w}`})}),e.jsx(_a,{})]}),e.jsxs("div",{className:"flex justify-center",children:[!u.available&&!u.error&&e.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:()=>u.checkForUpdates(),disabled:g,className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[g?e.jsx(T,{name:"loader",className:"size-4 animate-spin"}):e.jsx(T,{name:"refresh",className:"size-4"}),g?"Checking...":"Check for updates"]}),!g&&u.available&&e.jsxs(S,{type:"button",variant:"default",size:"sm",onClick:()=>n(!0),className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[e.jsx(T,{name:"download",className:"size-4"}),`Update to ${u.info?.version||""}`]})]}),u.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:u.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:ea,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(T,{name:"github-fill",className:"size-5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:ta,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(T,{name:"information",className:"size-5"}),e.jsx("span",{children:"Pi Agent"})]})]})}),e.jsx(Oa,{}),e.jsx("p",{className:"text-center typography-ui text-muted-foreground/60",children:"Made with care for the community"}),e.jsx(Da,{open:s,onOpenChange:n,info:u.info,downloading:u.downloading,downloaded:u.downloaded,progress:u.progress,error:u.error,onDownload:u.downloadUpdate,onRestart:u.restartToUpdate,runtimeType:u.runtimeType})]}):e.jsxs(e.Fragment,{children:[e.jsxs(te,{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:He,children:"Version"}),e.jsx("span",{className:"typography-meta text-muted-foreground font-mono",children:w})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[u.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(T,{name:"loader",className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!u.checking&&u.available&&e.jsxs(S,{size:"sm",variant:"default",onClick:()=>n(!0),children:[e.jsx(T,{name:"download",className:"h-4 w-4 mr-1"}),`Update to ${u.info?.version||""}`]}),!u.checking&&!u.available&&!u.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"}),e.jsx(S,{size:"sm",variant:"outline",onClick:()=>u.checkForUpdates(),disabled:u.checking,children:"Check for updates"})]})]}),u.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:u.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:He,children:"Instance URLs"}),e.jsx(_a,{})]}),e.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[e.jsxs("a",{href:ea,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(T,{name:"github-fill",className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:ta,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(T,{name:"information",className:"h-4 w-4"}),e.jsx("span",{children:"Pi Agent"})]})]})]}),e.jsx(Da,{open:s,onOpenChange:n,info:u.info,downloading:u.downloading,downloaded:u.downloaded,progress:u.progress,error:u.error,onDownload:u.downloadUpdate,onRestart:u.restartToUpdate,runtimeType:u.runtimeType})]}),e.jsx(Oa,{})]})},Oa=()=>e.jsxs(e.Fragment,{children:[e.jsx(te,{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(te,{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(te,{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:ta,target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline underline-offset-4 hover:text-primary",children:"pi.dev"}),"."]})]})}),e.jsx(te,{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, Ghostty-web, and every contributor whose work, feedback, and ideas help make this project possible."})]})}),e.jsx(te,{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:ea,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"})]})})]}),Yi=({onResolved:t})=>{const[s,n]=a.useState(!1),[i,o]=a.useState(!1);a.useEffect(()=>{let h=!0;return Le.getSettings({runtimeKey:it()}).then(u=>{h&&n(u.pi.project.requiresTrust===!0)}).catch(()=>{}),()=>{h=!1}},[]);const p=async h=>{o(!0);try{await Le.setPiSettings({scope:"project",trust:h},{runtimeKey:it()}),n(!1),t?.()}catch(u){const d=u instanceof Error&&u.message?u.message:"Failed to update project trust",w=d.includes("SESSION_BUSY")||u?.code==="SESSION_BUSY";F.error(w?"Project trust cannot change while a session is streaming. Wait for the response to finish and try again.":d)}finally{o(!1)}};return e.jsx(lt,{open:s,onOpenChange:()=>{},children:e.jsxs(ct,{className:"max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Trust this project?"}),e.jsx(mt,{children:"This project contains Pi settings, skills, prompts, or extensions. Trusting it allows Pi to load those project resources."})]}),e.jsxs(Ot,{children:[e.jsx(S,{variant:"ghost",size:"sm",disabled:i,onClick:()=>{p(!1)},children:"Keep untrusted"}),e.jsx(S,{size:"sm",disabled:i,onClick:()=>{p(!0)},children:"Trust project"})]})]})})},Ie=({children:t,className:s,outerClassName:n,title:i,titleLeading:o,titleAccessory:p,description:h,headerEnd:u})=>{const d=i!=null||h!=null||u!=null,w=typeof i=="string"||typeof i=="number",c=o!=null||p!=null;return e.jsx(si,{outerClassName:J("h-full",n),className:"w-full @container",children:e.jsxs("div",{className:J("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:[d&&e.jsxs("div",{className:"mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-3 pb-6",children:[e.jsxs("div",{className:"min-w-0 flex-1 basis-64 space-y-1",children:[i!=null?w?c?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o,e.jsx("h1",{className:J(La,"min-w-0 truncate"),children:i}),e.jsx("span",{className:"shrink-0",children:p})]}):e.jsx("h1",{className:La,children:i}):i:null,h!=null?typeof h=="string"||typeof h=="number"?e.jsx("p",{className:Ei,children:h}):h:null]}),e.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-3",children:u})]}),t]})})},Ss=({value:t,onChange:s,readOnly:n=!1,initialMode:i="preview",placeholder:o="Enter snippet text... Use markdown to format your snippet. It will expand as #name in the composer.",contentLabel:p="Snippet content",settingsItem:h,minHeight:u=220,hideExpandsNote:d=!1,triggerPreview:w,triggerActionLabel:c="Expands as",variableChips:g})=>{const[r,f]=a.useState(()=>n?"preview":i),y=t.trim().length>0;a.useEffect(()=>{n&&r==="write"&&f("preview")},[n,r,y]);const b=r==="write"&&!n,j=a.useRef(null),A=a.useCallback(I=>{const P=j.current?.selectionStart??t.length,E=j.current?.selectionEnd??t.length;s(t.slice(0,P)+I+t.slice(E)),requestAnimationFrame(()=>{const N=j.current;if(!N)return;N.focus();const x=P+I.length;N.setSelectionRange(x,x)})},[s,t]);return e.jsxs("div",{"data-settings-item":h,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(S,{variant:"chip",size:"xs","aria-pressed":r==="preview",onClick:()=>f("preview"),children:[e.jsx(T,{name:"eye",className:"size-3.5","aria-hidden":!0}),"Preview"]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":r==="write",disabled:n,onClick:()=>f("write"),className:J(n&&"opacity-50"),children:[e.jsx(T,{name:"edit",className:"size-3.5","aria-hidden":!0}),"Write"]})]}),n?e.jsx("span",{className:"hidden typography-micro text-muted-foreground @xl:inline",children:"Read-only"}):null]}),b?e.jsxs("div",{className:"p-0",children:[g&&g.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"}),g.map(I=>e.jsx(S,{variant:"chip",size:"xs",onClick:()=>A(I.value),"aria-label":I.hint??`Insert ${I.value}`,title:I.hint??I.value,children:e.jsx("span",{className:"font-mono",children:I.label??I.value})},I.value))]}):null,e.jsx(Mi,{ref:j,value:t,onChange:I=>s(I.target.value),placeholder:o,simple:!0,fillContainer:!1,outerClassName:"border-0 ring-0 rounded-none bg-transparent",className:J("min-h-[220px] w-full bg-transparent px-3 py-3 font-mono typography-meta leading-6","placeholder:text-muted-foreground/70"),style:{minHeight:u},"aria-label":p})]}):e.jsx("div",{className:"min-h-[220px] px-4 py-4 @xl:px-6",style:{minHeight:u},children:y?e.jsx(la,{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(T,{name:"file-text",className:"size-6 text-muted-foreground/50","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:n?"No content":"Nothing to preview"}),n?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Start writing in the Write tab to see a live preview."})]})}),n?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:[!d&&w?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(T,{name:"information",className:"size-3.5 shrink-0 opacity-60","aria-hidden":!0}),c," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:w})," in the composer"]}):e.jsx("span",{}),e.jsxs("span",{className:"tabular-nums",children:[t.length," chars"]})]})]})},Xi=()=>{const{isMobile:t}=Ve(),[s,n]=a.useState(null),[i,o]=a.useState({}),[p,h]=a.useState(null),[u,d]=a.useState(!1),w=a.useCallback(async()=>{const g=await Le.listResources({runtimeKey:it()});n(g.agents),o(Object.fromEntries(g.agents.map(r=>[r.id,r.content??""]))),d(!1)},[]);a.useEffect(()=>{w().catch(()=>d(!0))},[w]);const c=async g=>{h(g.id);try{const r=await Le.updateResource({resourceId:g.id,content:i[g.id]??""},{runtimeKey:it()});n(r.agents),o(Object.fromEntries(r.agents.map(f=>[f.id,f.content??""]))),F.success("Behavior saved successfully")}catch{F.error("Failed to save behavior")}finally{h(null)}};return e.jsxs(e.Fragment,{children:[e.jsx(Yi,{onResolved:()=>{w().catch(()=>d(!0))}}),e.jsxs(Ie,{title:t?void 0:"Behavior",description:t?void 0:"Guide how the agent responds.",children:[u?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,(s??[]).map((g,r)=>{const f=i[g.id]??"",y=g.location==="global"?"Global AGENTS.md":`Project ${g.name}`,b=g.editable===!0,j=f!==(g.content??"");return e.jsxs(te,{title:y,divider:r>0,settingsItem:g.location==="global"?"behavior.global-agents":"behavior.project-agents",contentClassName:"space-y-3",info:b?"Markdown supported. Changes apply to new sessions.":"Read-only — this file is managed by a package or template.",children:[e.jsx(Ss,{value:f,onChange:A=>o(I=>({...I,[g.id]:A})),readOnly:!b,placeholder:b?"Describe how the agent should behave. Use markdown for structure.":void 0,settingsItem:g.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:j?"Unsaved changes":"No changes"}),e.jsx(S,{size:"xs",onClick:()=>{c(g)},disabled:p!==null||!j,children:p===g.id?"Saving...":"Save Changes"})]}):null]},g.id)})]})]})},Zi=({skill:t,onSelect:s,showLocationPill:n=!0})=>{const i=t.location==="project"?"Project":t.location==="global"?"Global":t.location,o=t.description?.trim()||"No description";return e.jsxs("button",{type:"button",onClick:()=>s(t.name),"aria-label":`${t.name} skill, ${i}`,className:J("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:[n?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:J("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:i})}):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:o})]})]})},eo=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>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"})]})]},n))}),to=()=>{const{isMobile:t}=Ve(),s=kt(k=>k.selectedSkillName),n=kt(k=>k.setSelectedSkill),i=kt(k=>k.skills),o=kt(k=>k.isLoading),p=kt(k=>k.loadSkills),[h,u]=a.useState(""),[d,w]=a.useState("all"),[c,g]=a.useState(!1),r=a.useMemo(()=>i.find(k=>k.name===s)??null,[i,s]),f=kt(k=>k.updateSkillContent),[y,b]=a.useState(!1),[j,A]=a.useState(""),[I,P]=a.useState(!1);a.useEffect(()=>{r&&A(r.content??""),b(!1)},[r?.id,r?.content]);const E=a.useCallback(async()=>{if(!c){g(!0);try{const{invalidateSkillsLoadCache:k}=await Zt(async()=>{const{invalidateSkillsLoadCache:m}=await import("./useAppFontEffects-CYzYRbLp.js").then(v=>v.dD);return{invalidateSkillsLoadCache:m}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78]));k(),await p()}finally{g(!1)}}},[p,c]);a.useEffect(()=>{p()},[p]);const N=a.useMemo(()=>[...i].sort((k,m)=>{if(k.location!==m.location){if(k.location==="project")return-1;if(m.location==="project")return 1;if(k.location==="global")return-1;if(m.location==="global")return 1}return k.name.localeCompare(m.name,void 0,{sensitivity:"base"})}),[i]),x=a.useMemo(()=>{let k=N;d!=="all"&&(k=k.filter(v=>v.location===d));const m=h.trim().toLowerCase();return m?k.filter(v=>{const C=v.name.toLowerCase(),L=(v.description??"").toLowerCase();return C.includes(m)||L.includes(m)}):k},[N,d,h]),D=a.useMemo(()=>{let k=0,m=0;for(const v of i)v.location==="project"?k+=1:v.location==="global"&&(m+=1);return{all:i.length,project:k,global:m}},[i]);if(r){const k=r.location==="project"?"Project":r.location==="global"?"Global":r.location,m=typeof r.content=="string"&&r.content.trim().length>0,v=r.editable===!0,C=j!==(r.content??""),L=async()=>{if(!v||I)return;P(!0);const q=await f(r.name,j);P(!1),q?(F.success("Skill saved"),b(!1)):F.error("Failed to save skill")},B=()=>{A(r.content??""),b(!1)};return e.jsx(e.Fragment,{children:e.jsxs(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>n(null),"aria-label":"Back to skills",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:r.name})]}),description:r.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:r.description}):void 0,headerEnd:v&&!y?e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>b(!0),children:[e.jsx(T,{name:"edit",className:"size-3.5"}),"Edit"]}):void 0,children:[e.jsxs(te,{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:k}),v?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(T,{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"]})]}),v?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(te,{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:v&&y?e.jsx("span",{className:"typography-micro text-muted-foreground",children:C?"Unsaved changes":"No changes"}):void 0,children:[y?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{value:j,onChange:A,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(S,{variant:"ghost",size:"xs",onClick:B,disabled:I,children:"Cancel"}),e.jsx(S,{size:"xs",onClick:()=>{L()},disabled:I||!C,children:I?"Saving...":"Save Changes"})]})]}):m?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(la,{content:r.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(T,{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."}),v?e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>b(!0),className:"mt-2",children:[e.jsx(T,{name:"edit",className:"size-3.5"}),"Add content"]}):null]}),v&&!y&&m?e.jsx("div",{className:"flex justify-end pt-3",children:e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>b(!0),children:[e.jsx(T,{name:"edit",className:"size-3.5"}),"Edit"]})}):null]})]})})}return o&&i.length===0?e.jsx(e.Fragment,{children:e.jsx(Ie,{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 items-center gap-2",children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:c,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(T,{name:"refresh",className:J("size-4",c&&"animate-spin")})})}),children:e.jsx(te,{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(eo,{count:6})})})})}):x.length===0&&h.trim()===""&&i.length===0?e.jsx(e.Fragment,{children:e.jsx(Ie,{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",children:[e.jsx(T,{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(ie,{value:h,onChange:k=>u(k.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),h?e.jsx("button",{type:"button",onClick:()=>u(""),"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(T,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:c,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(T,{name:"refresh",className:J("size-4",c&&"animate-spin")})})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(T,{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(Ie,{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",children:[e.jsx(T,{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(ie,{value:h,onChange:k=>u(k.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),h?e.jsx("button",{type:"button",onClick:()=>u(""),"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(T,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:c,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(T,{name:"refresh",className:J("size-4",c&&"animate-spin")})})]}),children:e.jsxs(te,{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(S,{variant:"chip",size:"xs","aria-pressed":d==="all",onClick:()=>w("all"),children:["All ",D.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="project",onClick:()=>w("project"),children:["Project ",D.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="global",onClick:()=>w("global"),children:["Global ",D.global]})]}),x.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:h.trim()?`No skills match “${h}”.`:`No ${d} skills.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{u(""),w("all")},children:"Clear filters"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:x.map(k=>e.jsx(Zi,{skill:k,onSelect:n,showLocationPill:d==="all"},k.id))})]})})})},so=({project:t,onSelect:s})=>{const n=t.label?.trim()||t.path.split("/").pop()?.trim()||t.path,i=!!t.label?.trim();return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${n} project, ${t.path}`,className:J("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("span",{className:"inline-flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground",children:e.jsx(T,{name:"folder",className:"size-4","aria-hidden":!0})})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:n}),i?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})]})]})},ao=()=>{const{isMobile:t}=Ve(),s=bs(r=>r.projects),n=bs(r=>r.updateProjectMeta),i=_(r=>r.settingsProjectsSelectedId),o=_(r=>r.setSettingsProjectsSelectedId),[p,h]=a.useState(""),u=a.useCallback(()=>{ai.requestDirectoryDialog()},[]),d=a.useMemo(()=>i?s.find(r=>r.id===i)??null:null,[s,i]);a.useEffect(()=>{i&&!s.some(r=>r.id===i)&&o(null)},[s,i,o]);const w=a.useCallback(async r=>{d&&n(d.id,{label:r.label,defaultModel:r.defaultModel??null})},[d,n]),c=a.useMemo(()=>[...s].sort((r,f)=>{const y=(r.label?.trim()||r.path).toLowerCase(),b=(f.label?.trim()||f.path).toLowerCase();return y.localeCompare(b,void 0,{sensitivity:"base"})}),[s]),g=a.useMemo(()=>{const r=p.trim().toLowerCase();return r?c.filter(f=>{const y=(f.label??"").toLowerCase(),b=f.path.toLowerCase();return y.includes(r)||b.includes(r)}):c},[c,p]);if(d){const r=d.label?.trim()||d.path.split("/").pop()?.trim()||d.path;return e.jsx(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>o(null),"aria-label":"Back to projects",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{name:"arrow-left-s",className:"size-4"})}),e.jsx(T,{name:"folder",className:"size-5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"truncate",children:r})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:d.path}),children:e.jsx(Ai,{project:d,onIdentitySave:w})})}return s.length===0?e.jsx(Ie,{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(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(T,{name:"add",className:"size-4"}),"Add project"]}),children:e.jsx(te,{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(T,{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(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(T,{name:"add",className:"size-4"}),"Add project"]})]})})}):e.jsx(Ie,{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",children:[e.jsx(T,{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(ie,{value:p,onChange:r=>h(r.target.value),placeholder:"Search projects","aria-label":"Search projects",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),p?e.jsx("button",{type:"button",onClick:()=>h(""),"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(T,{name:"close",className:"size-4"})}):null]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(T,{name:"add",className:"size-4"}),"Add project"]})]}),children:e.jsx(te,{title:"Projects",divider:!1,settingsItem:"projects.browse",children:g.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 “",p,"”."]}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>h(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[g.map(r=>e.jsx(so,{project:r,onSelect:o},r.id)),e.jsxs("button",{type:"button",onClick:u,"aria-label":"Add project",className:J("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(T,{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"})]})]})})})},no=()=>{if(typeof navigator>"u")return;const t=(navigator.userAgent||"").toLowerCase();if(t.includes("mac"))return"macos";if(t.includes("win"))return"windows";if(t.includes("linux"))return"linux"},Ua=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}},da=(t="",s="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:t,value:s}),ro=t=>t.trim().toLowerCase()==="authorization",Js=t=>{const s={};for(const n of t){const i=n.name.trim(),o=n.value.trim();i&&o&&!ro(i)&&(s[i]=o)}return Object.keys(s).length>0?s:void 0},io=t=>Object.entries(t||{}).map(([s,n])=>da(s,n)),jn=()=>{if(typeof window>"u")return null;const s=Ut()||window.location.href;try{const n=Number(new URL(s).port||window.location.port);return Number.isFinite(n)&&n>0?n:null}catch{const n=Number(window.location.port);return Number.isFinite(n)&&n>0?n:null}},Fa=t=>{try{const s=new URL(t).hostname.toLowerCase();return s==="localhost"||s==="127.0.0.1"||s==="::1"||s==="[::1]"}catch{return!1}},oo=async()=>{const t=zt(Ut())||window.location.origin;if(!Re()||!es())return t;let s;try{s=await Be("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}})}catch{return t}if(!s.ok||(await s.json().catch(()=>null))?.desktopLanAccessActive!==!0)return t;const i=await tn(),o=jn();return!i||!o?t:`http://${i}:${o}`},Ba=t=>{const s=t.trim();if(s)try{window.location.assign(s)}catch{window.location.href=s}},lo=({open:t,onOpenChange:s,phase:n,remoteClientLabel:i,onRemoteClientLabelChange:o,remoteClientError:p,addDeviceTransport:h,onAddDeviceTransportChange:u,addDeviceFallback:d,onAddDeviceFallbackChange:w,transportOptions:c,addDeviceCreating:g,onCreatePairingLink:r,pairingQrDataUrl:f,pairingUrl:y,pairingCopied:b,onCopyPairing:j})=>e.jsx(lt,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:n==="result"?"sm:max-w-lg":"sm:max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:n==="result"?"Scan to connect":"Add a device"}),e.jsx(mt,{children:n==="result"?"Scan this with the PiChamber app on your other device. It is single-use and expires.":"Create a one-time QR code that connects another device to this server."})]}),n==="configure"?e.jsxs("form",{className:"space-y-4",onSubmit:A=>{A.preventDefault(),r()},children:[e.jsx(ie,{className:"h-8",value:i,onChange:A=>o(A.target.value),placeholder:"Device name — e.g. My iPhone",autoFocus:!0}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:"Where will you use this device?"}),e.jsx("div",{role:"radiogroup","aria-label":"Where will you use this device?",className:"space-y-1.5",children:[{key:"relay",label:"Anywhere",hint:"Works at home and away. Away traffic goes through PiChamber Private Relay — an end-to-end encrypted tunnel. No setup needed.",available:!!c?.relayAvailable},{key:"lan",label:"Home network only",hint:"Connects directly over your Wi-Fi. Does not work away from this network.",available:!!c?.lanUrl},{key:"local",label:"This computer only",hint:"For apps running on this same machine.",available:!!c?.localUrl}].map(A=>{const I=h===A.key;return e.jsxs("div",{className:J("flex items-start gap-2 py-0.5",A.available?"cursor-pointer":"opacity-45"),onClick:()=>{A.available&&u(A.key)},role:"presentation",children:[e.jsx(fn,{checked:I,disabled:!A.available,onChange:()=>u(A.key),ariaLabel:A.label,className:"mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:J("typography-ui-label font-normal",I?"text-foreground":"text-foreground/70"),children:A.label}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:A.hint})]})]},A.key)})}),h==="lan"?e.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[e.jsx(Ma,{checked:d,onChange:w,ariaLabel:"Also allow the encrypted relay when away from home"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Also allow the encrypted relay when away from home"})]}):null,h==="relay"&&c?.lanUrl?e.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[e.jsx(Ma,{checked:d,onChange:w,ariaLabel:"Prefer the direct home connection when available"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Prefer the direct home connection when available"})]}):null]}),p?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:p}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:g,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:g||!c,children:"Create QR code"})]})]}):e.jsxs("div",{className:"space-y-3",children:[f?e.jsx("div",{className:"flex justify-center",children:e.jsx("img",{src:f,alt:"PiChamber connection QR code",className:"w-full max-w-[420px] rounded-md bg-white p-4"})}):null,y?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:y}),e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:j,children:[e.jsx(T,{name:b?"check":"file-copy",className:J("h-3.5 w-3.5",b&&"text-[var(--status-success)]")}),b?"Copied":"Copy all"]})]}):null,e.jsx("div",{className:"flex justify-end",children:e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:()=>s(!1),children:"Done"})})]})]})}),co=({open:t,onOpenChange:s,label:n,onLabelChange:i,url:o,onUrlChange:p,token:h,onTokenChange:u,headers:d,onHeadersChange:w,saving:c,onAdd:g})=>e.jsx(lt,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Add Server"}),e.jsx(mt,{children:"Add another PiChamber server by URL. Use this when the server is already running and you have a connection token."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:r=>{r.preventDefault(),g()},children:[e.jsx(ie,{className:"h-8",value:n,onChange:r=>i(r.target.value),placeholder:"Label (optional)",disabled:c}),e.jsx(ie,{className:"h-8",value:o,onChange:r=>p(r.target.value),placeholder:"https://host:port",disabled:c,autoFocus:!0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ie,{className:"h-8",value:h,onChange:r=>u(r.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:c}),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("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cs,{children:"Additional headers"}),e.jsx(vt,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),d.map(r=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ie,{className:"h-8 font-mono text-xs",value:r.name,onChange:f=>w(y=>y.map(b=>b.id===r.id?{...b,name:f.target.value}:b)),placeholder:"Header name",disabled:c}),e.jsx(ie,{className:"h-8 font-mono text-xs",value:r.value,onChange:f=>w(y=>y.map(b=>b.id===r.id?{...b,value:f.target.value}:b)),placeholder:"Header value",type:"password",disabled:c}),e.jsx("button",{type:"button",onClick:()=>w(f=>f.filter(y=>y.id!==r.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:c,children:e.jsx(T,{name:"close",className:"h-4 w-4"})})]},r.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>w(r=>[...r,da()]),disabled:c,children:[e.jsx(T,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:c,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:c||!o.trim(),children:"Add Server"})]})]})]})}),uo=({open:t,onOpenChange:s,label:n,onLabelChange:i,url:o,onUrlChange:p,token:h,onTokenChange:u,headers:d,onHeadersChange:w,saving:c,onSave:g})=>e.jsx(lt,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Edit"}),e.jsx(mt,{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:r=>{r.preventDefault(),g()},children:[e.jsx(ie,{className:"h-8",value:n,onChange:r=>i(r.target.value),placeholder:"Label (optional)",disabled:c}),e.jsx(ie,{className:"h-8",value:o,onChange:r=>p(r.target.value),placeholder:"https://host:port",disabled:c,autoFocus:!0}),e.jsx(ie,{className:"h-8",value:h,onChange:r=>u(r.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:c}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cs,{children:"Additional headers"}),e.jsx(vt,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),d.map(r=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ie,{className:"h-8 font-mono text-xs",value:r.name,onChange:f=>w(y=>y.map(b=>b.id===r.id?{...b,name:f.target.value}:b)),placeholder:"Header name",disabled:c}),e.jsx(ie,{className:"h-8 font-mono text-xs",value:r.value,onChange:f=>w(y=>y.map(b=>b.id===r.id?{...b,value:f.target.value}:b)),placeholder:"Header value",type:"password",disabled:c}),e.jsx("button",{type:"button",onClick:()=>w(f=>f.filter(y=>y.id!==r.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:c,children:e.jsx(T,{name:"close",className:"h-4 w-4"})})]},r.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>w(r=>[...r,da()]),disabled:c,children:[e.jsx(T,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:c,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:c,children:"Save Changes"})]})]})]})}),mo=({open:t,onOpenChange:s,link:n,onLinkChange:i,saving:o,onImport:p})=>e.jsx(lt,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"sm:max-w-lg",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Import Link"}),e.jsx(mt,{children:"Paste a connection link from another PiChamber server."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:h=>{h.preventDefault(),p()},children:[e.jsx(ie,{className:"h-8",value:n,onChange:h=>i(h.target.value),placeholder:"pichamber://connect?...",disabled:o,autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:o,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:o||!n.trim(),children:"Import Link"})]})]})]})});function po(t){const[s,n]=a.useState([]),[i,o]=a.useState({}),[p,h]=a.useState("local"),[u,d]=a.useState(!1),[w,c]=a.useState(!1),[g,r]=a.useState(""),[f,y]=a.useState(""),[b,j]=a.useState(""),[A,I]=a.useState([]),[P,E]=a.useState(""),[N,x]=a.useState(null),[D,k]=a.useState(!1),[m,v]=a.useState(!1),[C,L]=a.useState(null),[B,q]=a.useState(""),[Y,$]=a.useState(""),[V,oe]=a.useState(""),[xe,je]=a.useState([]),z=a.useCallback(async()=>{d(!0),x(null);try{const K=await sn();n(K.hosts||[]),h(K.defaultHostId||"local")}catch(K){x(K instanceof Error?K.message:String(K))}finally{d(!1)}},[]);a.useEffect(()=>{z()},[z]);const O=a.useCallback(async(K,re=p)=>{c(!0),x(null);try{await an({hosts:K,defaultHostId:re,initialHostChoiceCompleted:!0}),n(K),h(re)}catch(fe){x(fe instanceof Error?fe.message:String(fe))}finally{c(!1)}},[p]),X=a.useCallback(async()=>{const K=ja(f);if(!K){x("Invalid URL (must be http/https)");return}const re=K.persistedUrl,be={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:g.trim()||Jt(re),url:re,apiUrl:re,...b.trim()?{clientToken:b.trim()}:{},...Js(A)?{requestHeaders:Js(A)}:{}};await O([be,...s],p),r(""),y(""),j(""),I([]),k(!1),K.redeemUrl&&Ba(K.redeemUrl)},[p,A,s,g,b,f,O]),H=a.useCallback(async()=>{const K=wr(P);if(!K){x("Invalid PiChamber connection link.");return}const re=await kr().catch(()=>""),fe=JSON.stringify({pairingId:K.pairingId,secret:K.secret,clientLabel:K.label||"PiChamber Desktop",clientKind:"desktop",deviceName:"PiChamber Desktop",devicePlatform:no(),...re?{dedupeKey:`desktop:${re}`}:{}}),be={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:fe},pe=async me=>{if(!me.ok)return null;const Pe=await me.json().catch(()=>null);return(typeof Pe?.clientToken=="string"?Pe.clientToken.trim():"")||null},Q=[...K.candidates].sort((me,Pe)=>(me.type==="relay"?1:0)-(Pe.type==="relay"?1:0));let U=null;for(const me of Q){if(me.type==="relay"){const Je=Nr({relayUrl:me.relayUrl,serverId:me.serverId,hostEncPubJwk:me.hostEncPubJwk,...me.grant?{grant:me.grant}:{}});try{const Ye=await Je.fetch("/api/client-auth/pairing/redeem",be),he=await pe(Ye);if(he){U={kind:"relay",relay:{relayUrl:me.relayUrl,serverId:me.serverId,hostEncPubJwk:me.hostEncPubJwk},token:he};break}}catch{}finally{Je.close()}continue}const Pe=zt(me.url);if(Pe)try{const Je=await fetch(`${Pe}/api/client-auth/pairing/redeem`,be),Ye=await pe(Je);if(Ye){U={kind:"direct",url:Pe,token:Ye};break}}catch{}}if(!U){x("Invalid URL (must be http/https)");return}const ae=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,R=K.candidates.find(me=>me.type==="relay"),Z=U.kind==="relay"?U.relay:R?{relayUrl:R.relayUrl,serverId:R.serverId,hostEncPubJwk:R.hostEncPubJwk}:void 0,le=K.candidates.filter(me=>me.type!=="relay").map(me=>zt(me.url)).find(me=>!!me),ce=U.kind==="direct"?U.url:le,{token:G}=U,ne=ce||(Z?Cr(Z.serverId):null);if(!ne){x("Invalid URL (must be http/https)");return}const de={url:ne,apiUrl:ce||void 0,clientToken:G,...Z?{relay:Z}:{}},Ne=s.find(me=>Z?me.relay?.serverId===Z.serverId:!me.relay&&zt(me.apiUrl||me.url)===ne);if(Ne){const me=s.map(Pe=>Pe.id===Ne.id?{...Pe,label:K.label||Pe.label,...de}:Pe);await O(me,p)}else await O([{id:ae(),label:K.label||Jt(ne),...de},...s],p);E(""),x(null),v(!1)},[P,p,s,O]),M=a.useCallback(async K=>{const re=s.filter(be=>be.id!==K);await O(re,p===K?"local":p),C===K&&L(null)},[p,C,s,O]),W=a.useCallback(K=>{L(K.id),q(K.label),$(K.apiUrl||K.url),oe(K.clientToken||""),je(io(K.requestHeaders)),x(null)},[]),se=a.useCallback(async()=>{if(!C)return;const K=ja(Y);if(!K){x("Invalid URL (must be http/https)");return}const re=K.persistedUrl,fe=s.map(be=>be.id===C?{...be,label:B.trim()||Jt(re),url:re,apiUrl:re,clientToken:V.trim()||void 0,requestHeaders:Js(xe)}:be);await O(fe,p),L(null),K.redeemUrl&&Ba(K.redeemUrl)},[p,xe,B,V,Y,C,s,O]),ye=a.useCallback(async K=>{await O(s,K)},[s,O]);return a.useEffect(()=>{if(!t||s.length===0)return;let K=!1;return Promise.all(s.map(async re=>{const fe=()=>Tr(re.relay,{clientToken:re.clientToken||null,requestHeaders:re.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(re.relay&&!re.apiUrl)return[re.id,await fe()];const be=zt(Sr(re));if(!be)return[re.id,re.relay?await fe():{status:"unreachable",latencyMs:0}];const pe=await Pr(be,{clientToken:re.clientToken||null,requestHeaders:re.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(pe.status==="unreachable"&&re.relay){const Q=await fe();if(Q.status==="ok")return[re.id,Q]}return[re.id,pe]})).then(re=>{K||o(Object.fromEntries(re))}),()=>{K=!0}},[s,t]),{directHosts:s,directHostStatus:i,directDefaultHostId:p,directLoading:u,directSaving:w,directLabel:g,setDirectLabel:r,directUrl:f,setDirectUrl:y,directToken:b,setDirectToken:j,directHeaders:A,setDirectHeaders:I,directConnectLink:P,setDirectConnectLink:E,directError:N,directAddDialogOpen:D,setDirectAddDialogOpen:k,directImportDialogOpen:m,setDirectImportDialogOpen:v,directEditingId:C,setDirectEditingId:L,directEditLabel:B,setDirectEditLabel:q,directEditUrl:Y,setDirectEditUrl:$,directEditToken:V,setDirectEditToken:oe,directEditHeaders:xe,setDirectEditHeaders:je,handleAddDirectHost:X,importDirectConnectLink:H,handleRemoveDirectHost:M,beginEditDirectHost:W,saveDirectHostEdit:se,setDefaultDirectHost:ye}}function ho(t){const[s,n]=a.useState([]),[i,o]=a.useState([]),[p,h]=a.useState(!1),[u,d]=a.useState(""),[w,c]=a.useState(null),[g,r]=a.useState(null),[f,y]=a.useState(null),[b,j]=a.useState(null),[A,I]=a.useState(!1),[P,E]=a.useState(!1),[N,x]=a.useState("configure"),[D,k]=a.useState(!1),[m,v]=a.useState("relay"),[C,L]=a.useState(!0),[B,q]=a.useState(null),Y=a.useMemo(()=>s.filter(M=>!!M.revokedAt).length,[s]),$=a.useCallback(async M=>{if(t){M?.silent||h(!0),M?.silent||c(null);try{const[W,se]=await Promise.all([t.listClients(),t.listPendingPairings().catch(()=>null)]);n(W),se&&o(se)}catch(W){M?.silent||c(W instanceof Error?W.message:String(W))}finally{M?.silent||h(!1)}}},[t]),V=a.useRef(!1);a.useEffect(()=>{if(!(!P||N!=="result"||!f)){if(i.some(M=>M.id===f)){V.current=!0;return}V.current&&(y(null),E(!1),s.some(M=>M.pairingId===f)&&F.success("Device connected."))}},[P,N,f,i,s]);const oe=a.useCallback(async M=>{if(t)try{await t.cancelPairing(M),o(W=>W.filter(se=>se.id!==M)),await $({silent:!0})}catch(W){c(W instanceof Error?W.message:String(W))}},[t,$]);a.useEffect(()=>{if(!t)return;$();const M=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||$({silent:!0})},5e3);return()=>window.clearInterval(M)},[t,$]);const xe=a.useCallback(async()=>{if(t?.getPairingTransports)try{const ye=await t.getPairingTransports();return{localUrl:ye.local,lanUrl:ye.lan,relayAvailable:ye.relayAvailable}}catch{}const M=jn(),W=M?`http://127.0.0.1:${M}`:Fa(window.location.origin)?window.location.origin:null;let se=null;try{const ye=zt(await oo());se=ye&&!Fa(ye)?ye:null}catch{}return{localUrl:W,lanUrl:se,relayAvailable:!0}},[t]),je=a.useCallback(async()=>{c(null),r(null),j(null),I(!1),y(null),x("configure"),L(!0),E(!0);const M=await xe();q(M),v(M.relayAvailable?"relay":M.lanUrl?"lan":"local")},[xe]),z=a.useCallback(async()=>{if(!(!t?.createPairingSession||!B)){c(null),k(!0);try{const M=u.trim()||void 0;let W,se,ye=!0;m==="local"?(W=B.localUrl??void 0,se=!1):m==="lan"?(W=B.lanUrl??void 0,se=C):C&&B.lanUrl?(W=B.lanUrl,se=!0):(ye=!1,se=!0);const{pairing:K,server:re}=await t.createPairingSession({label:M,allowedClientKinds:["mobile","desktop"],serverUrl:W,includeRelay:se,includeDirect:ye}),fe=Ir({pairingId:K.id,secret:K.secret,label:re.label,fingerprint:K.fingerprint??void 0,expiresAt:K.expiresAt,candidates:re.candidates}),be=Er(fe);r(be),j(await bn.toDataURL(be,{width:1024,margin:2,errorCorrectionLevel:"L"})),I(!1),V.current=!1,y(K.id),x("result"),await $({silent:!0})}catch(M){c(M instanceof Error?M.message:String(M))}finally{k(!1)}}},[t,B,m,C,u,$]),O=a.useCallback(()=>{g&&ni(g).then(M=>{M.ok&&(I(!0),window.setTimeout(()=>I(!1),2e3))})},[g]),X=a.useCallback(async M=>{if(!t)return;const W=M.clientKind==="desktop-local";c(null);try{if(await t.revokeClient(M.id),W&&Re()){const se=await sn();await an({hosts:se.hosts,defaultHostId:se.defaultHostId,initialHostChoiceCompleted:se.initialHostChoiceCompleted,localClientToken:null}),n(ye=>ye.map(K=>K.id===M.id?{...K,revokedAt:new Date().toISOString()}:K)),Mr({apiBaseUrl:Ut(),clientToken:null,runtimeKey:"local"});return}await $()}catch(se){c(se instanceof Error?se.message:String(se))}},[t,$]),H=a.useCallback(async()=>{if(t){c(null);try{await t.purgeRevokedClients(),await $()}catch(M){c(M instanceof Error?M.message:String(M))}}},[t,$]);return{remoteClients:s,pendingPairings:i,remoteClientsLoading:p,remoteClientLabel:u,setRemoteClientLabel:d,remoteClientError:w,pairingUrl:g,pairingQrDataUrl:b,pairingCopied:A,addDeviceOpen:P,setAddDeviceOpen:E,addDevicePhase:N,addDeviceCreating:D,addDeviceTransport:m,setAddDeviceTransport:v,addDeviceFallback:C,setAddDeviceFallback:L,transportOptions:B,revokedClientCount:Y,openAddDevice:je,createPairingLink:z,handleCopyPairing:O,revokeRemoteClient:X,purgeRevokedRemoteClients:H,cancelPendingPairing:oe}}const go=()=>{const{isMobile:t}=Ve(),s=_(he=>he.timeFormatPreference),{clientAuth:n}=ln(),i=Re(),{directHosts:o,directHostStatus:p,directDefaultHostId:h,directLoading:u,directSaving:d,directLabel:w,setDirectLabel:c,directUrl:g,setDirectUrl:r,directToken:f,setDirectToken:y,directHeaders:b,setDirectHeaders:j,directConnectLink:A,setDirectConnectLink:I,directError:P,directAddDialogOpen:E,setDirectAddDialogOpen:N,directImportDialogOpen:x,setDirectImportDialogOpen:D,directEditingId:k,setDirectEditingId:m,directEditLabel:v,setDirectEditLabel:C,directEditUrl:L,setDirectEditUrl:B,directEditToken:q,setDirectEditToken:Y,directEditHeaders:$,setDirectEditHeaders:V,handleAddDirectHost:oe,importDirectConnectLink:xe,handleRemoveDirectHost:je,beginEditDirectHost:z,saveDirectHostEdit:O,setDefaultDirectHost:X}=po(i),{remoteClients:H,pendingPairings:M,remoteClientsLoading:W,remoteClientLabel:se,setRemoteClientLabel:ye,remoteClientError:K,pairingUrl:re,pairingQrDataUrl:fe,pairingCopied:be,addDeviceOpen:pe,setAddDeviceOpen:Q,addDevicePhase:U,addDeviceCreating:ae,addDeviceTransport:R,setAddDeviceTransport:Z,addDeviceFallback:le,setAddDeviceFallback:ce,transportOptions:G,revokedClientCount:ne,openAddDevice:de,createPairingLink:Ne,handleCopyPairing:me,revokeRemoteClient:Pe,purgeRevokedRemoteClients:Je,cancelPendingPairing:Ye}=ho(n);return e.jsxs(Ie,{title:t?void 0:"Remote Instances",children:[n?e.jsxs(te,{title:"Connect to this server",info:"Create a secure link or token so PiChamber Desktop can connect to this server.",divider:!1,settingsItem:"remote-instances.client-auth",contentClassName:"space-y-3",children:[e.jsx("div",{children:e.jsxs(S,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{de()},children:[e.jsx(T,{name:"add",className:"h-3.5 w-3.5"}),"Add a device"]})}),e.jsxs("div",{className:"space-y-2.5",children:[ne>0?e.jsx("div",{className:"flex justify-end",children:e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Je()},children:"Clear revoked"})}):null,W&&H.length===0&&M.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading tokens..."}):H.length===0&&M.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No devices connected yet."}):e.jsxs(e.Fragment,{children:[M.map(he=>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"}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:he.label||"Device name — e.g. My iPhone"}),he.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(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Ye(he.id)},children:"Cancel"})]},`pending-${he.id}`)),H.map(he=>{const De=he.clientKind==="desktop-local",st=he.lastUsedAt?Date.parse(he.lastUsedAt):Number.NaN,qe=!he.revokedAt&&(De||Number.isFinite(st)&&Date.now()-st<9e4),jt=he.revokedAt?"Revoked":qe?he.lastTransport==="relay"&&!De?"Connected · Relay":"Connected · Local network":Number.isFinite(st)?`Last used ${ri(st,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",{className:J("h-2 w-2 shrink-0 rounded-full",he.revokedAt?"bg-muted-foreground/20":qe?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:he.label}),Ua(he.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:Ua(he.devicePlatform)}):null,De?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:J("typography-micro truncate",qe&&!he.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:jt})]})}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Pe(he)},disabled:!!he.revokedAt,children:"Revoke"})]},he.id)})]})]}),K?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:K}):null]}):null,i?e.jsxs(te,{title:"Other PiChamber servers",info:"Servers this app can switch to. Import a pairing link from the other server, or add one by address.",settingsItem:"remote-instances.direct-hosts",contentClassName:"space-y-4",headerAction:e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:()=>D(!0),disabled:d,children:"Import Link"}),e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>N(!0),disabled:d,children:[e.jsx(T,{name:"add",className:"h-3.5 w-3.5"}),"Add Server"]})]}),children:[e.jsx("div",{className:"space-y-2.5",children:u?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading instances..."}):o.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No other servers added yet."}):o.map(he=>{const De=p[he.id],st=De?De.status==="ok"?"Connected":De.status==="auth"?"Auth required":De.status==="update-recommended"?"Update recommended":De.status==="incompatible"?"Incompatible":De.status==="wrong-service"?"Wrong service":"Unreachable":"Checking",qe=De?.status==="ok";return e.jsx("div",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",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:J("h-2 w-2 shrink-0 rounded-full",De?qe?"bg-[var(--status-success)]":"bg-[var(--status-error)]":"bg-muted-foreground/30 animate-pulse")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:Jt(he.label)}),h===he.id?e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"Default"}):null,e.jsxs("span",{className:J("typography-micro shrink-0",qe?"text-[var(--status-success)]":"text-muted-foreground"),children:[st,qe&&typeof De?.latencyMs=="number"?` · ${Math.max(0,Math.round(De.latencyMs))}ms ping`:""]})]}),e.jsx("p",{className:J("typography-micro text-muted-foreground truncate",he.apiUrl&&"font-mono"),children:he.relay&&!he.apiUrl?"via PiChamber Relay":Jt(he.apiUrl||he.url)})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{X(he.id)},disabled:d||h===he.id,"aria-label":"Set as default",children:h===he.id?e.jsx(T,{name:"star-fill",className:"h-3.5 w-3.5"}):e.jsx(T,{name:"star",className:"h-3.5 w-3.5"})}),he.relay&&!he.apiUrl?null:e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>z(he),disabled:d,children:[e.jsx(T,{name:"pencil",className:"h-3.5 w-3.5"}),"Edit"]}),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{je(he.id)},disabled:d,children:[e.jsx(T,{name:"delete-bin",className:"h-3.5 w-3.5"}),"Delete"]})]})]})},he.id)})}),P?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:P}):null]}):null,i?e.jsxs(e.Fragment,{children:[e.jsx(co,{open:E,onOpenChange:N,label:w,onLabelChange:c,url:g,onUrlChange:r,token:f,onTokenChange:y,headers:b,onHeadersChange:j,saving:d,onAdd:oe}),e.jsx(uo,{open:!!k,onOpenChange:he=>{he||m(null)},label:v,onLabelChange:C,url:L,onUrlChange:B,token:q,onTokenChange:Y,headers:$,onHeadersChange:V,saving:d,onSave:O}),e.jsx(mo,{open:x,onOpenChange:D,link:A,onLinkChange:I,saving:d,onImport:xe})]}):null,e.jsx(lo,{open:pe,onOpenChange:Q,phase:U,remoteClientLabel:se,onRemoteClientLabelChange:ye,remoteClientError:K,addDeviceTransport:R,onAddDeviceTransportChange:Z,addDeviceFallback:le,onAddDeviceFallbackChange:ce,transportOptions:G,addDeviceCreating:ae,onCreatePairingLink:Ne,pairingQrDataUrl:fe,pairingUrl:re,pairingCopied:be,onCopyPairing:me})]})},fo="@ai-sdk/openai-compatible",xo=/^[a-z0-9][a-z0-9-_]*$/,bo=/^https?:\/\//,vo=/^\{env:([^}]+)\}$/;let yo=0;const ks=()=>`row-${yo++}`,ua=()=>({row:ks(),id:"",name:""}),ma=()=>({row:ks(),key:"",value:""}),jo=()=>({providerID:"",name:"",baseURL:"",apiKey:"",models:[ua()],headers:[ma()]});function wo(t){const s=t.trim();if(!s)return{};const i=s.match(vo)?.[1]?.trim();return i?{env:i}:{key:s}}function ko(t){const s=t.options&&typeof t.options=="object"?t.options:{},n=typeof s.baseURL=="string"?s.baseURL:"",i=s.headers&&typeof s.headers=="object"&&!Array.isArray(s.headers)?s.headers:{},o=Object.entries(i).filter(d=>typeof d[0]=="string"&&typeof d[1]=="string").map(([d,w])=>({row:ks(),key:d,value:w})),p=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([d,w])=>({id:d,name:w&&typeof w=="object"&&"name"in w&&typeof w.name=="string"?w.name:d})):[],h=p.length>0?p.map(d=>({row:ks(),id:typeof d?.id=="string"?d.id:"",name:typeof d?.name=="string"?d.name:typeof d?.id=="string"?d.id:""})):[ua()],u=Array.isArray(t.env)?t.env.find(d=>typeof d=="string"&&d.trim().length>0)?.trim():void 0;return{providerID:t.id,name:typeof t.name=="string"&&t.name.trim()?t.name:t.id,baseURL:n,apiKey:u?`{env:${u}}`:"",models:h,headers:o.length>0?o:[ma()]}}function No(t){const s=t.form.providerID.trim(),n=t.form.name.trim(),i=t.form.baseURL.trim(),{env:o,key:p}=wo(t.form.apiKey),h=t.disabledProviders??[],u=t.editingProviderID?.trim(),d=s?xo.test(s)?void 0:"Use lowercase letters, numbers, hyphens, or underscores":"Provider ID is required",w=n?void 0:"Display name is required",c=i?bo.test(i)?void 0:"Base URL must start with http:// or https://":"Base URL is required",r=!!(o||p||u&&t.allowExistingAuth&&u===s)?void 0:"API key or {env:VAR_NAME} is required",f=h.includes(s),b=d||!!(u&&u===s)?void 0:t.existingProviderIDs.has(s)&&!f?"A provider with this ID is already connected":void 0,j=new Set,A=t.form.models.map(v=>{const C=v.id.trim(),L=C?j.has(C)?"Duplicate":void j.add(C):"Required",B=v.name.trim()?void 0:"Required";return{id:L,name:B}}),I=A.every(v=>!v.id&&!v.name),P=Object.fromEntries(t.form.models.map(v=>[v.id.trim(),{name:v.name.trim()}])),E=new Set,N=t.form.headers.map(v=>{const C=v.key.trim(),L=v.value.trim();return!C&&!L?{}:{key:C?E.has(C.toLowerCase())?"Duplicate":void E.add(C.toLowerCase()):"Required",value:L?void 0:"Required"}}),x=N.every(v=>!v.key&&!v.value),D=Object.fromEntries(t.form.headers.map(v=>({key:v.key.trim(),value:v.value.trim()})).filter(v=>v.key&&v.value).map(v=>[v.key,v.value])),k={providerID:d??b,name:w,baseURL:c,apiKey:r};return!d&&!b&&!w&&!c&&!r&&I&&x?{err:k,models:A,headers:N,result:{providerID:s,name:n,apiKey:p,config:{npm:fo,name:n,...o?{env:[o]}:{},options:{baseURL:i,...Object.keys(D).length>0?{headers:D}:{}},models:P}}}:{err:k,models:A,headers:N}}const Co=({existingProviderIDs:t,disabledProviders:s=[],busy:n=!1,mode:i="create",initialValues:o,allowExistingAuth:p=!1,authFailureHint:h=null,onSubmit:u,onCancel:d,onDisconnect:w})=>{const c=i==="edit",[g,r]=a.useState(()=>o??jo()),[f,y]=a.useState({}),[b,j]=a.useState([]),[A,I]=a.useState([]),P=a.useRef(null);a.useEffect(()=>{o&&(c&&P.current===o.providerID||(P.current=c?o.providerID:null,r(o),y({}),j([]),I([])))},[o,c]);const E=(k,m)=>{r(v=>({...v,[k]:m})),y(v=>({...v,[k]:void 0}))},N=(k,m,v)=>{r(C=>({...C,models:C.models.map((L,B)=>B===k?{...L,[m]:v}:L)})),j(C=>{const L=[...C];return L[k]={...L[k]??{},[m]:void 0},L})},x=(k,m,v)=>{r(C=>({...C,headers:C.headers.map((L,B)=>B===k?{...L,[m]:v}:L)})),I(C=>{const L=[...C];return L[k]={...L[k]??{},[m]:void 0},L})},D=async k=>{if(k.preventDefault(),n)return;const m=No({form:g,existingProviderIDs:t,disabledProviders:s,editingProviderID:c?g.providerID:void 0,allowExistingAuth:c&&p});y(m.err),j(m.models),I(m.headers),m.result&&await u(m.result)};return e.jsxs("form",{onSubmit:D,className:"space-y-0",children:[e.jsxs(te,{title:c?"Edit custom provider":"Custom provider",divider:!1,settingsItem:"providers.custom",contentClassName:ht,children:[e.jsx("p",{className:Ra,children:"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."}),h?e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:h}):null,e.jsxs(Me,{label:"Provider ID",info:"Lowercase letters, numbers, hyphens, and underscores. Used as the Pi provider id.",children:[e.jsx(ie,{value:g.providerID,onChange:k=>E("providerID",k.target.value),placeholder:"my-provider",className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:!c,disabled:c||n,"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(Me,{label:"Display name",info:"Shown in the provider and model pickers.",children:[e.jsx(ie,{value:g.name,onChange:k=>E("name",k.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(Me,{label:"Base URL",info:"OpenAI-compatible API base URL. Must start with http:// or https://.",children:[e.jsx(ie,{value:g.baseURL,onChange:k=>E("baseURL",k.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.jsxs(Me,{label:"API key",info:c&&p?"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(ie,{type:"password",value:g.apiKey,onChange:k=>E("apiKey",k.target.value),placeholder:c&&p?"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(te,{title:"Models",contentClassName:ht,children:[g.models.map((k,m)=>e.jsx("div",{className:`${St} 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:He,children:"Model ID"}),e.jsx(ie,{value:k.id,onChange:v=>N(m,"id",v.target.value),placeholder:"gpt-4o",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Model ID"}),b[m]?.id?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:b[m]?.id}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:He,children:"Model name"}),e.jsx(ie,{value:k.name,onChange:v=>N(m,"name",v.target.value),placeholder:"GPT-4o",className:"mt-1 h-8 rounded-md px-3","aria-label":"Model name"}),b[m]?.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:b[m]?.name}):null]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:Ge,disabled:g.models.length<=1,onClick:()=>{g.models.length<=1||(r(v=>({...v,models:v.models.filter((C,L)=>L!==m)})),j(v=>v.filter((C,L)=>L!==m)))},"aria-label":"Remove model",children:e.jsx(T,{name:"delete-bin",className:"size-4"})})]})},k.row)),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{r(k=>({...k,models:[...k.models,ua()]})),j(k=>[...k,{}])},children:"Add model"})]}),e.jsxs(te,{title:"Headers",contentClassName:ht,children:[e.jsx("p",{className:Ra,children:"Optional request headers sent with every call."}),g.headers.map((k,m)=>e.jsx("div",{className:`${St} 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:He,children:"Header name"}),e.jsx(ie,{value:k.key,onChange:v=>x(m,"key",v.target.value),placeholder:"X-Custom-Header",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header name"}),A[m]?.key?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:A[m]?.key}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:He,children:"Header value"}),e.jsx(ie,{value:k.value,onChange:v=>x(m,"value",v.target.value),placeholder:"value",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header value"}),A[m]?.value?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:A[m]?.value}):null]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:Ge,disabled:g.headers.length<=1,onClick:()=>{g.headers.length<=1||(r(v=>({...v,headers:v.headers.filter((C,L)=>L!==m)})),I(v=>v.filter((C,L)=>L!==m)))},"aria-label":"Remove header",children:e.jsx(T,{name:"delete-bin",className:"size-4"})})]})},k.row)),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{r(k=>({...k,headers:[...k.headers,ma()]})),I(k=>[...k,{}])},children:"Add header"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4",children:[d?e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:d,disabled:n,children:"Back"}):null,w?e.jsx(S,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{w()},disabled:n,children:"Disconnect"}):null,e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:n,children:n?"Saving...":c?"Update provider":"Save provider"})]})]})},So=({provider:t,onSelect:s})=>{const n=t.models.length,i=n===1?"1 model":`${n} models`,{hasLogo:o}=ii(t.id);return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.label} provider, ${i}${t.authenticated?", authenticated":""}`,className:J("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:[o?e.jsx(cn,{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(T,{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(T,{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(T,{name:"stack",className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"tabular-nums",children:i})]})]})},Po=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>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"})]},n))}),Gt="__pi_custom_provider__",sa=Bi(t=>({selectedProviderId:null,setSelectedProviderId:s=>t(n=>n.selectedProviderId===s?n:{selectedProviderId:s})})),To=(t,s,n)=>t.some(i=>i.providerID===s&&i.modelID===n),Qe=()=>({runtimeKey:it()}),ps="__pi_fallback__",Io=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},Eo=t=>[...t].sort((s,n)=>s.authenticated!==n.authenticated?s.authenticated?-1:1:s.label.localeCompare(n.label,void 0,{sensitivity:"base"})),wn=a.memo(({providerId:t,model:s,storedLevel:n,isBusy:i,isHidden:o,isConnected:p,onThinkingChange:h,onToggleHidden:u})=>{const d=a.useMemo(()=>dn(s),[s]),c=a.useMemo(()=>un(d),[d])||n!==void 0,g=a.useMemo(()=>Io(d,n),[d,n]),r=n??ps;return e.jsxs("div",{className:J("flex min-w-0 items-center gap-2 py-2",o&&"opacity-60"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",children:s.label||s.id}),c?e.jsxs(_e,{value:r,onValueChange:f=>h(t,s.id,f===ps?null:f),disabled:i,children:[e.jsx(Oe,{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(Ue,{children:f=>f===ps?"Default":f&&mn(f)?vs[f]:f??""})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:ps,children:"Default"}),g.map(f=>e.jsx(Ee,{value:f,children:vs[f]},f))]})]}):null,s.supportsThinking?e.jsx(T,{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,p?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>u(t,s.id),"aria-label":o?"Show model in pickers":"Hide model from pickers",title:o?"Show model in pickers":"Hide model from pickers",children:e.jsx(T,{name:o?"eye":"eye-off",className:"size-4"})}):null]})});wn.displayName="ProviderModelRow";const Mo=({login:t,promptValue:s,onPromptValueChange:n,onSubmit:i,busy:o})=>e.jsxs("div",{className:"space-y-3 border-t border-[var(--surface-subtle)] pt-3",children:[t.authUrl?e.jsx("a",{className:"typography-meta text-[var(--primary-base)] underline",href:t.authUrl.url,target:"_blank",rel:"noreferrer",children:t.authUrl.instructions||"Open"}):null,t.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:t.deviceCode.userCode}),e.jsx("a",{className:"ml-2 text-[var(--primary-base)] underline",href:t.deviceCode.verificationUri,target:"_blank",rel:"noreferrer",children:"Open"})]}):null,t.prompt?e.jsxs(ze,{label:t.prompt.message||"Copy the authorization code from your browser and paste it here.",children:[t.prompt.type==="select"&&t.prompt.options?e.jsxs(_e,{value:s,onValueChange:n,children:[e.jsx(Oe,{size:Ke,className:ca,children:e.jsx(Ue,{})}),e.jsx(Fe,{children:t.prompt.options.map(p=>e.jsx(Ee,{value:p.id,children:p.label},p.id))})]}):e.jsx(ie,{type:t.prompt.type==="secret"?"password":"text",value:s,onChange:p=>n(p.target.value),placeholder:t.prompt.placeholder,autoComplete:"off"}),e.jsx(S,{size:"sm",onClick:i,disabled:o||s.length===0,children:"Continue"})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Waiting for authorization…"})]});function Ao(){const t=sa(R=>R.selectedProviderId),s=sa(R=>R.setSelectedProviderId),n=_(R=>R.hiddenModels),i=_(R=>R.toggleHiddenModel),o=_(R=>R.hideAllModels),p=_(R=>R.showAllModels),h=Ae(R=>R.settingsDefaultThinkingByModel),u=Ae(R=>R.setSettingsDefaultThinkingByModel),d=Ae(R=>R.setSettingsDefaultThinking),[w,c]=a.useState(null),[g,r]=a.useState(""),[f,y]=a.useState(""),[b,j]=a.useState(null),[A,I]=a.useState(!1),[P,E]=a.useState(null),[N,x]=a.useState(!1),[D,k]=a.useState(!1),[m,v]=a.useState(!1),[C,L]=a.useState(!1),[B,q]=a.useState(null),[Y,$]=a.useState(new Set),[V,oe]=a.useState(""),[xe,je]=a.useState(80),z=a.useCallback(async()=>{const{providers:R}=await Le.listProviders(Qe());c(R),k(!1),Ae.getState().loadProviders({source:"providersPage:refresh"})},[]),O=a.useCallback(async()=>{if(!m){v(!0);try{const{providers:R}=await Le.refreshProviders(Qe());c(R),k(!1);const Z=Ae.getState();Z.invalidateProviderCache(),Z.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:R}))}catch{k(!0)}finally{v(!1)}}},[m]),X=a.useCallback(async()=>{if(!C){L(!0),q(null);try{const{providers:R}=await Le.refreshProviders(Qe());c(R),k(!1),q("success");const Z=Ae.getState();Z.invalidateProviderCache(),Z.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:R})),F.success("Model catalog refreshed")}catch{k(!0),q("error"),F.error("Could not refresh model catalog")}finally{L(!1)}}},[C]);a.useEffect(()=>{let R=!0;return z().catch(()=>{R&&k(!0)}),()=>{R=!1}},[z]),a.useEffect(()=>{let R=!0;const Z=Qe();return Le.getSettings(Z).then(le=>{if(!R||Z.runtimeKey!==it())return;const ce=le.pichamber.defaultThinkingByModel??{},G=le.pichamber.defaultThinking,ne=Ae.getState().settingsDefaultThinkingByModel;(()=>{const Ne=Object.keys(ne),me=Object.keys(ce);if(Ne.length!==me.length)return!1;for(const Pe of Ne)if(ne[Pe]!==ce[Pe])return!1;return!0})()||u(ce),G!==Ae.getState().settingsDefaultThinking&&d(G)}).catch(()=>{}),()=>{R=!1}},[d,u]),a.useEffect(()=>{if(!b||b.state!=="pending")return;let R=!0;const Z=window.setInterval(()=>{Le.getProviderLogin(b.providerId,b.id,Qe()).then(le=>{R&&(j(le.login),le.login.state==="complete"&&z().catch(()=>k(!0)))}).catch(()=>{R&&j(le=>le&&{...le,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})})},1e3);return()=>{R=!1,window.clearInterval(Z)}},[b,z]),a.useEffect(()=>{if(!b||b.state!=="complete"||!w)return;w.find(Z=>Z.id===b.providerId)?.authenticated===!0&&j(null)},[b,w]),a.useEffect(()=>{const R=Z=>{const le=Z.detail;Array.isArray(le)&&(c(le),k(!1))};return window.addEventListener("pichamber:providers-refreshed",R),()=>window.removeEventListener("pichamber:providers-refreshed",R)},[]);const H=w?.find(R=>R.id===t)??null,M=H?.id;a.useEffect(()=>{if(!M){E(null);return}let R=!0;return Le.getProviderConfig(M,Qe()).then(Z=>{R&&E(Z.config)}).catch(()=>{R&&E(null)}),()=>{R=!1}},[M]);const W=a.useCallback(async(R,Z,le)=>{const ce=ys({providerId:R,modelId:Z});if(!ce)return;const G=Qe(),ne=Ae.getState().settingsDefaultThinkingByModel,de={...ne};le===null?delete de[ce]:de[ce]=le,u(de),$(Ne=>new Set(Ne).add(ce)),ot("saving");try{const Ne=await Le.setPiChamberDefaults({defaultThinkingByModel:{[ce]:le}},G);if(G.runtimeKey!==it()){u(ne);return}const me=Ne.pichamber.defaultThinkingByModel??{};u(me),Ne.pichamber.defaultThinking!==void 0&&d(Ne.pichamber.defaultThinking),ot("saved")}catch{G.runtimeKey===it()&&u(ne),ot("error")}finally{$(Ne=>{const me=new Set(Ne);return me.delete(ce),me})}},[d,u]),se=a.useCallback((R,Z,le)=>{W(R,Z,le)},[W]),ye=a.useCallback((R,Z)=>{i(R,Z)},[i]);a.useEffect(()=>{je(80)},[M]);const K=a.useMemo(()=>H?H.models.slice(0,xe):[],[H,xe]),re=H?H.models.length>K.length:!1,fe=a.useMemo(()=>w?Eo(w):[],[w]),be=a.useMemo(()=>{const R=V.trim().toLowerCase();return R?fe.filter(Z=>{const le=Z.label.toLowerCase(),ce=Z.id.toLowerCase();return le.includes(R)||ce.includes(R)}):fe},[fe,V]);return{selectedProviderId:t,setSelectedProviderId:s,hiddenModels:n,toggleHiddenModel:i,hideAllModels:o,showAllModels:p,settingsDefaultThinkingByModel:h,setSettingsDefaultThinkingByModel:u,setSettingsDefaultThinking:d,providers:w,setProviders:c,apiKey:g,setApiKey:r,promptValue:f,setPromptValue:y,login:b,setLogin:j,customEditing:A,setCustomEditing:I,providerConfig:P,setProviderConfig:E,busy:N,setBusy:x,failed:D,setFailed:k,refreshing:m,setRefreshing:v,refreshingCatalog:C,setRefreshingCatalog:L,catalogRefreshFeedback:B,setCatalogRefreshFeedback:q,thinkingBusyKeys:Y,setThinkingBusyKeys:$,providerQuery:V,setProviderQuery:oe,visibleCap:xe,setVisibleCap:je,refresh:z,refreshProviders:O,refreshCatalog:X,provider:H,providerId:M,sortedProviders:fe,filteredProviders:be,displayModels:K,hasMore:re,saveCustomProvider:async R=>{x(!0);try{await Le.setProviderModels({providerId:R.providerID,label:R.name,baseUrl:R.config.options.baseURL,api:"openai-completions",models:Object.entries(R.config.models).map(([Z,le])=>({id:Z,providerId:R.providerID,label:le.name})),...R.config.options.headers?{headers:R.config.options.headers}:{},...R.config.env?.[0]?{apiKeyReference:`{env:${R.config.env[0]}}`}:{}},Qe()),R.apiKey&&j((await Le.loginProvider({providerId:R.providerID,type:"api_key",apiKey:R.apiKey},Qe())).login),s(R.providerID),I(!1),await z()}catch{k(!0)}finally{x(!1)}},startLogin:async R=>{if(!(!H||N||R==="api_key"&&g.trim().length===0)){x(!0);try{const Z=await Le.loginProvider({providerId:H.id,type:R,...R==="api_key"?{apiKey:g.trim()}:{}},Qe());r(""),y(""),j(Z.login),Z.login.state==="complete"&&await z()}catch{j({id:"",providerId:H.id,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{x(!1)}}},submitPrompt:async()=>{if(!(!b||!b.prompt||f.length===0||N)){x(!0);try{const R=await Le.respondProviderLogin(b.providerId,b.id,f,Qe());y(""),j(R.login),R.login.state==="complete"&&await z()}catch{j(R=>R&&{...R,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{x(!1)}}},logout:async()=>{if(!(!H||N)){x(!0);try{await Le.logoutProvider({providerId:H.id},Qe()),j(null),await z()}catch{k(!0)}finally{x(!1)}}},handleThinkingChange:se,handleToggleHidden:ye}}const Do=()=>{const{isMobile:t}=Ve(),{selectedProviderId:s,setSelectedProviderId:n,hiddenModels:i,hideAllModels:o,showAllModels:p,settingsDefaultThinkingByModel:h,providers:u,apiKey:d,setApiKey:w,promptValue:c,setPromptValue:g,login:r,customEditing:f,setCustomEditing:y,providerConfig:b,busy:j,failed:A,refreshing:I,refreshingCatalog:P,catalogRefreshFeedback:E,thinkingBusyKeys:N,providerQuery:x,setProviderQuery:D,setVisibleCap:k,refreshProviders:m,refreshCatalog:v,provider:C,filteredProviders:L,displayModels:B,hasMore:q,saveCustomProvider:Y,startLogin:$,submitPrompt:V,logout:oe,handleThinkingChange:xe,handleToggleHidden:je}=Ao();if(A&&!u)return e.jsx(Ie,{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(S,{variant:"outline",size:"sm",onClick:()=>{m()},disabled:I,children:[e.jsx(T,{name:"refresh",className:J("size-4",I&&"animate-spin")}),I?"Retrying…":"Retry"]})]})});if(f||s===Gt){const O=b?.providerId===C?.id?b:null,X=O?ko({id:O.providerId,name:O.label,options:{baseURL:O.baseUrl},models:O.models}):void 0;return e.jsx(Ie,{title:O?"Edit custom provider":"Custom provider",children:e.jsx(Co,{existingProviderIDs:new Set(u?.map(H=>H.id)??[]),mode:O?"edit":"create",initialValues:X,allowExistingAuth:C?.authenticated===!0,busy:j,onSubmit:H=>{Y(H)},onCancel:()=>{y(!1),n(C?.id??null)}})})}if(C){const O=r?.providerId===C.id?r:null,X=C.authenticated||O?.state==="complete";return e.jsxs(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>n(null),"aria-label":"Back to providers",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{name:"arrow-left-s",className:"size-4"})}),e.jsx(cn,{providerId:C.id,className:"size-5 shrink-0"}),e.jsx("span",{className:"truncate",children:C.label})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:C.id}),children:[A?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,e.jsxs(te,{title:"Authentication",divider:!1,settingsItem:"providers.auth",headerAction:X?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{oe()},disabled:j,children:j?"Disconnecting...":"Disconnect"}):null,children:[X?e.jsxs("div",{className:"flex items-center gap-1.5 py-1.5 typography-ui-label",children:[e.jsx(T,{name:"check",className:"size-4 text-[var(--status-success)]"}),"Connected"]}):e.jsxs("div",{className:"space-y-4 py-1.5",children:[e.jsx(ze,{label:"API Key",children:e.jsxs("div",{className:"flex w-full max-w-[24rem] gap-2",children:[e.jsx(ie,{type:"password",value:d,onChange:H=>w(H.target.value),placeholder:"sk-...",autoComplete:"off"}),e.jsx(S,{size:"sm",onClick:()=>{$("api_key")},disabled:j||d.trim().length===0,children:j?"Saving...":"Save Key"})]})}),e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{$("oauth")},disabled:j,children:"Reconnect"})]}),O?.state==="pending"?e.jsx(Mo,{login:O,promptValue:c,onPromptValueChange:g,onSubmit:()=>{V()},busy:j}):null,O?.state==="failed"?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Authorization was declined or did not complete."}):null]}),e.jsxs(te,{title:"Available Models",settingsItem:"providers.models",info:"Hidden models stay out of the composer and session default pickers. Thinking defaults apply to new sessions and composer model changes.",headerAction:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{v()},disabled:P||j,"aria-label":"Refresh model catalog",title:"Refresh model catalog",children:e.jsx(T,{name:"refresh",className:J("size-4",P&&"animate-spin")})}),X?e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>p(C.id),children:"Show all"}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>o(C.id,C.models.map(H=>H.id)),children:"Hide all"})]}):null,b?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>y(!0),children:"Update provider"}):null]}),children:[e.jsx("div",{"aria-live":"polite",className:"sr-only",children:P?"Refreshing model catalog":E==="success"?"Model catalog refreshed":E==="error"?"Could not refresh model catalog":""}),e.jsxs("div",{className:"divide-y divide-[var(--surface-subtle)]",children:[C.models.length===0?e.jsx("p",{className:"py-3 typography-meta text-muted-foreground",children:"No models available."}):B.map(H=>{const M=To(i,C.id,H.id),W=ys({providerId:C.id,modelId:H.id})??`${C.id}/${H.id}`,se=h[W],ye=mn(se)?se:void 0,K=N.has(W);return e.jsx(wn,{providerId:C.id,model:H,storedLevel:ye,isBusy:K,isHidden:M,isConnected:X,onThinkingChange:xe,onToggleHidden:je},H.id)}),q?e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>k(H=>H+80),children:["Show ",Math.min(80,C.models.length-B.length)," more (",B.length," of"," ",C.models.length,")"]})}):null]})]})]})}return u===null?e.jsx(Ie,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{m()},disabled:I,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(T,{name:"refresh",className:J("size-4",I&&"animate-spin")})})}),children:e.jsx(te,{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(Po,{count:6})})})}):L.length===0&&x.trim()===""&&u.length===0?e.jsx(Ie,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(T,{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(ie,{value:x,onChange:O=>D(O.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-[24rem] pl-8"})]}),e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{m()},disabled:I,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(T,{name:"refresh",className:J("size-4",I&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Gt),children:[e.jsx(T,{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(T,{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(S,{variant:"outline",size:"sm",onClick:()=>n(Gt),children:"Add custom provider"})]})}):e.jsxs(Ie,{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",children:[e.jsx(T,{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(ie,{value:x,onChange:O=>D(O.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),x?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(T,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{m()},disabled:I,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(T,{name:"refresh",className:J("size-4",I&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Gt),children:[e.jsx(T,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:[A?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Refresh failed — showing cached providers."}):null,e.jsx(te,{title:"Providers",divider:!1,settingsItem:"providers.browse",children:L.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 “",x,"”."]}),e.jsx(S,{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:[L.map(O=>e.jsx(So,{provider:O,onSelect:n},O.id)),e.jsxs("button",{type:"button",onClick:()=>n(Gt),"aria-label":"Add custom provider",className:J("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(T,{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"})]})]})})]})},Lo=({snippet:t,onSelect:s,showSourcePill:n=!0})=>{const i=t.source==="project"?"Project":t.source==="global"?"Global":t.source,o=t.description?.trim()||t.content.replace(/\s+/g," ").trim().slice(0,140)||"No description",p=o.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, ${i}`,className:J("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:[n?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:J("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:i})}):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:[o,p?"…":null]})]})]})},kn=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>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"})]})]},n))}),Ro=t=>t.split(/[,\s]+/).map(s=>s.trim()).filter(s=>s.length>0),zo=()=>{const{isMobile:t}=Ve(),s=pn(),n=et(Q=>Q.selectedSnippetId),i=et(Q=>Q.snippetDraft),o=et(Q=>Q.snippets),p=et(Q=>Q.isLoading),h=et(Q=>Q.setSelectedSnippet),u=et(Q=>Q.setSnippetDraft),d=et(Q=>Q.createSnippet),w=et(Q=>Q.updateSnippet),c=et(Q=>Q.deleteSnippet),g=et(Q=>Q.loadSnippets),r=a.useMemo(()=>n?o.find(Q=>Q.id===n)??null:null,[n,o]),f=!!(i&&!r),[y,b]=a.useState(""),[j,A]=a.useState("global"),[I,P]=a.useState(""),[E,N]=a.useState(""),[x,D]=a.useState(""),[k,m]=a.useState(!1),[v,C]=a.useState(!1),[L,B]=a.useState(!1),q=a.useRef(""),Y=a.useRef(""),$=a.useRef(""),V=a.useRef(""),oe=a.useRef("global");a.useEffect(()=>{f&&i?(b(i.name),A(i.scope),P(i.description??""),N(""),D(i.content??""),q.current=i.content??"",Y.current=i.description??"",$.current=i.name,V.current="",oe.current=i.scope):r&&(b(r.name),A(r.source),P(r.description??""),N((r.aliases??[]).join(", ")),D(r.content),q.current=r.content,Y.current=r.description??"",$.current=r.name,V.current=(r.aliases??[]).join(", "),oe.current=r.source)},[i,f,r]);const xe=a.useCallback(()=>{f&&u(null),h(null)},[f,h,u]),je=a.useCallback(async()=>{const Q=y.trim().replace(/\s+/g,"-");if(!Q){F.error("Snippet name is required");return}if(!/^[a-z0-9_-]+$/i.test(Q)){F.error("Snippet name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){F.error("Snippet content is required");return}const U=Ro(E);if(U.length>10){F.error("Snippets support at most 10 aliases");return}for(const R of U)if(!/^[a-z0-9_-]+$/i.test(R)){F.error("Aliases may only contain letters, numbers, dashes and underscores");return}if(j==="project"&&!s?.trim()){F.error("Project snippets need an active project directory");return}m(!0);const ae=f?await d(Q,x,{description:I,aliases:U,scope:j,directory:s}):await w(r?.id??"",{name:Q!==$.current?Q:void 0,content:x!==q.current?x:void 0,description:I!==Y.current?I:void 0,aliases:E.trim()!==V.current.trim()?U:void 0,...j!==oe.current?{scope:j,...j==="project"&&s?{directory:s}:{}}:{}},s);m(!1),ae?(f||u(null),F.success(f?"Snippet created":"Snippet updated")):F.error(f?"Failed to create snippet":"Failed to update snippet")},[E,x,d,I,s,f,y,j,r?.id,u,w]),z=a.useCallback(async()=>{if(!r)return;C(!0);const Q=await c(r.id,s);C(!1),Q?(F.success("Snippet deleted"),B(!1)):F.error("Failed to delete snippet")},[c,s,r]),[O,X]=a.useState(""),[H,M]=a.useState("all"),[W,se]=a.useState(!1),ye=a.useCallback(async()=>{if(!W){se(!0);try{const{invalidateSnippetsLoadCache:Q}=await Zt(async()=>{const{invalidateSnippetsLoadCache:U}=await import("./useAppFontEffects-CYzYRbLp.js").then(ae=>ae.dE);return{invalidateSnippetsLoadCache:U}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78]));Q(s),await g(s)}finally{se(!1)}}},[s,g,W]);a.useEffect(()=>{g(s)},[s,g]);const K=a.useMemo(()=>[...o].sort((Q,U)=>Q.name.localeCompare(U.name)),[o]),re=a.useMemo(()=>{let Q=K;H!=="all"&&(Q=Q.filter(ae=>ae.source===H));const U=O.trim().toLowerCase();return U?Q.filter(ae=>{const R=ae.name.toLowerCase().includes(U),Z=(ae.description??"").toLowerCase().includes(U),le=ae.content.toLowerCase().includes(U),ce=(ae.aliases??[]).some(G=>G.toLowerCase().includes(U));return R||Z||le||ce}):Q},[K,H,O]),fe=a.useMemo(()=>{let Q=0,U=0;for(const ae of o)ae.source==="project"?U+=1:Q+=1;return{all:o.length,global:Q,project:U}},[o]),be=a.useCallback(async()=>{const Q=new Set(o.map(R=>R.name.toLowerCase()));let U="new-snippet",ae=1;for(;Q.has(U.toLowerCase());)U=`new-snippet-${ae++}`;u({name:U,scope:"global",content:"",description:""}),h(null)},[h,u,o]);if(n!==null||i){if(!r&&!f)return e.jsx(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:xe,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{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(T,{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(S,{variant:"outline",size:"sm",onClick:xe,children:"Back to snippets"})]})});const Q=f?y.trim()!==$.current||I!==Y.current||x!==q.current||E.trim()!==V.current.trim()||j!==oe.current:y.trim()!==$.current||x!==q.current||I!==Y.current||E.trim()!==V.current.trim()||j!==oe.current,U=Q&&!k&&x.trim().length>0&&y.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:xe,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New snippet":`#${r?.name??y}`})]}),description:f?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a reusable text snippet"}):r?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:r.description}):void 0,headerEnd:!f&&r?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>B(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(T,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[e.jsx(te,{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(ie,{value:y,onChange:ae=>b(ae.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:j,onValueChange:ae=>A(ae),children:[e.jsx(Oe,{size:Ke,className:"w-full",children:e.jsx(Ue,{})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:"global",children:"Global"}),e.jsx(Ee,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:j==="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(ie,{value:I,onChange:ae=>P(ae.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(ie,{value:E,onChange:ae=>N(ae.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(te,{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:Q?"Unsaved changes":"No changes"}),children:[e.jsx(Ss,{value:x,onChange:D,initialMode:f?"write":"preview",triggerPreview:`#${y.trim()||"name"}`},f?"new-snippet-editor":`snippet-editor:${r?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:xe,children:"Cancel"}),e.jsx(S,{size:"sm",onClick:()=>{je()},disabled:!U,children:k?"Saving…":f?"Create snippet":"Save changes"})]})]}),!f&&r?e.jsx(te,{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 #",r.name,". This cannot be undone."]})]}),e.jsxs(S,{variant:"destructive",size:"sm",onClick:()=>B(!0),disabled:v,children:[e.jsx(T,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(lt,{open:L,onOpenChange:ae=>!ae&&B(!1),children:e.jsxs(ct,{className:"max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Delete snippet?"}),e.jsxs(mt,{children:["This will permanently delete #",r?.name??"",". This cannot be undone."]})]}),e.jsxs(Ot,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>B(!1),disabled:v,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{z()},disabled:v,children:v?"Deleting…":"Delete"})]})]})})]})}if(p&&o.length===0)return e.jsx(Ie,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{ye()},disabled:W,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(T,{name:"refresh",className:J("size-4",W&&"animate-spin")})})}),children:e.jsx(te,{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(kn,{count:6})})})});const pe=re.length===0&&o.length===0;return e.jsx(Ie,{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",children:[e.jsx(T,{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(ie,{value:O,onChange:Q=>X(Q.target.value),placeholder:"Search snippets","aria-label":"Search snippets",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),O?e.jsx("button",{type:"button",onClick:()=>X(""),"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(T,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{ye()},disabled:W,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(T,{name:"refresh",className:J("size-4",W&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{be()},children:[e.jsx(T,{name:"add",className:"size-4"}),"New snippet"]})]}),children:pe?e.jsx(te,{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(T,{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(S,{variant:"outline",size:"sm",onClick:()=>{be()},children:[e.jsx(T,{name:"add",className:"size-4"}),"New snippet"]})]})}):e.jsxs(te,{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(S,{variant:"chip",size:"xs","aria-pressed":H==="all",onClick:()=>M("all"),children:["All ",fe.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":H==="project",onClick:()=>M("project"),children:["Project ",fe.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":H==="global",onClick:()=>M("global"),children:["Global ",fe.global]})]}),re.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:O.trim()?`No snippets match “${O}”.`:`No ${H} snippets.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{X(""),M("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[re.map(Q=>e.jsx(Lo,{snippet:Q,onSelect:h,showSourcePill:H==="all"},`${Q.source}:${Q.id}`)),e.jsxs("button",{type:"button",onClick:()=>{be()},"aria-label":"Create new snippet",className:J("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(T,{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 Nn(t){let s=0;const n=/\$(\d+)/g;let i;for(;(i=n.exec(t))!==null;){const o=Number.parseInt(i[1]??"",10);Number.isSafeInteger(o)&&o>s&&(s=o)}return s}function _o(t){return`$${Nn(t)+1}`}function Oo(t){const s=Nn(t);return s<1?null:`\${@:${s+1}}`}function Uo(t){const s=_o(t),n=Oo(t);return[{value:s,label:s,hint:`Insert ${s}, the next argument`},{value:"$@",label:"$@",hint:"Insert $@, all arguments"},...n?[{value:n,label:n,hint:`Insert ${n}, all arguments after the positional ones`}]:[]]}const Fo=async({previousName:t,nextName:s,previousLocation:n,nextLocation:i})=>{const o=bs.getState(),p=o.projects.find(b=>b.id===o.activeProjectId),h=p?.path?{id:p.id,path:p.path}:null,u=_.getState().globalDraftStarters??[],d=h?await li(h):[];if(!(n==="project"?d:u).some(b=>b.type==="prompt"&&b.name===t))return!0;if(i==="project"&&!h)return!1;const g=b=>b.filter(j=>!(j.type==="prompt"&&j.name===t));let r=n==="global"?g(u):u,f=n==="project"?g(d):d;const y={type:"prompt",name:s,scope:i};return i==="project"?f.some(b=>b.type==="prompt"&&b.name===s)||(f=[...f,y]):r.some(b=>b.type==="prompt"&&b.name===s)||(r=[...r,y]),JSON.stringify(r)!==JSON.stringify(u)&&(_.getState().setGlobalDraftStarters(r),await ke({draftStarters:r})),h&&JSON.stringify(f)!==JSON.stringify(d)?ci(h,f):!0},Bo=()=>{const{isMobile:t}=Ve(),s=pn(),n=tt(U=>U.selectedPromptId),i=tt(U=>U.promptDraft),o=tt(U=>U.prompts),p=tt(U=>U.isLoading),h=tt(U=>U.setSelectedPrompt),u=tt(U=>U.setPromptDraft),d=tt(U=>U.createPrompt),w=tt(U=>U.updatePrompt),c=tt(U=>U.deletePrompt),g=tt(U=>U.loadPrompts),r=a.useMemo(()=>n?o.find(U=>U.id===n)??null:null,[o,n]),f=!!(i&&!r),y=f||r?.editable===!0,b=!f&&r&&r.editable!==!0,[j,A]=a.useState(""),[I,P]=a.useState("global"),[E,N]=a.useState(""),[x,D]=a.useState(""),[k,m]=a.useState(!1),[v,C]=a.useState(!1),[L,B]=a.useState(!1),q=a.useRef(""),Y=a.useRef(""),$=a.useRef(""),V=a.useRef("global");a.useEffect(()=>{f&&i?(A(i.name),P(i.location),N(i.description??""),D(i.content??""),q.current=i.name,Y.current=i.description??"",$.current=i.content??"",V.current=i.location):r&&(A(r.name),P(r.location==="project"?"project":"global"),N(r.description??""),D(r.content??""),q.current=r.name,Y.current=r.description??"",$.current=r.content??"",V.current=r.location==="project"?"project":"global")},[i,f,r]);const oe=a.useCallback(()=>{f&&u(null),h(null)},[f,u,h]),xe=a.useCallback(async()=>{const U=j.trim().replace(/\s+/g,"-");if(!U){F.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(U)){F.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){F.error("Prompt content is required");return}if(I==="project"&&!s?.trim()){F.error("Project prompts need an active project directory");return}m(!0);const ae=await d(U,x,{description:E,location:I,directory:s});m(!1),ae?F.success(`Prompt /${U} created`):F.error("Failed to create prompt template")},[x,d,E,s,I,j]),je=a.useCallback(async()=>{if(!r)return;const U=j.trim().replace(/\s+/g,"-");if(!U){F.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(U)){F.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){F.error("Prompt content is required");return}if(I==="project"&&!s?.trim()){F.error("Project prompts need an active project directory");return}m(!0);const ae=q.current,R=V.current,Z=await w(r.id,{...U!==q.current?{name:U}:{},...E!==Y.current?{description:E}:{},...x!==$.current?{content:x}:{},...I!==V.current?{location:I}:{}},s);if(m(!1),Z){let le=!0;if(ae&&(U!==ae||I!==R))try{le=await Fo({previousName:ae,nextName:U,previousLocation:R,nextLocation:I})}catch{le=!1}F.success(`Prompt /${U} updated`),le||F.warning("The prompt was updated, but one or more pinned starters could not be updated.")}else F.error("Failed to update prompt template")},[x,E,s,I,j,r,w]),z=a.useCallback(async()=>{if(!r)return;C(!0);const U=await c(r.id,s);C(!1),U?(F.success("Prompt template deleted"),B(!1)):F.error("Failed to delete prompt template")},[c,s,r]),[O,X]=a.useState(""),[H,M]=a.useState("all"),[W,se]=a.useState(!1),ye=a.useCallback(async()=>{if(!W){se(!0);try{oi(s),await g(s)}finally{se(!1)}}},[s,g,W]);a.useEffect(()=>{g(s)},[s,g]);const K=a.useMemo(()=>[...o].sort((U,ae)=>U.name.localeCompare(ae.name)),[o]),re=a.useMemo(()=>{let U=K;H!=="all"&&(U=U.filter(R=>R.location===H));const ae=O.trim().toLowerCase();return ae?U.filter(R=>R.name.toLowerCase().includes(ae)||(R.description??"").toLowerCase().includes(ae)||(R.content??"").toLowerCase().includes(ae)):U},[H,O,K]),fe=a.useMemo(()=>{let U=0,ae=0;for(const R of o)R.location==="project"?ae+=1:R.location==="global"&&(U+=1);return{all:o.length,global:U,project:ae}},[o]),be=a.useMemo(()=>Uo(x),[x]),pe=a.useCallback(()=>{const U=new Set(o.map(Z=>Z.name.toLowerCase()));let ae="new-prompt",R=1;for(;U.has(ae.toLowerCase());)ae=`new-prompt-${R++}`;u({name:ae,location:"global"}),h(null)},[o,u,h]);if(n!==null||i){if(!r&&!f)return e.jsx(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:oe,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{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(T,{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(S,{variant:"outline",size:"sm",onClick:oe,children:"Back to prompt templates"})]})});const U=r?.location==="project"?"Project":r?.location==="global"?"Global":r?.location??"Global",R=j.trim().replace(/\s+/g,"-")!==q.current||E!==Y.current||x!==$.current||I!==V.current,Z=R&&!k&&x.trim().length>0&&j.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:oe,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(T,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New prompt template":`/${r?.name??j}`})]}),description:f?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a native Pi command"}):r?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:r.description}):void 0,headerEnd:!f&&r?.editable===!0?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>B(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(T,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[f?e.jsx(te,{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(ie,{value:j,onChange:le=>A(le.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:["/",j.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:I,onValueChange:le=>P(le),children:[e.jsx(Oe,{size:Ke,className:"w-full",children:e.jsx(Ue,{})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:"global",children:"Global"}),e.jsx(Ee,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:I==="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(ie,{value:E,onChange:le=>N(le.target.value),placeholder:"What does this command do?",className:"h-9 w-full"})]})]})}):e.jsxs(te,{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:J("inline-flex items-center rounded-full px-2.5 py-1 font-medium capitalize",r?.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:U}),r?.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(T,{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,r?.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:I,onValueChange:le=>P(le),children:[e.jsx(Oe,{size:Ke,className:"w-full","aria-label":"Prompt template scope",children:e.jsx(Ue,{})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:"global",children:"Global"}),e.jsx(Ee,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:I==="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(ie,{value:j,onChange:le=>A(le.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:["/",j.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(ie,{value:E,onChange:le=>N(le.target.value),className:"h-9 w-full"})]}):null]}),e.jsxs(te,{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(te,{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:R?"Unsaved changes":"No changes"}):void 0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{value:x,onChange:D,initialMode:f?"write":"preview",contentLabel:"Prompt content",placeholder:"Enter prompt content... Use markdown and Pi argument syntax such as $1 and $@.",triggerPreview:`/${j.trim()||"name"}`,triggerActionLabel:"Runs as",variableChips:be},f?"new-prompt-editor":`prompt-editor:${r?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{f?oe():(A(q.current),P(V.current),N(Y.current),D($.current))},children:"Cancel"}),e.jsx(S,{size:"sm",onClick:()=>{f?xe():je()},disabled:!Z,children:k?"Saving…":f?"Create prompt":"Save changes"})]})]}):e.jsx(e.Fragment,{children:(r?.content??"").trim()?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(la,{content:r?.content??"",stripFrontmatter:!0,className:"max-w-none"})}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"No content."})})}),!f&&r?.editable===!0?e.jsx(te,{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 /",r.name,". This cannot be undone."]})]}),e.jsxs(S,{variant:"destructive",size:"sm",onClick:()=>B(!0),disabled:v,children:[e.jsx(T,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(lt,{open:L,onOpenChange:le=>!le&&B(!1),children:e.jsxs(ct,{className:"max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Delete prompt?"}),e.jsxs(mt,{children:["This will permanently delete /",r?.name??"",". This cannot be undone."]})]}),e.jsxs(Ot,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>B(!1),disabled:v,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{z()},disabled:v,children:v?"Deleting…":"Delete"})]})]})})]})}if(p&&o.length===0)return e.jsx(Ie,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name.",headerEnd:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{ye()},disabled:W,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(T,{name:"refresh",className:J("size-4",W&&"animate-spin")})})}),children:e.jsx(te,{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(kn,{count:6})})})});const Q=re.length===0&&o.length===0;return e.jsx(Ie,{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",children:[e.jsx(T,{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(ie,{value:O,onChange:U=>X(U.target.value),placeholder:"Search prompt templates","aria-label":"Search prompt templates",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),O?e.jsx("button",{type:"button",onClick:()=>X(""),"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(T,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{ye()},disabled:W,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(T,{name:"refresh",className:J("size-4",W&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{pe()},children:[e.jsx(T,{name:"add",className:"size-4"}),"New prompt"]})]}),children:Q?e.jsx(te,{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(T,{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(S,{variant:"outline",size:"sm",onClick:()=>{pe()},children:[e.jsx(T,{name:"add",className:"size-4"}),"New prompt"]})]})}):e.jsxs(te,{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(S,{variant:"chip",size:"xs","aria-pressed":H==="all",onClick:()=>M("all"),children:["All ",fe.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":H==="project",onClick:()=>M("project"),children:["Project ",fe.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":H==="global",onClick:()=>M("global"),children:["Global ",fe.global]})]}),re.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:O.trim()?`No prompt templates match “${O}”.`:`No ${H} prompt templates.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{X(""),M("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[re.map(U=>{const ae=U.editable===!0,R=U.location==="project"?"Project":U.location==="global"?"Global":U.location,Z=U.description?.trim()||(U.content??"").replace(/\s+/g," ").trim().slice(0,140)||"No description";return e.jsxs("button",{type:"button",onClick:()=>h(U.id),"aria-label":`${U.name} prompt template, ${R}${ae?"":", read-only"}`,className:J("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:J("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:R}),ae?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:Z})]})]},U.id)}),e.jsxs("button",{type:"button",onClick:()=>{pe()},"aria-label":"Create new prompt template",className:J("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(T,{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"})]})]})]})})},pa=()=>{const t=Ae(c=>c.settingsGitmojiEnabled),s=Ae(c=>c.setSettingsGitmojiEnabled),n=Ar(),i=_(c=>c.gitChangesViewMode),o=_(c=>c.setGitChangesViewMode),[p,h]=a.useState(!0),u=a.useMemo(()=>[{id:"flat",label:"Flat List"},{id:"tree",label:"Tree View"}],[]);a.useEffect(()=>{(async()=>{try{let g=null;if(!g){const r=Yt()?.settings;if(r)try{const y=(await r.load())?.settings;y&&(g={gitmojiEnabled:typeof y.gitmojiEnabled=="boolean"?y.gitmojiEnabled:void 0,gitChangesViewMode:y.gitChangesViewMode==="flat"||y.gitChangesViewMode==="tree"?y.gitChangesViewMode:void 0})}catch{}}if(!g){const r=await Be("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});r.ok&&(g=await r.json())}g&&(typeof g.gitmojiEnabled=="boolean"&&s(g.gitmojiEnabled),(g.gitChangesViewMode==="flat"||g.gitChangesViewMode==="tree")&&o(g.gitChangesViewMode))}catch(g){console.warn("Failed to load git settings:",g)}finally{h(!1)}})()},[o,s]);const d=a.useCallback(async c=>{s(c);try{await ke({gitmojiEnabled:c})}catch(g){console.warn("Failed to save gitmoji setting:",g)}},[s]),w=a.useCallback(c=>{c!==i&&(o(c),ke({gitChangesViewMode:c}))},[i,o]);return p?null:e.jsx(te,{title:"Git Preferences",children:e.jsxs("div",{className:We,children:[e.jsx(_t,{settingsItem:"git.changes-view",title:"Changes View",children:e.jsx(Nt,{"aria-label":"Git changes view mode",children:u.map(c=>e.jsx(Ct,{selected:i===c.id,onSelect:()=>{w(c.id)},label:c.label,ariaLabel:`Git changes view mode: ${c.label}`},c.id))})}),e.jsx(ve,{settingsItem:"git.gitmoji",checked:t,onChange:c=>{d(c)},label:"Enable Gitmoji Picker",ariaLabel:"Enable Gitmoji picker"}),e.jsx(ve,{settingsItem:"git.gitignored-files",checked:n,onChange:Dr,label:"Display Gitignored Files",ariaLabel:"Display gitignored files"})]})})},Ha=[{key:"keyword",label:"Green",cssVar:"var(--syntax-keyword)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"string",label:"Cyan",cssVar:"var(--syntax-string)"},{key:"function",label:"Orange",cssVar:"var(--syntax-function)"},{key:"type",label:"Yellow",cssVar:"var(--syntax-type)"}],Ho=[{key:"branch",Icon:"git-branch",label:"Branch"},{key:"briefcase",Icon:"briefcase",label:"Work"},{key:"house",Icon:"home",label:"Personal"},{key:"graduation",Icon:"graduation-cap",label:"School"},{key:"code",Icon:"code",label:"Code"}],Ko=({open:t,onOpenChange:s,profileId:n,importData:i})=>{const o=Vt(M=>M.getProfileById),p=Vt(M=>M.createProfile),h=Vt(M=>M.updateProfile),u=Vt(M=>M.deleteProfile),d=a.useMemo(()=>n&&n!=="new"&&!i?o(n):null,[n,o,i]),w=n==="new"||i!=null,c=n==="global",[g,r]=a.useState(""),[f,y]=a.useState(""),[b,j]=a.useState(""),[A,I]=a.useState("ssh"),[P,E]=a.useState(""),[N,x]=a.useState(!1),[D,k]=a.useState(""),[m,v]=a.useState(""),[C,L]=a.useState("keyword"),[B,q]=a.useState("branch"),[Y,$]=a.useState(!1),[V,oe]=a.useState(!1),[xe,je]=a.useState(!1);a.useEffect(()=>{if(t){if(i){const M=i.host.split("/"),W=M.length>=3?M[M.length-1]:i.host;r(W),y(i.username),j(""),I("token"),E(""),x(!1),k(""),v(i.host),L("string"),q("code")}else if(w)r(""),y(""),j(""),I("ssh"),E(""),x(!1),k(""),v(""),L("keyword"),q("branch");else if(d)r(d.name),y(d.userName),j(d.userEmail),I(d.authType||"ssh"),E(d.sshKey||""),x(d.signCommits===!0),k(d.signingKey||""),v(d.host||""),L(d.color||"keyword"),q(d.icon||"branch");else if(c){const M=o("global");M&&(r(M.name),y(M.userName),j(M.userEmail),I(M.authType||"ssh"),E(M.sshKey||""),x(!1),k(""),v(M.host||""),L(M.color||"keyword"),q(M.icon||"branch"))}}},[t,n,d,w,i,c,o]);const z=async()=>{if(!f.trim()||!b.trim()){F.error("User name and email are required");return}if(A==="token"&&!m.trim()){F.error("Host is required for token-based authentication");return}if(N&&!D.trim()){F.error("Signing key is required when commit signing is enabled");return}$(!0);try{const M={name:g.trim()||f.trim(),userName:f.trim(),userEmail:b.trim(),authType:A,sshKey:A==="ssh"&&P.trim()||null,signCommits:N,signingKey:D.trim()||null,host:A==="token"&&m.trim()||null,color:C,icon:B};let W;if(w)W=await p(M);else if(n)W=await h(n,M);else return;W?(F.success(w?"Profile created":"Profile updated"),s(!1)):F.error(w?"Failed to create profile":"Failed to update profile")}catch(M){console.error("Error saving profile:",M),F.error("An error occurred while saving")}finally{$(!1)}},O=async()=>{if(!(!n||w)){je(!0);try{await u(n)?(F.success("Profile deleted"),oe(!1),s(!1)):F.error("Failed to delete profile")}catch(M){console.error("Error deleting profile:",M),F.error("An error occurred while deleting")}finally{je(!1)}}},X=a.useMemo(()=>Ha.find(W=>W.key===C)?.cssVar||"var(--syntax-keyword)",[C]),H=i?"Import Credential":w?"New Identity":c?"Global Identity":d?.name||"Edit Identity";return e.jsxs(e.Fragment,{children:[e.jsx(lt,{open:t,onOpenChange:s,children:e.jsxs(ct,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:H}),e.jsx(mt,{children:c?"System-wide Git identity (read-only)":w?"Create a new Git identity profile":"Edit identity profile settings"})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[!c&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:`${He} block mb-1.5`,children:"Profile Name"}),e.jsx(ie,{value:g,onChange:M=>r(M.target.value),placeholder:"Work Profile, Personal, etc.",className:"h-8"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-1.5",children:Ha.map(M=>e.jsx("button",{type:"button",onClick:()=>L(M.key),className:J("w-6 h-6 rounded-md border-2 transition-all cursor-pointer",C===M.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:M.cssVar},title:M.label},M.key))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5",children:Ho.map(M=>{const W=M.Icon;return e.jsx("button",{type:"button",onClick:()=>q(M.key),className:J("w-7 h-7 rounded-md border-2 transition-all flex items-center justify-center cursor-pointer",B===M.key?"border-[var(--interactive-border)] bg-[var(--surface-muted)]":"border-transparent hover:border-[var(--interactive-border)] hover:bg-[var(--surface-muted)]/50"),title:M.label,children:e.jsx(T,{name:W,className:"w-3.5 h-3.5",style:{color:B===M.key?X:"var(--surface-muted-foreground)"}})},M.key)})})]})]}),!c&&e.jsx("div",{className:"border-t border-border/40"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:He,children:"User Name"}),!c&&e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(vt,{contentClassName:"max-w-xs",children:"The name that will appear in Git commit messages."})]}),e.jsx(ie,{value:f,onChange:M=>y(M.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c,className:"h-8"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:He,children:"Email Address"}),!c&&e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(vt,{contentClassName:"max-w-xs",children:"Should match your email in GitHub/GitLab for proper attribution."})]}),e.jsx(ie,{type:"email",value:b,onChange:M=>j(M.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c,className:"h-8"})]})]}),!c&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border/40"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"Auth Method"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(S,{size:"sm",type:"button",variant:"chip","aria-pressed":A==="ssh",onClick:()=>I("ssh"),children:[e.jsx(T,{name:"lock-2",className:"w-3.5 h-3.5 mr-1"})," SSH"]}),e.jsxs(S,{size:"sm",type:"button",variant:"chip","aria-pressed":A==="token",onClick:()=>I("token"),children:[e.jsx(T,{name:"key",className:"w-3.5 h-3.5 mr-1"})," ","Token"]})]})]}),A==="ssh"&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:He,children:"SSH Key Path"}),e.jsx(vt,{contentClassName:"max-w-xs",children:"Optional path to private key. e.g. ~/.ssh/id_ed25519"})]}),e.jsx(ie,{value:P,onChange:M=>E(M.target.value),placeholder:"~/.ssh/id_ed25519",className:"h-8 font-mono text-xs"})]}),e.jsxs("div",{className:"border-t border-border/40 pt-3 space-y-3",children:[e.jsx(ve,{checked:N,onChange:x,label:"Sign commits with this identity",info:"Commit signing",ariaLabel:"Sign commits with this identity"}),e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsx("label",{className:He,children:"Signing key"})}),e.jsx(ie,{value:D,onChange:M=>k(M.target.value),placeholder:"~/.ssh/id_ed25519.pub",disabled:!N,className:"h-8 font-mono text-xs"})]})]}),A==="token"&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:He,children:"Host"}),e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(vt,{contentClassName:"max-w-xs",children:"Token will be read from ~/.git-credentials for this host."})]}),e.jsx(ie,{value:m,onChange:M=>v(M.target.value),placeholder:"github.com",required:!0,className:"h-8 font-mono text-xs"})]})]})]})]}),e.jsxs(Ot,{className:"gap-2",children:[!c&&!w&&e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>oe(!0),className:"text-[var(--status-error)] hover:text-[var(--status-error)] border-[var(--status-error)]/30 hover:bg-[var(--status-error)]/10 mr-auto",children:[e.jsx(T,{name:"delete-bin",className:"w-3.5 h-3.5 mr-1"})," ","Delete"]}),e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>s(!1),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:c?"Close":"Cancel"}),!c&&e.jsx(S,{size:"sm",onClick:z,disabled:Y,children:Y?"Saving...":w?"Create":"Save"})]})]})}),e.jsx(lt,{open:V,onOpenChange:M=>{xe||oe(M)},children:e.jsxs(ct,{className:"max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Delete Profile"}),e.jsx(mt,{children:`Are you sure you want to delete \\"${d?.name||g}\\"?`})]}),e.jsxs(Ot,{children:[e.jsx(S,{variant:"ghost",onClick:()=>oe(!1),disabled:xe,children:"Cancel"}),e.jsx(S,{size:"sm",variant:"destructive",onClick:()=>{O()},disabled:xe,children:"Delete"})]})]})})]})},$o={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart"},Go={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Wo=()=>{const{isMobile:t}=Ve(),{profiles:s,globalIdentity:n,defaultGitIdentityId:i,deleteProfile:o,loadProfiles:p,loadGlobalIdentity:h,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:d,setDefaultGitIdentityId:w,getUnimportedCredentials:c}=Vt(vn(m=>({profiles:m.profiles,globalIdentity:m.globalIdentity,defaultGitIdentityId:m.defaultGitIdentityId,deleteProfile:m.deleteProfile,loadProfiles:m.loadProfiles,loadGlobalIdentity:m.loadGlobalIdentity,loadDiscoveredCredentials:m.loadDiscoveredCredentials,loadDefaultGitIdentityId:m.loadDefaultGitIdentityId,setDefaultGitIdentityId:m.setDefaultGitIdentityId,getUnimportedCredentials:m.getUnimportedCredentials}))),[g,r]=a.useState(!1),[f,y]=a.useState(null),[b,j]=a.useState(null),[A,I]=a.useState(null),[P,E]=a.useState(!1);a.useEffect(()=>{p(),h(),u(),d()},[p,h,u,d]);const N=c(),x=(m,v)=>{y(m),j(v??null),r(!0)},D=async m=>{const v=i===m?null:m;if(!await w(v)){F.error("Failed to update default identity");return}F.success(v?"Default identity updated":"Default identity unset")},k=async()=>{if(!A)return;E(!0),await o(A.id)?(F.success(`Profile \\"${A.name}\\" deleted`),I(null)):F.error("Failed to delete profile"),E(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{title:t?void 0:"Git",children:[e.jsx(te,{title:"Identities",headerAction:e.jsxs(S,{size:"sm",variant:"outline",onClick:()=>x("new"),children:[e.jsx(T,{name:"add",className:"w-3.5 h-3.5 mr-1"})," ","New"]}),settingsItem:"git.identities",children:e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",children:[n&&e.jsx(Ka,{profile:n,isDefault:i==="global",onEdit:()=>x("global"),onToggleDefault:()=>D("global"),isReadOnly:!0,hasBorder:s.length>0||N.length>0}),s.map((m,v)=>e.jsx(Ka,{profile:m,isDefault:i===m.id,onEdit:()=>x(m.id),onToggleDefault:()=>D(m.id),onDelete:()=>I(m),hasBorder:v<s.length-1||N.length>0},m.id)),!n&&s.length===0&&N.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground",children:[e.jsx(T,{name:"shield-keyhole",className:"mx-auto mb-2 h-8 w-8 opacity-40"}),e.jsx("p",{className:"typography-ui-label",children:"No identities configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Create one to manage Git author settings per project"})]}),N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 border-t border-[var(--surface-subtle)]",children:e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Found in ~/.git-credentials"})}),N.map((m,v)=>e.jsx(Vo,{credential:m,onImport:()=>x("new",{host:m.host,username:m.username}),hasBorder:v<N.length-1},`${m.host}-${m.username}`))]})]})}),e.jsx(pa,{})]}),e.jsx(Ko,{open:g,onOpenChange:r,profileId:f,importData:b}),e.jsx(lt,{open:A!==null,onOpenChange:m=>{P||m||I(null)},children:e.jsxs(ct,{className:"max-w-md",children:[e.jsxs(dt,{children:[e.jsx(ut,{children:"Delete Profile"}),e.jsx(mt,{children:`Are you sure you want to delete \\"${A?.name??""}\\"?`})]}),e.jsxs(Ot,{children:[e.jsx(S,{variant:"ghost",onClick:()=>I(null),disabled:P,children:"Cancel"}),e.jsx(S,{size:"sm",variant:"destructive",onClick:()=>{k()},disabled:P,children:"Delete"})]})]})})]})},Ka=({profile:t,isDefault:s,onEdit:n,onToggleDefault:i,onDelete:o,isReadOnly:p,hasBorder:h})=>{const[u,d]=a.useState(!1),w=$o[t.icon||"branch"]||"git-branch",c=Go[t.color||""],g=t.authType||"ssh",r=y=>{y.currentTarget===y.target&&(y.key!=="Enter"&&y.key!==" "||(y.preventDefault(),n()))},f=y=>e.jsxs(e.Fragment,{children:[e.jsx(y,{onClick:b=>{b.stopPropagation(),i()},children:s?"Unset default":"Set as default"}),!p&&o&&e.jsxs(y,{onClick:b=>{b.stopPropagation(),o()},className:"text-destructive focus:text-destructive",children:[e.jsx(T,{name:"delete-bin",className:"h-4 w-4 mr-px"}),"Delete"]})]});return e.jsxs(Di,{open:u,onOpenChange:d,children:[e.jsxs(Li,{render:e.jsx("div",{className:J("group flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30 cursor-pointer",h&&"border-b border-[var(--surface-subtle)]"),onClick:n,role:"button",tabIndex:0,onKeyDown:r,onContextMenu:y=>{y.preventDefault(),d(!0)}}),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(T,{name:w,className:"w-4 h-4 shrink-0",style:{color:c}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:t.name}),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:g}),s&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"}),p&&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:"system"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:g==="token"&&t.host?t.host:t.userEmail})]})]}),e.jsxs(di,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(S,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",onClick:y=>y.stopPropagation(),children:e.jsx(T,{name:"more-2",className:"h-3.5 w-3.5"})})}),e.jsx(mi,{align:"end",className:"w-fit min-w-28",children:f(pi)})]})]}),e.jsx(Ri,{className:"w-fit min-w-28",children:f(zi)})]})},Vo=({credential:t,onImport:s,hasBorder:n})=>{const i=t.host.split("/"),o=i.length>=3?i[i.length-1]:t.host,p=t.host.includes("/");return e.jsxs("div",{className:J("flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30",n&&"border-b border-[var(--surface-subtle)]"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate block",children:o}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 truncate block leading-tight",children:p?t.host:t.username})]}),e.jsxs(S,{size:"sm",variant:"ghost",onClick:s,className:"gap-1 shrink-0",children:[e.jsx(T,{name:"download",className:"h-3 w-3"}),"Import"]})]})},$a=()=>{const t=Qi();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},qo=()=>{const[t,s]=a.useState(()=>$a());return a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=[window.matchMedia("(display-mode: standalone)"),window.matchMedia("(display-mode: minimal-ui)"),window.matchMedia("(display-mode: fullscreen)"),window.matchMedia("(display-mode: window-controls-overlay)")],i=()=>{s($a())};i();for(const o of n)typeof o.addEventListener=="function"?o.addEventListener("change",i):typeof o.addListener=="function"&&o.addListener(i);return window.addEventListener("appinstalled",i),window.addEventListener("focus",i),()=>{for(const o of n)typeof o.removeEventListener=="function"?o.removeEventListener("change",i):typeof o.removeListener=="function"&&o.removeListener(i);window.removeEventListener("appinstalled",i),window.removeEventListener("focus",i)}},[]),t},Qo=[{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"}],Jo=[{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."}],Yo=[{id:"svg",label:"SVG",description:"Render diagrams as scalable graphics."},{id:"ascii",label:"ASCII",description:"Render diagrams as text blocks."}],qt="PiChamber - AI Coding Assistant",Cn=[{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."}],Sn=[{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."}],Xo=[{value:"default",label:"Old"},{value:"new",label:"New"}],aa=t=>t==="portrait"||t==="landscape"?t:"system",Zo=[{id:"markdown",label:"Markdown",description:"Render user text with markdown formatting."},{id:"plain",label:"Plain text",description:"Render user text with preserved whitespace and links."}],Pn=[{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."}],Tn=[{id:"auto",label:"Auto",description:"Use locale week start."},{id:"monday",label:"Monday"},{id:"sunday",label:"Sunday"}],el=[{id:"steer",label:"Steer"},{id:"queue",label:"Queue"}],tl=t=>t==="markdown"?"markdown":"plain",sl=[{id:"left",label:"Left"},{id:"right",label:"Right"}],al=[{id:"classic",label:"Classic"},{id:"traffic-lights",label:"Traffic lights"}],nl=({themeMode:t,setThemeMode:s,showMobileLayoutSetting:n,mobileLayoutPreference:i,onMobileLayoutPreferenceChange:o,selectedLightTheme:p,setLightThemePreference:h,lightThemes:u,selectedDarkTheme:d,setDarkThemePreference:w,darkThemes:c,formatThemeLabel:g,customThemesLoading:r,themesReloading:f,setThemesReloading:y,reloadCustomThemes:b,dockBadgeSupported:j,dockBadgeEnabled:A,setDockBadgeEnabled:I})=>e.jsxs(te,{title:"Color mode & Theme",divider:!1,children:[e.jsxs(yt,{children:[e.jsxs("div",{className:ht,children:[e.jsx(Nt,{"aria-label":"Color Mode",children:Qo.map(P=>e.jsx(Ct,{selected:t===P.value,onSelect:()=>s(P.value),label:P.label,ariaLabel:P.label},P.value))}),n&&e.jsx(js,{children:e.jsx(Me,{label:"Mobile Layout",children:e.jsx(ws,{value:i,options:Xo.map(P=>({value:P.value,label:P.label})),onChange:o,"aria-label":"Mobile Layout"})})})]}),e.jsxs("div",{className:ht,children:[e.jsx(Me,{label:"Light Theme",settingsItem:"appearance.light-theme",children:e.jsxs(_e,{value:p?.metadata.id??"",onValueChange:h,children:[e.jsx(Oe,{"aria-label":"Select light theme",size:Ke,className:Pt,children:e.jsx(Ue,{placeholder:"Select theme",children:p?g(p.metadata.name,"light"):void 0})}),e.jsx(Fe,{children:u.map(P=>e.jsx(Ee,{value:P.metadata.id,children:g(P.metadata.name,"light")},P.metadata.id))})]})}),e.jsx(Me,{label:"Dark Theme",settingsItem:"appearance.dark-theme",children:e.jsxs(_e,{value:d?.metadata.id??"",onValueChange:w,children:[e.jsx(Oe,{"aria-label":"Select dark theme",size:Ke,className:Pt,children:e.jsx(Ue,{placeholder:"Select theme",children:d?g(d.metadata.name,"dark"):void 0})}),e.jsx(Fe,{children:c.map(P=>e.jsx(Ee,{value:P.metadata.id,children:g(P.metadata.name,"dark")},P.metadata.id))})]})}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{type:"button",disabled:r||f,onClick:()=>{const P=Date.now();y(!0),b().finally(()=>{const E=Date.now()-P;if(E<500){window.setTimeout(()=>{y(!1)},500-E);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(T,{name:"restart",className:J("h-3.5 w-3.5",f&&"animate-spin")}),f?"Reloading themes...":"Reload themes"]}),e.jsx(vt,{children:"Import custom themes from ~/.config/pichamber/themes/"})]})]})]}),j&&e.jsx(js,{settingsItem:"appearance.dock-badge",children:e.jsx(ve,{checked:A,onChange:I,label:"Dock badge",info:"Show a count of chats with unseen activity on the macOS dock icon.",ariaLabel:"Dock badge"})})]}),rl=({desktopWindowControlsPosition:t,desktopWindowControlsStyle:s,hasThemeSettings:n,onWindowControlsPositionChange:i,onWindowControlsStyleChange:o})=>e.jsx(te,{title:"Window controls",info:"Choose where minimize, maximize, and close buttons appear. Defaults to the right.",divider:n,children:e.jsxs(yt,{children:[e.jsx(Me,{label:"Window controls position",settingsItem:"sessions.desktop-window-controls-position",children:e.jsx(ws,{value:t,options:sl.map(p=>({value:p.id,label:p.label})),onChange:i,"aria-label":"Window controls position"})}),e.jsx(Me,{label:"Style",settingsItem:"sessions.desktop-window-controls-style",children:e.jsx(ws,{value:s,options:al.map(p=>({value:p.id,label:p.label})),onChange:o,"aria-label":"Window controls style"})})]})}),il=({shouldShowTimeFormat:t,shouldShowWeekStart:s,timeFormatPreference:n,selectedTimeFormatLabel:i,onTimeFormatPreferenceChange:o,weekStartPreference:p,selectedWeekStartLabel:h,onWeekStartPreferenceChange:u})=>e.jsx(te,{title:"Localization",children:e.jsx(yt,{children:(t||s)&&e.jsxs("div",{className:ht,children:[t&&e.jsx(Me,{label:"Time Format",settingsItem:"appearance.time-format",children:e.jsxs(_e,{value:n,onValueChange:d=>o(d),children:[e.jsx(Oe,{"aria-label":"Select time format",size:Ke,className:Pt,children:e.jsx(Ue,{children:i})}),e.jsx(Fe,{children:Pn.map(d=>e.jsx(Ee,{value:d.id,children:d.label},d.id))})]})}),s&&e.jsx(Me,{label:"Week Starts On",settingsItem:"appearance.week-start",children:e.jsxs(_e,{value:p,onValueChange:d=>u(d),children:[e.jsx(Oe,{"aria-label":"Select week start",size:Ke,className:Pt,children:e.jsx(Ue,{children:h})}),e.jsx(Fe,{children:Tn.map(d=>e.jsx(Ee,{value:d.id,children:d.label},d.id))})]})})]})})}),ol=({showPwaInstallNameSetting:t,pwaInstallName:s,setPwaInstallName:n,onApplyPwaInstallName:i,showPwaOrientationSetting:o,pwaOrientation:p,selectedPwaOrientationLabel:h,onApplyPwaOrientation:u,showMobileKeyboardModeSetting:d,mobileKeyboardMode:w,selectedMobileKeyboardModeLabel:c,onSetMobileKeyboardMode:g})=>e.jsxs(te,{title:"App install",contentClassName:ht,children:[t&&e.jsxs(ze,{label:"Install App Name",info:"Used by PWA installation process.",settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:St,children:[e.jsx(ie,{value:s,onChange:r=>n(r.target.value),onBlur:()=>{i(s)},onKeyDown:r=>{r.key==="Enter"&&(r.preventDefault(),i(s))},className:"min-w-0 flex-1",maxLength:64,"aria-label":"PWA install app name"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{n(qt),i("")},className:Ge,"aria-label":"Reset install app name",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]}),o&&e.jsxs(ze,{label:"Install Orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:St,children:[e.jsxs(_e,{value:p,onValueChange:r=>{const f=aa(r);u(f)},children:[e.jsx(Oe,{"aria-label":"PWA install orientation",size:Ke,className:za,children:e.jsx(Ue,{placeholder:"Select orientation",children:h})}),e.jsx(Fe,{children:Cn.map(r=>e.jsx(Ee,{value:r.id,children:r.label},r.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{u("system")},disabled:p==="system",className:Ge,"aria-label":"Reset install orientation",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]}),d&&e.jsxs(ze,{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:St,children:[e.jsxs(_e,{value:w,onValueChange:r=>{const f=nn(r);g(f)},children:[e.jsx(Oe,{"aria-label":"Mobile keyboard behavior",size:Ke,className:za,children:e.jsx(Ue,{placeholder:"Select keyboard behavior",children:c})}),e.jsx(Fe,{children:Sn.map(r=>e.jsx(Ee,{value:r.id,children:r.label},r.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{g("native")},disabled:w==="native",className:Ge,"aria-label":"Reset mobile keyboard behavior",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})]});function Ga(t,s,n){return Math.min(n,Math.max(s,t))}function ll(t){if(!Number.isFinite(t))return 0;const s=String(t);if(s.includes("e-")){const[,i]=s.split("e-");return Number(i)||0}const n=s.split(".");return n.length===2?n[1].length:0}function Wa(t,s){const n=ll(s);return n<=0?t:Number(t.toFixed(n))}const xt=ge.forwardRef(({value:t,onValueChange:s,min:n=-1/0,max:i=1/0,step:o=1,className:p,containerClassName:h,onBlur:u,disabled:d,fallbackValue:w,onClear:c,emptyLabel:g="—",...r},f)=>{const[y,b]=ge.useState(()=>t==null?"":String(t)),{isMobile:j}=Ve(),A=ge.useRef(!1),I=ge.useRef(null),P=ge.useCallback(()=>{if(typeof document>"u"||typeof window>"u")return;I.current?.();const Y=oe=>{oe.preventDefault(),oe.stopPropagation(),oe.stopImmediatePropagation?.(),I.current?.()},$=window.setTimeout(()=>{I.current?.()},700),V=()=>{window.clearTimeout($),document.removeEventListener("click",Y,!0),I.current=null};I.current=V,document.addEventListener("click",Y,!0)},[]);ge.useEffect(()=>()=>{I.current?.()},[]),ge.useEffect(()=>{b(t==null?"":String(t))},[t]);const E=ge.useMemo(()=>t!==void 0?t:w!==void 0?w:Number.isFinite(n)?n:0,[w,n,t]),N=ge.useRef(E);ge.useEffect(()=>{N.current=E},[E]);const x=ge.useCallback(Y=>{const $=Ga(Y,n,i),V=Wa($,o);N.current=V,s(V)},[i,n,s,o]),D=ge.useCallback(Y=>{const $=Y.target.value;if(b($),$.trim()===""){c?.();return}const V=Number($);Number.isFinite(V)&&x(V)},[x,c]),k=ge.useCallback(Y=>{if(y.trim()===""){c||b(t==null?"":String(t)),u?.(Y);return}const $=Number(y);if(!Number.isFinite($))b(t==null?"":String(t));else{const V=Ga($,n,i),oe=Wa(V,o);oe!==t?x($):N.current=oe,b(String(oe))}u?.(Y)},[x,y,i,n,u,c,o,t]),m=!!(d||E>=i),v=!!(d||E<=n),C=()=>{v||x(N.current-o)},L=()=>{m||x(N.current+o)},B=Y=>$=>{$.preventDefault(),$.stopPropagation(),A.current=!0,P(),Y()},q=Y=>$=>{if(A.current){A.current=!1,$.preventDefault(),$.stopPropagation();return}Y()};return j?e.jsxs("div",{className:J("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",h),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:v,onTouchStart:B(C),onClick:q(C),className:J("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",!v&&"active:bg-interactive-hover"),children:e.jsx(T,{name:"subtract",className:"block h-4 w-4"})}),e.jsx("div",{className:J("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]",p),"aria-live":"polite",children:t==null?g:y}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:m,onTouchStart:B(L),onClick:q(L),className:J("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",!m&&"active:bg-interactive-hover"),children:e.jsx(T,{name:"add",className:"block h-4 w-4"})})]}):e.jsxs("div",{className:J("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",h),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:v,onClick:()=>x(N.current-o),className:J("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(T,{name:"subtract",className:"block h-3.5 w-3.5"})}),e.jsx("input",{...r,ref:f,type:"text",inputMode:r.inputMode??"numeric",value:y,onChange:D,onBlur:k,disabled:d,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:J("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",p)}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:m,onClick:()=>x(N.current+o),className:J("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(T,{name:"add",className:"block h-3.5 w-3.5"})})]})});xt.displayName="NumberInput";const cl=({shouldShow:t,uiFont:s,setUiFont:n,monoFont:i,setMonoFont:o,fontSize:p,setFontSize:h,terminalFontSize:u,setTerminalFontSize:d,editorFontSize:w,setEditorFontSize:c,padding:g,setPadding:r,inputBarOffset:f,setInputBarOffset:y,isMobile:b})=>e.jsxs(te,{title:"Density & type",contentClassName:ht,children:[t("fontSize")||t("terminalFontSize")?e.jsxs(yt,{children:[t("fontSize")&&e.jsxs(Me,{label:"Interface Font",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[e.jsxs(_e,{value:s,onValueChange:j=>n(j),children:[e.jsx(Oe,{"aria-label":"Select interface font",size:Ke,className:Pt,children:e.jsx(Ue,{children:wa.find(j=>j.id===s)?.label})}),e.jsx(Fe,{children:wa.map(j=>e.jsx(Ee,{value:j.id,children:e.jsx("span",{style:{fontFamily:j.stack},children:j.label})},j.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>n(ka),disabled:s===ka,className:Ge,"aria-label":"Reset interface font",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]}),t("terminalFontSize")&&e.jsxs(Me,{label:"Code Font",controlClassName:"w-full",children:[e.jsxs(_e,{value:i,onValueChange:j=>o(j),children:[e.jsx(Oe,{"aria-label":"Select code font",size:Ke,className:Pt,children:e.jsx(Ue,{children:Na.find(j=>j.id===i)?.label})}),e.jsx(Fe,{children:Na.map(j=>e.jsx(Ee,{value:j.id,children:e.jsx("span",{style:{fontFamily:j.stack},children:j.label})},j.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>o(Ca),disabled:i===Ca,className:Ge,"aria-label":"Reset code font",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,t("fontSize")||t("terminalFontSize")||t("editorFontSize")?e.jsxs(yt,{children:[t("fontSize")&&e.jsx(Me,{label:"Interface Font Size",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(xt,{value:p,onValueChange:h,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx("span",{className:Rt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>h(100),disabled:p===100,className:Ge,"aria-label":"Reset font size",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("terminalFontSize")&&e.jsx(Me,{label:"Terminal Font Size",settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(xt,{value:u,onValueChange:d,min:9,max:52,step:1}),e.jsx("span",{className:Rt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>d(13),disabled:u===13,className:Ge,"aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("editorFontSize")&&e.jsx(Me,{label:"Editor Font Size",settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(xt,{value:w,onValueChange:c,min:9,max:32,step:1}),e.jsx("span",{className:Rt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>c(13),disabled:w===13,className:Ge,"aria-label":"Reset editor font size",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,t("spacing")||t("inputBarOffset")&&b?e.jsxs(yt,{children:[t("spacing")&&e.jsx(Me,{label:"Spacing Density",settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(xt,{value:g,onValueChange:r,min:50,max:200,step:5}),e.jsx("span",{className:Rt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>r(100),disabled:g===100,className:Ge,"aria-label":"Reset spacing",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("inputBarOffset")&&b&&e.jsx(Me,{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:Lt,children:[e.jsx(xt,{value:f,onValueChange:y,min:0,max:100,step:5}),e.jsx("span",{className:Rt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>y(0),disabled:f===0,className:Ge,"aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),dl=({shouldShow:t,fileEditorKeymap:s,setFileEditorKeymap:n,autoSaveEnabled:i,setAutoSaveEnabled:o,expandedEditorToolbar:p,onExpandedEditorToolbarChange:h,showTerminalQuickKeysOnDesktop:u,setShowTerminalQuickKeysOnDesktop:d,showTerminalShellSetting:w,terminalShell:c,setTerminalShell:g,terminalShellOptions:r,terminalShellSupportsLogin:f,terminalLoginShellEnabled:y,setTerminalLoginShellEnabled:b})=>e.jsxs(te,{title:"Navigation",contentClassName:"space-y-4",children:[t("fileEditorKeymap")&&e.jsx(_t,{title:"File editor keymap",settingsItem:"appearance.file-editor-keymap",children:e.jsx(Nt,{"aria-label":"File editor keymap",children:["default","vim"].map(j=>e.jsx(Ct,{selected:s===j,onSelect:()=>n(j),label:j==="default"?"Default":"Vim",ariaLabel:j==="default"?"Default":"Vim"},j))})}),e.jsxs("div",{className:We,children:[t("autoSaveEnabled")&&e.jsx(ve,{checked:i,onChange:o,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(ve,{checked:p,onChange:h,label:"Always show editor toolbar (docked under the file tabs)",ariaLabel:"Always show editor toolbar",settingsItem:"appearance.expanded-editor-toolbar"}),t("terminalQuickKeys")&&e.jsx(ve,{checked:u,onChange:d,label:"Terminal Quick Keys",ariaLabel:"Terminal quick keys",settingsItem:"appearance.terminal-quick-keys",info:"Show Esc, Ctrl, Arrows in terminal view"}),w&&e.jsx(Me,{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:c,onValueChange:j=>{Lr(j)&&g(j)},children:[e.jsx(Oe,{"aria-label":"Select terminal shell",size:Ke,className:Pt,children:e.jsx(Ue,{})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:"auto",children:"Auto"}),r.map(j=>e.jsx(Ee,{value:j.id,children:j.name},j.id))]})]})}),w&&f&&e.jsx(ve,{checked:y,onChange:b,label:"Start as login shell",ariaLabel:"Start as login shell",settingsItem:"appearance.terminal-login-shell"})]})]}),ul=({hasBehaviorSettings:t,showBehaviorMessageOptions:s,behaviorSectionDivider:n,showBehaviorFeatureCheckboxes:i,shouldShow:o,userMessageRenderingMode:p,onUserMessageRenderingModeChange:h,mermaidRenderingMode:u,onMermaidRenderingModeChange:d,diffLayoutPreference:w,setDiffLayoutPreference:c,followUpBehavior:g,setFollowUpBehavior:r,showExpandedBashTools:f,onShowExpandedBashToolsChange:y,showExpandedEditTools:b,onShowExpandedEditToolsChange:j,draftStartersVisible:A,onDraftStartersVisibleChange:I,showReasoningTraces:P,onShowReasoningTracesChange:E,collapsibleThinkingBlocks:N,onCollapsibleThinkingBlocksChange:x,collapseThinkingByDefault:D,onCollapseThinkingByDefaultChange:k,collapsibleUserMessages:m,onCollapsibleUserMessagesChange:v,stickyUserHeader:C,onStickyUserHeaderChange:L,promptNavigatorEnabled:B,onPromptNavigatorEnabledChange:q,wideChatLayoutEnabled:Y,onWideChatLayoutChange:$,showSplitAssistantMessageActions:V,onShowSplitAssistantMessageActionsChange:oe,codeBlockLineWrap:xe,setCodeBlockLineWrap:je,showToolFileIcons:z,onShowToolFileIconsChange:O,showTurnChangedFiles:X,onShowTurnChangedFilesChange:H,directoryShowHidden:M,setDirectoryShowHidden:W,settingsDefaultFileViewerPreview:se,onFileViewerPreviewChange:ye,persistChatDraft:K,setPersistChatDraft:re,inputSpellcheckEnabled:fe,onInputSpellcheckChange:be})=>t?e.jsxs(e.Fragment,{children:[s&&e.jsx(te,{title:"Message options",divider:n,children:e.jsxs(yt,{className:"lg:gap-y-6",children:[o("userMessageRendering")&&e.jsx(_t,{title:"User Message Rendering",children:e.jsx(Nt,{"aria-label":"User message rendering mode",children:Zo.map(pe=>e.jsx(Ct,{selected:tl(p)===pe.id,onSelect:()=>h(pe.id),label:pe.label,ariaLabel:`User message rendering: ${pe.label}`},pe.id))})}),o("mermaidRendering")&&e.jsx(_t,{title:"Mermaid Rendering",children:e.jsx(Nt,{"aria-label":"Mermaid rendering mode",children:Yo.map(pe=>e.jsx(Ct,{selected:u===pe.id,onSelect:()=>d(pe.id),label:pe.label,ariaLabel:`Mermaid rendering: ${pe.label}`},pe.id))})}),o("diffLayout")&&e.jsx(_t,{title:"Diff Layout",children:e.jsx(Nt,{"aria-label":"Diff layout",children:Jo.map(pe=>e.jsx(Ct,{selected:w===pe.id,onSelect:()=>c(pe.id),label:pe.label,ariaLabel:`Diff layout: ${pe.label}`},pe.id))})}),o("followUpBehavior")&&e.jsx(_t,{title:"Follow-up behavior",settingsItem:"chat.follow-up-behavior",children:e.jsx(Nt,{"aria-label":"Follow-up behavior",children:el.map(pe=>e.jsx(Ct,{selected:g===pe.id,onSelect:()=>r(pe.id),label:pe.label,ariaLabel:`Follow-up behavior: ${pe.label}`},pe.id))})})]})}),i&&e.jsxs(e.Fragment,{children:[o("expandedTools")&&e.jsxs(te,{title:"Show tools opened by default",divider:s||n,contentClassName:We,children:[e.jsx(ve,{checked:f,onChange:y,label:"Bash",ariaLabel:"Show expanded bash tools"}),e.jsx(ve,{checked:b,onChange:j,label:"Edit tools",ariaLabel:"Show expanded edit tools"})]}),e.jsx(te,{title:"Features",contentClassName:We,children:e.jsx(ve,{checked:A,onChange:I,label:"Show Starters on New Session Screen",ariaLabel:"Show starters on the new session screen",settingsItem:"chat.draft-starters-visible"})}),o("reasoning")&&e.jsxs(te,{title:"Reasoning",settingsItem:"chat.reasoning",contentClassName:We,children:[e.jsx(ve,{checked:P,onChange:E,label:"Show Reasoning Traces",ariaLabel:"Show reasoning traces",settingsItem:"chat.reasoning-traces"}),P&&e.jsx(ve,{checked:N,onChange:x,label:"Enable Collapsible Reasoning Blocks",ariaLabel:"Enable collapsible reasoning blocks",settingsItem:"chat.collapsible-reasoning"}),P&&N&&e.jsx(ve,{checked:D,onChange:k,label:"Collapsed by Default",ariaLabel:"Collapse reasoning blocks by default",info:"Thinking still opens while it streams, then folds when that block finishes. Turn this off to keep a one-line trace unless you expand it.",settingsItem:"chat.collapsed-reasoning-default"})]}),(o("collapsibleUserMessages")||o("stickyUserHeader")||o("promptNavigatorEnabled")||o("wideChatLayout")||o("splitAssistantMessageActions")||o("codeBlockLineWrap"))&&e.jsxs(te,{title:"Message Appearance",settingsItem:"chat.message-appearance",contentClassName:We,children:[o("collapsibleUserMessages")&&e.jsx(ve,{checked:m,onChange:v,label:"Collapse Long User Messages",ariaLabel:"Collapse long user messages",settingsItem:"chat.collapsible-user-messages"}),o("stickyUserHeader")&&e.jsx(ve,{checked:C,onChange:L,label:"Sticky User Header",ariaLabel:"Sticky user header",settingsItem:"chat.sticky-user-header"}),o("promptNavigatorEnabled")&&e.jsx(ve,{checked:B,onChange:q,label:"Prompt Navigator",ariaLabel:"Prompt navigator",settingsItem:"chat.prompt-navigator"}),o("wideChatLayout")&&e.jsx(ve,{checked:Y,onChange:$,label:"Wide Chat Layout",ariaLabel:"Wide chat layout",settingsItem:"chat.wide-layout"}),o("splitAssistantMessageActions")&&e.jsx(ve,{checked:V,onChange:oe,label:"Inline Assistant Actions",ariaLabel:"Inline assistant actions",settingsItem:"chat.inline-assistant-actions",info:"Show Copy Answer, Save as image, and Read aloud on assistant text blocks that appear before later tool calls in the same response."}),o("codeBlockLineWrap")&&e.jsx(ve,{checked:xe,onChange:je,label:"Wrap Code Block Lines",ariaLabel:"Wrap code block lines",settingsItem:"chat.code-block-line-wrap"})]}),(o("showToolFileIcons")||o("showTurnChangedFiles")||o("dotfiles")||o("fileViewerPreview"))&&e.jsxs(te,{title:"Tools & Files",settingsItem:"chat.tools-and-files",contentClassName:We,children:[o("showToolFileIcons")&&e.jsx(ve,{checked:z,onChange:O,label:"Show Tool File Icons",ariaLabel:"Show tool file icons",settingsItem:"chat.tool-file-icons"}),o("showTurnChangedFiles")&&e.jsx(ve,{checked:X,onChange:H,label:"Show Changed Files for Completed Turns",ariaLabel:"Show changed files for completed turns",settingsItem:"chat.changed-files"}),o("dotfiles")&&e.jsx(ve,{checked:M,onChange:W,label:"Show Dotfiles",ariaLabel:"Show dotfiles",settingsItem:"chat.dotfiles"}),o("fileViewerPreview")&&e.jsx(ve,{checked:se,onChange:ye,label:"Open previewable files in preview mode",ariaLabel:"Open previewable files in preview mode"})]}),(o("persistDraft")||o("inputSpellcheck"))&&e.jsxs(te,{title:"Composer",settingsItem:"chat.composer",contentClassName:We,children:[o("persistDraft")&&e.jsx(ve,{checked:K,onChange:re,label:"Persist Draft Messages",ariaLabel:"Persist draft messages",settingsItem:"chat.persist-drafts"}),o("inputSpellcheck")&&e.jsx(ve,{checked:fe,onChange:be,label:"Enable Spellcheck in Text Inputs",ariaLabel:"Enable spellcheck in text inputs",settingsItem:"chat.spellcheck"})]})]})]}):null,ml=({perfHudEnabled:t,onPerfHudEnabledChange:s})=>e.jsx(te,{title:"Diagnostics",children:e.jsx(ve,{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"})}),Ps=({visibleSettings:t})=>{const{isMobile:s}=Ve(),{terminal:n}=ln(),{browserTab:i}=qo(),o=Rr(),p=_(l=>l.showReasoningTraces),h=_(l=>l.setShowReasoningTraces),u=_(l=>l.collapsibleThinkingBlocks),d=_(l=>l.setCollapsibleThinkingBlocks),w=_(l=>l.collapseThinkingByDefault),c=_(l=>l.setCollapseThinkingByDefault),g=_(l=>l.mermaidRenderingMode),r=_(l=>l.setMermaidRenderingMode),f=_(l=>l.userMessageRenderingMode),y=_(l=>l.setUserMessageRenderingMode),b=_(l=>l.collapsibleUserMessages),j=_(l=>l.setCollapsibleUserMessages),A=_(l=>l.stickyUserHeader),I=_(l=>l.promptNavigatorEnabled),P=_(l=>l.setStickyUserHeader),E=_(l=>l.setPromptNavigatorEnabled),N=_(l=>l.expandedEditorToolbar),x=_(l=>l.setExpandedEditorToolbar),D=_(l=>l.autoSaveEnabled),k=_(l=>l.setAutoSaveEnabled),m=_(l=>l.wideChatLayoutEnabled),v=_(l=>l.setWideChatLayoutEnabled),C=_(l=>l.codeBlockLineWrap),L=_(l=>l.setCodeBlockLineWrap),B=_(l=>l.fontSize),q=_(l=>l.setFontSize),Y=_(l=>l.terminalFontSize),$=_(l=>l.setTerminalFontSize),V=_(l=>l.terminalShell),oe=_(l=>l.setTerminalShell),xe=_(l=>l.terminalLoginShells),je=_(l=>l.setTerminalLoginShells),z=_(l=>l.editorFontSize),O=_(l=>l.setEditorFontSize),X=_(l=>l.uiFont),H=_(l=>l.setUiFont),M=_(l=>l.monoFont),W=_(l=>l.setMonoFont),se=_(l=>l.padding),ye=_(l=>l.setPadding),K=_(l=>l.inputBarOffset),re=_(l=>l.setInputBarOffset),fe=_(l=>l.mobileKeyboardMode),be=_(l=>l.setMobileKeyboardMode),pe=_(l=>l.diffLayoutPreference),Q=_(l=>l.setDiffLayoutPreference),U=_(l=>l.showTerminalQuickKeysOnDesktop),ae=_(l=>l.setShowTerminalQuickKeysOnDesktop),R=_(l=>l.fileEditorKeymap),Z=_(l=>l.setFileEditorKeymap),le=Sa(l=>l.followUpBehavior),ce=Sa(l=>l.setFollowUpBehavior),G=_(l=>l.persistChatDraft),ne=_(l=>l.setPersistChatDraft),de=_(l=>l.inputSpellcheckEnabled),Ne=_(l=>l.setInputSpellcheckEnabled),me=_(l=>l.showToolFileIcons),Pe=_(l=>l.setShowToolFileIcons),Je=_(l=>l.showTurnChangedFiles),Ye=_(l=>l.setShowTurnChangedFiles),he=_(l=>l.showExpandedBashTools),De=_(l=>l.setShowExpandedBashTools),st=_(l=>l.showExpandedEditTools),qe=_(l=>l.setShowExpandedEditTools),jt=_(l=>l.timeFormatPreference),ts=_(l=>l.setTimeFormatPreference),Ft=_(l=>l.weekStartPreference),ss=_(l=>l.setWeekStartPreference),gt=_(l=>l.showSplitAssistantMessageActions),as=_(l=>l.setShowSplitAssistantMessageActions),Ts=_(l=>l.draftStartersVisible),ns=_(l=>l.setDraftStartersVisible),Is=Ae(l=>l.settingsDefaultFileViewerPreview),rs=Ae(l=>l.setSettingsDefaultFileViewerPreview),{themeMode:Bt,setThemeMode:Ht,availableThemes:Tt,customThemesLoading:Es,reloadCustomThemes:Ms,lightThemeId:Kt,darkThemeId:$t,setLightThemePreference:As,setDarkThemePreference:Ds}=hi(),[Ls,Rs]=a.useState(!1),ue=a.useMemo(()=>Re()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),Te=_(l=>l.dockBadgeEnabled),$e=_(l=>l.setDockBadgeEnabled),we=gi(),pt=_(l=>l.desktopWindowControlsPosition),Xe=_(l=>l.setDesktopWindowControlsPosition),Se=_(l=>l.desktopWindowControlsStyle),Ze=_(l=>l.setDesktopWindowControlsStyle),is=a.useSyncExternalStore(zr,_r,()=>!1),zs=a.useCallback(l=>{Xe(l),ke({desktopWindowControlsPosition:l})},[Xe]),_s=a.useCallback(l=>{Ze(l),ke({desktopWindowControlsStyle:l})},[Ze]),Os=a.useCallback(l=>{y(l),ke({userMessageRenderingMode:l})},[y]),os=a.useCallback(l=>{P(l),ke({stickyUserHeader:l})},[P]),Us=a.useCallback(l=>{E(l),ke({promptNavigatorEnabled:l})},[E]),Fs=a.useCallback(l=>{ns(l),ke({draftStartersVisible:l})},[ns]),ls=a.useCallback(l=>{x(l),ke({expandedEditorToolbar:l})},[x]),It=a.useCallback(l=>{j(l),ke({collapsibleUserMessages:l})},[j]),cs=a.useCallback(l=>{h(l),ke({showReasoningTraces:l})},[h]),Bs=a.useCallback(l=>{d(l),ke({collapsibleThinkingBlocks:l})},[d]),On=a.useCallback(l=>{c(l),ke({collapseThinkingByDefault:l})},[c]),Un=a.useCallback(l=>{v(l),ke({wideChatLayoutEnabled:l})},[v]),Fn=a.useCallback(l=>{as(l),ke({showSplitAssistantMessageActions:l})},[as]),Bn=a.useCallback(l=>{Ne(l),ke({inputSpellcheckEnabled:l})},[Ne]),Hn=a.useCallback(l=>{r(l),ke({mermaidRenderingMode:l})},[r]),Kn=a.useCallback(l=>{Pe(l),ke({showToolFileIcons:l})},[Pe]),$n=a.useCallback(l=>{Ye(l),ke({showTurnChangedFiles:l})},[Ye]),Gn=a.useCallback(l=>{rs(l),ke({defaultFileViewerPreview:l}),window.dispatchEvent(new CustomEvent("pichamber:file-viewer-preview-mode-changed",{detail:{enabled:l}}))},[rs]),Wn=a.useCallback(l=>{De(l),ke({showExpandedBashTools:l})},[De]),Vn=a.useCallback(l=>{qe(l),ke({showExpandedEditTools:l})},[qe]),qn=a.useCallback(l=>{ts(l),ke({timeFormatPreference:l})},[ts]),Qn=a.useCallback(l=>{ss(l),ke({weekStartPreference:l})},[ss]),ds=a.useMemo(()=>Tt.filter(l=>l.metadata.variant==="light").sort((l,Ce)=>l.metadata.name.localeCompare(Ce.metadata.name)),[Tt]),us=a.useMemo(()=>Tt.filter(l=>l.metadata.variant==="dark").sort((l,Ce)=>l.metadata.name.localeCompare(Ce.metadata.name)),[Tt]),Jn=a.useMemo(()=>ds.find(l=>l.metadata.id===Kt)??ds[0],[ds,Kt]),Yn=a.useMemo(()=>us.find(l=>l.metadata.id===$t)??us[0],[us,$t]),Xn=a.useCallback((l,Ce)=>{const at=Ce==="dark"?" Dark":" Light";return l.endsWith(at)?l.slice(0,-at.length):l},[]),ee=l=>t?t.includes(l):!0,ha=ee("theme"),ga=ee("windowControlsPosition")&&we,Zn=ee("theme")||ee("timeFormat")||ee("weekStart"),fa=s&&bt()&&!Re(),xa=ee("theme")||ga||fa||ee("pwaInstallName")||ee("pwaOrientation")||ee("timeFormat")||ee("weekStart"),ba=ee("fontSize")||ee("terminalFontSize")||ee("editorFontSize")||ee("spacing")||ee("inputBarOffset")&&s,va=ee("terminalQuickKeys")||ee("terminalShell")||ee("terminalLoginShell")||ee("fileEditorKeymap")||ee("autoSaveEnabled")||ee("expandedEditorToolbar"),er=ee("mermaidRendering")||ee("userMessageRendering")||ee("collapsibleUserMessages")||ee("stickyUserHeader")||ee("promptNavigatorEnabled")||ee("wideChatLayout")||ee("codeBlockLineWrap")||ee("splitAssistantMessageActions")||ee("diffLayout")||ee("dotfiles")||ee("fileViewerPreview")||ee("reasoning")||ee("followUpBehavior")||ee("persistDraft")||ee("showToolFileIcons")||ee("expandedTools")||ee("inputSpellcheck"),tr=ee("userMessageRendering")||ee("mermaidRendering")||ee("diffLayout")||ee("followUpBehavior"),sr=ee("collapsibleUserMessages")||ee("stickyUserHeader")||ee("promptNavigatorEnabled")||ee("wideChatLayout")||ee("codeBlockLineWrap")||ee("splitAssistantMessageActions")||ee("dotfiles")||ee("fileViewerPreview")||ee("persistDraft")||ee("showToolFileIcons")||ee("showTurnChangedFiles")||ee("inputSpellcheck")||ee("reasoning")||ee("expandedTools"),ar=xa||ba||va,Et=ee("pwaInstallName")&&bt()&&i&&!Re(),Mt=ee("pwaOrientation")&&bt()&&!Re(),At=ee("mobileKeyboardMode")&&bt()&&!Re()&&Or(),Hs=ee("terminalShell")||ee("terminalLoginShell"),[Ks,$s]=a.useState([]),[nr,rr]=a.useState(0);a.useEffect(()=>ia(()=>{$s([]),rr(l=>l+1)}),[]),a.useEffect(()=>{let l=!1;if(!(!Hs||!n.listShells))return n.listShells().then(Ce=>{l||$s(Ce)}).catch(()=>{l||$s([])}),()=>{l=!0}},[Hs,n,nr]);const ir=a.useMemo(()=>{const l=Ks.filter(Ce=>Ce.id!=="auto");return V==="auto"||l.some(Ce=>Ce.id===V)?l:[{id:V,name:V,supportsLogin:!1},...l]},[Ks,V]),or=Ks.find(l=>l.id===V)?.supportsLogin===!0,lr=xe.includes(V),cr=l=>{je(l?[...xe.filter(Ce=>Ce!==V),V]:xe.filter(Ce=>Ce!==V))},[Gs,dr]=a.useState(()=>Hi()),[ur,Dt]=a.useState(""),[Ws,ms]=a.useState("system"),mr=a.useMemo(()=>Pn.find(Ce=>Ce.id===jt)?.label??"Auto",[jt]),pr=a.useMemo(()=>Tn.find(Ce=>Ce.id===Ft)?.label??"Auto",[Ft]),hr=a.useMemo(()=>{const l=Cn.find(Ce=>Ce.id===Ws);return l?l.label:void 0},[Ws]),gr=a.useMemo(()=>{const l=Sn.find(Ce=>Ce.id===fe);return l?l.label:void 0},[fe]),fr=a.useCallback(l=>{l!==Gs&&(dr(l),Ki(l),window.location.reload())},[Gs]),xr=a.useCallback(async l=>{if(typeof window>"u")return;const Ce=window,nt=l.trim().replace(/\s+/g," ").slice(0,64);if(await ke({pwaAppName:nt}),typeof Ce.__PICHAMBER_SET_PWA_INSTALL_NAME__=="function"){const ya=Ce.__PICHAMBER_SET_PWA_INSTALL_NAME__(nt);Dt(ya);return}Dt(nt||qt),Ce.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),br=a.useCallback(async l=>{if(typeof window>"u")return;const Ce=window,at=aa(l);if(await ke({pwaOrientation:at}),typeof Ce.__PICHAMBER_SET_PWA_ORIENTATION__=="function"){const nt=Ce.__PICHAMBER_SET_PWA_ORIENTATION__(at);ms(nt);return}ms(at),Ce.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return a.useEffect(()=>{if(typeof window>"u"||!Et&&!Mt&&!At)return;let l=!1;return(async()=>{try{const at=await Be("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!at.ok){l||Dt(qt);return}const nt=await at.json().catch(()=>({})),vr=(typeof nt?.pwaAppName=="string"?nt.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),yr=aa(nt?.pwaOrientation),jr=nn(nt?.mobileKeyboardMode);l||(Et&&Dt(vr||qt),Mt&&ms(yr),At&&be(jr))}catch{l||(Et&&Dt(qt),Mt&&ms("system"),At&&be("native"))}})(),()=>{l=!0}},[be,At,Et,Mt]),e.jsxs(e.Fragment,{children:[xa&&e.jsxs(e.Fragment,{children:[ha&&e.jsx(nl,{themeMode:Bt,setThemeMode:Ht,showMobileLayoutSetting:fa,mobileLayoutPreference:Gs,onMobileLayoutPreferenceChange:fr,selectedLightTheme:Jn,setLightThemePreference:As,lightThemes:ds,selectedDarkTheme:Yn,setDarkThemePreference:Ds,darkThemes:us,formatThemeLabel:Xn,customThemesLoading:Es,themesReloading:Ls,setThemesReloading:Rs,reloadCustomThemes:Ms,dockBadgeSupported:ue,dockBadgeEnabled:Te,setDockBadgeEnabled:$e}),ga&&e.jsx(rl,{desktopWindowControlsPosition:pt,desktopWindowControlsStyle:Se,hasThemeSettings:ha,onWindowControlsPositionChange:zs,onWindowControlsStyleChange:_s}),Zn&&e.jsx(il,{shouldShowTimeFormat:ee("timeFormat"),shouldShowWeekStart:ee("weekStart"),timeFormatPreference:jt,selectedTimeFormatLabel:mr,onTimeFormatPreferenceChange:qn,weekStartPreference:Ft,selectedWeekStartLabel:pr,onWeekStartPreferenceChange:Qn}),(Et||Mt||At)&&e.jsx(ol,{showPwaInstallNameSetting:Et,pwaInstallName:ur,setPwaInstallName:Dt,onApplyPwaInstallName:xr,showPwaOrientationSetting:Mt,pwaOrientation:Ws,selectedPwaOrientationLabel:hr,onApplyPwaOrientation:br,showMobileKeyboardModeSetting:At,mobileKeyboardMode:fe,selectedMobileKeyboardModeLabel:gr,onSetMobileKeyboardMode:l=>{be(l),ke({mobileKeyboardMode:l})}})]}),ba&&e.jsx(cl,{shouldShow:ee,uiFont:X,setUiFont:H,monoFont:M,setMonoFont:W,fontSize:B,setFontSize:q,terminalFontSize:Y,setTerminalFontSize:$,editorFontSize:z,setEditorFontSize:O,padding:se,setPadding:ye,inputBarOffset:K,setInputBarOffset:re,isMobile:s}),va&&e.jsx(dl,{shouldShow:ee,fileEditorKeymap:R,setFileEditorKeymap:Z,autoSaveEnabled:D,setAutoSaveEnabled:k,expandedEditorToolbar:N,onExpandedEditorToolbarChange:ls,showTerminalQuickKeysOnDesktop:U,setShowTerminalQuickKeysOnDesktop:ae,showTerminalShellSetting:Hs,terminalShell:V,setTerminalShell:oe,terminalShellOptions:ir,terminalShellSupportsLogin:or,terminalLoginShellEnabled:lr,setTerminalLoginShellEnabled:cr}),e.jsx(ul,{hasBehaviorSettings:er,showBehaviorMessageOptions:tr,behaviorSectionDivider:ar,showBehaviorFeatureCheckboxes:sr,shouldShow:ee,userMessageRenderingMode:f,onUserMessageRenderingModeChange:Os,mermaidRenderingMode:g,onMermaidRenderingModeChange:Hn,diffLayoutPreference:pe,setDiffLayoutPreference:Q,followUpBehavior:le,setFollowUpBehavior:ce,showExpandedBashTools:he,onShowExpandedBashToolsChange:Wn,showExpandedEditTools:st,onShowExpandedEditToolsChange:Vn,draftStartersVisible:Ts,onDraftStartersVisibleChange:Fs,showReasoningTraces:p,onShowReasoningTracesChange:cs,collapsibleThinkingBlocks:u,onCollapsibleThinkingBlocksChange:Bs,collapseThinkingByDefault:w,onCollapseThinkingByDefaultChange:On,collapsibleUserMessages:b,onCollapsibleUserMessagesChange:It,stickyUserHeader:A,onStickyUserHeaderChange:os,promptNavigatorEnabled:I,onPromptNavigatorEnabledChange:Us,wideChatLayoutEnabled:m,onWideChatLayoutChange:Un,showSplitAssistantMessageActions:gt,onShowSplitAssistantMessageActionsChange:Fn,codeBlockLineWrap:C,setCodeBlockLineWrap:L,showToolFileIcons:me,onShowToolFileIconsChange:Kn,showTurnChangedFiles:Je,onShowTurnChangedFilesChange:$n,directoryShowHidden:o,setDirectoryShowHidden:Ur,settingsDefaultFileViewerPreview:Is,onFileViewerPreviewChange:Gn,persistChatDraft:G,setPersistChatDraft:ne,inputSpellcheckEnabled:de,onInputSpellcheckChange:Bn}),ee("perfHud")&&e.jsx(ml,{perfHudEnabled:is,onPerfHudEnabledChange:Fr})]})},pl=1,hl=365,Va=30,gl=[{value:"archive",label:"Archive"},{value:"delete",label:"Delete"}],In=()=>{const t=_(r=>r.autoDeleteEnabled),s=_(r=>r.autoDeleteAfterDays),n=_(r=>r.sessionRetentionAction),i=_(r=>r.setAutoDeleteEnabled),o=_(r=>r.setAutoDeleteAfterDays),p=_(r=>r.setSessionRetentionAction),{candidates:h,isRunning:u,runCleanup:d,action:w}=fi({autoRun:!1}),c=h.length,g=a.useCallback(async()=>{const r=await d({force:!0});if(r.completedIds.length===0&&r.failedIds.length===0){F.message(r.action==="archive"?"No sessions eligible for archiving":"No sessions eligible for deletion");return}r.completedIds.length>0&&F.success(r.action==="archive"?`Archived ${r.completedIds.length} session(s)`:`Deleted ${r.completedIds.length} session(s)`),r.failedIds.length>0&&F.error(r.action==="archive"?`Failed to archive ${r.failedIds.length} session(s)`:`Failed to delete ${r.failedIds.length} session(s)`)},[d]);return e.jsxs(te,{title:"Session Retention",info:"Automatically archive or delete inactive sessions based on last activity. Keeps the 5 most recent sessions.",children:[e.jsx(ve,{settingsItem:"sessions.auto-cleanup",checked:t,onChange:i,label:"Enable Auto-Cleanup",ariaLabel:"Enable auto-cleanup"}),e.jsxs(js,{className:"space-y-0",children:[e.jsxs(ze,{settingsItem:"sessions.retention-period",label:"Retention Period",children:[e.jsx(xt,{value:s,onValueChange:o,min:pl,max:hl,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(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>o(Va),disabled:s===Va,className:Ge,"aria-label":"Reset retention period",title:"Reset",children:e.jsx(T,{name:"restart",className:"h-3.5 w-3.5"})})]}),e.jsx(ze,{settingsItem:"sessions.retention-action",label:"When sessions expire",children:e.jsx(ws,{value:n,onChange:p,options:gl.map(r=>({value:r.value,label:r.label}))})})]}),e.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[e.jsx(ze,{label:"Manual Cleanup",children:e.jsx(S,{type:"button",variant:"outline",size:"xs",onClick:g,disabled:u,className:"!font-normal",children:u?"Cleaning up...":"Run cleanup now"})}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:w==="archive"?`Eligible for archiving right now: ${c}`:`Eligible for deletion right now: ${c}`})]})]})},qa=(t,s,n)=>!t||!Number.isFinite(t)?s:new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short",hour12:n==="auto"?void 0:n==="12h"}).format(t),En=()=>{const t=_(x=>x.timeFormatPreference),[s,n]=a.useState(!1),[i,o]=a.useState(!0),[p,h]=a.useState(!1),[u,d]=a.useState(null),[w,c]=a.useState(!1),[g,r]=a.useState([]),[f,y]=a.useState(xi),[b,j]=a.useState(""),A=a.useMemo(()=>bi(),[]),I=a.useCallback(async()=>{o(!0),j("");try{const x=await vi();r(x)}catch(x){const D=x instanceof Error?x.message:"Could not load passkeys.";j(D)}finally{o(!1)}},[]);a.useEffect(()=>{let x=!1;return(async()=>{try{if(!A.supported){x||(n(!1),o(!1));return}x||n(!0)}catch{x||n(!1)}if(!x){const D=await qs();if(y(D),!D.enabled){r([]),o(!1);return}await I()}})(),()=>{x=!0,Aa()}},[I,A.supported]);const P=a.useCallback(async()=>{if(!f.enabled){const x="Enable the UI password lock before adding passkeys.";j(x),F.message(x);return}if(!s){j(A.reason),F.message(A.reason);return}if(p){Aa(),h(!1);return}j(""),h(!0);try{await yi(),y(await qs()),await I(),F.success("Passkey added")}catch(x){if(ji(x)){F.message("Passkey setup canceled");return}const D=x instanceof Error?x.message:"Could not add passkey.";j(D),F.error(D)}finally{h(!1)}},[p,I,f.enabled,A.reason,s]),E=a.useCallback(async x=>{d(x),j("");try{await wi(x),y(await qs()),await I(),F.success("Passkey removed")}catch(D){const k=D instanceof Error?D.message:"Could not remove passkey.";j(k),F.error(k)}finally{d(null)}},[I]),N=a.useCallback(async()=>{c(!0),j("");try{await ki(),window.location.reload()}catch(x){const D=x instanceof Error?x.message:"Could not clear saved authentication.";j(D),F.error(D),c(!1)}},[]);return e.jsxs(te,{title:"Passkeys",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ze,{label:"Current device",children:[e.jsx(S,{type:"button",variant:p?"secondary":"outline",size:"xs",onClick:()=>{P()},disabled:i||w,className:"!font-normal",children:p?"Cancel passkey setup":"Add passkey"}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{N()},disabled:i||p||w,className:"!font-normal text-muted-foreground hover:text-foreground",children:w?"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:A.reason}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading passkeys…"}):g.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:g.map(x=>e.jsxs(ze,{label:e.jsx("span",{className:"truncate",children:x.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:x.lastUsedAt?`Last used ${qa(x.lastUsedAt,"Never used",t)}`:`Added ${qa(x.createdAt,"Never used",t)}`}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{E(x.id)},disabled:u===x.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:u===x.id?"Removing…":"Delete"})]},x.id))})]}),b&&e.jsx("div",{className:"mt-1 py-1.5",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:b})})]})},fl=t=>{if(!t)return;const s=t.providerId.trim(),n=t.modelId.trim();if(!(!s||!n))return`${s}/${n}`},Ys=t=>{const s=Ni(t??void 0);return s?{providerId:s.providerId,modelId:s.modelId}:null},xl=(t,s={})=>{if(!t)return{};const n={};if(!s.defaultModel){const i=Ys(typeof t.defaultModel=="string"?t.defaultModel:void 0);i&&(n.defaultModel=i)}if(!s.smallModel&&t.smallModelUseDefault===!1){const i=Ys(typeof t.smallModelOverride=="string"?t.smallModelOverride:void 0);i&&(n.smallModel=i)}if(!s.walkthroughModel){const i=Ys(typeof t.walkthroughModelOverride=="string"?t.walkthroughModelOverride:void 0);i&&(n.walkthroughModel=i)}return n},bl=t=>!!(t.defaultModel||t.smallModel||t.walkthroughModel),Xs=()=>({runtimeKey:it()}),hs="__pi_fallback__",vl=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},Mn=()=>{const t=Ae(m=>m.providers),s=Ae(m=>m.modelsMetadata),n=Ae(m=>m.loadProviders),i=Ae(m=>m.setProvider),o=Ae(m=>m.setModel),p=Ae(m=>m.setSettingsDefaultModel),h=Ae(m=>m.setSettingsDefaultThinking),u=Ae(m=>m.setSettingsDefaultThinkingByModel),d=_(m=>m.showDeletionDialog),w=_(m=>m.setShowDeletionDialog),[c,g]=a.useState(null),[r,f]=a.useState("loading"),y=a.useCallback(m=>{g(m),p(fl(m.defaultModel)),h(m.defaultThinking),u(m.defaultThinkingByModel??{})},[p,h,u]);a.useEffect(()=>{n({source:"sessionsDefaults"})},[n]),a.useEffect(()=>{let m=!0;return(async()=>{try{const C=await Le.getSettings(Xs());if(!m)return;let L=C.pichamber;if(!L.defaultModel&&!L.smallModel&&!L.walkthroughModel){const B=Yt()?.settings;if(B)try{const q=await B.load(),Y=xl(q?.settings,L);if(bl(Y)){const $=await Le.setPiChamberDefaults(Y,Xs());if(!m)return;L=$.pichamber,await ke({defaultModel:"",smallModelOverride:"",walkthroughModelOverride:""})}}catch{}}if(!m)return;y(L),f("ready")}catch{m&&f("failed")}})(),()=>{m=!1}},[y]);const b=a.useCallback(async m=>{ot("saving");try{const v=await Le.setPiChamberDefaults(m,Xs());y(v.pichamber),ot("saved")}catch{ot("error")}},[y]),j=a.useCallback((m,v)=>{const C=t.find(B=>B.id===m);return(Array.isArray(C?.models)?C.models:[]).find(B=>B.id===v)},[t]),A=a.useCallback(m=>{m&&t.find(C=>C.id===m.providerId)&&(i(m.providerId),o(m.modelId)),b({defaultModel:m})},[b,t,o,i]),I=a.useCallback((m,v)=>{const C=ys(m);C&&b({defaultThinkingByModel:{[C]:v}})},[b]),P=a.useCallback((m,v)=>s.get(`${m}/${v}`)?.structured_output!==!1,[s]);if(r==="loading")return null;if(r==="failed"&&!c)return e.jsx(te,{title:"Session Defaults",divider:!1,children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Session defaults are unavailable."})});const E=ys(c?.defaultModel),N=c?.defaultModel?j(c.defaultModel.providerId,c.defaultModel.modelId):void 0,x=dn(N),D=!!(c?.defaultModel&&un(x)),k=E?c?.defaultThinkingByModel?.[E]:void 0;return e.jsx(te,{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:ht,children:[e.jsx(ze,{settingsItem:"sessions.default-model",label:"Default Model",info:"The model new sessions start with. Unset keeps Pi's default.",children:e.jsx(Qs,{value:c?.defaultModel??null,noneLabel:"Default",ariaLabel:"Default model",onChange:A})}),D&&c?.defaultModel?e.jsx(ze,{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:k??hs,onValueChange:m=>{I(c.defaultModel,m===hs?null:m)},children:[e.jsx(Oe,{size:Ke,className:ca,"aria-label":"Default thinking",children:e.jsx(Ue,{children:m=>m===hs?"Default":m?vs[m]??m:""})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:hs,children:"Default"}),vl(x,k).map(m=>e.jsx(Ee,{value:m,children:vs[m]},m))]})]})}):null,e.jsx(ze,{settingsItem:"sessions.small-model",label:"Small Model",info:"A cheap model for quick utility tasks like short recaps and summaries.",children:e.jsx(Qs,{value:c?.smallModel??null,noneLabel:"Use default small model",ariaLabel:"Small model",onChange:m=>{b({smallModel:m})}})}),e.jsx(ze,{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(Qs,{value:c?.walkthroughModel??null,noneLabel:"Small model",ariaLabel:"Changes walkthrough model",isModelAllowed:P,onChange:m=>{b({walkthroughModel:m})}})}),e.jsx(ze,{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:St,children:e.jsxs("div",{className:Lt,children:[e.jsx(xt,{value:c?.defaultRetryLimit??3,min:0,max:10,step:1,"aria-label":"Default retry limit",onValueChange:m=>{if(!Number.isFinite(m))return;const v=Math.max(0,Math.min(10,Math.round(m)));b({defaultRetryLimit:v})}}),e.jsx("span",{className:Rt,children:"retries"})]})})}),e.jsx(js,{className:We,children:e.jsx(ve,{settingsItem:"sessions.deletion-dialog",checked:d,onChange:w,label:"Show Deletion Dialog",ariaLabel:"Show deletion dialog"})})]})})},Qa={completion:{titleKey:"{agent_name} is ready",messageKey:"{model_name} completed the task"},error:{titleKey:"Tool error",messageKey:"{last_message}"},question:{titleKey:"Input needed",messageKey:"{last_message}"},subtask:{titleKey:"{agent_name} is ready",messageKey:"{model_name} completed the task"}},yl={completion:"completion",subtask:"Subagent Completion",error:"error",question:"question"},jl=()=>{const t=a.useMemo(()=>Re(),[]),s=a.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),n=!t&&!s,i=_(z=>z.nativeNotificationsEnabled),o=_(z=>z.setNativeNotificationsEnabled),p=_(z=>z.notificationMode),h=_(z=>z.setNotificationMode),u=_(z=>z.notifyOnSubtasks),d=_(z=>z.setNotifyOnSubtasks),w=_(z=>z.notifyOnCompletion),c=_(z=>z.setNotifyOnCompletion),g=_(z=>z.notifyOnError),r=_(z=>z.setNotifyOnError),f=_(z=>z.notifyOnQuestion),y=_(z=>z.setNotifyOnQuestion),b=_(z=>z.notificationTemplates),j=_(z=>z.setNotificationTemplates),[A,I]=a.useState("default"),[P,E]=a.useState(!1),[N,x]=a.useState(!1),[D,k]=a.useState(!1);a.useEffect(()=>{if(!n){E(!1),x(!1);return}typeof Notification<"u"&&I(Notification.permission);const z=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;E(z),(async()=>{if(!z){x(!1);return}try{const X=await navigator.serviceWorker.getRegistration();if(!X){x(!1);return}const H=await X.pushManager.getSubscription();x(!!H)}catch{x(!1)}})()},[n]);const m=async z=>{if(t){o(z);return}if(!n){o(z);return}if(z&&typeof Notification<"u"&&Notification.permission==="default")try{const O=await Notification.requestPermission();I(O),O==="granted"?o(!0):F.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(O){console.error("Failed to request notification permission:",O),F.error("Failed to request notification permission")}else o(!!(z&&A==="granted"))},v=t||s||n&&typeof Notification<"u"&&Notification.permission==="granted",C=(z,O,X)=>{j(H=>({...H,[z]:{...H[z],[O]:X}}))},L=z=>{const O="=".repeat((4-z.length%4)%4),X=(z+O).replace(/-/g,"+").replace(/_/g,"/"),H=atob(X),M=new Uint8Array(H.length);for(let W=0;W<H.length;W+=1)M[W]=H.charCodeAt(W);return M},B=async(z,O,X)=>{let H=null;const M=new Promise((W,se)=>{H=setTimeout(()=>{se(new Error(X))},O)});try{return await Promise.race([z,M])}finally{H&&clearTimeout(H)}},q=async z=>{if(z.active)return;const O=z.installing||z.waiting;O&&O.state!=="activated"&&await B(new Promise(X=>{const H=()=>{O.state==="activated"&&(O.removeEventListener("statechange",H),X())};O.addEventListener("statechange",H),H()}),15e3,"Service worker activation timed out")},Y=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const z=[{label:"no-options",opts:null},{label:"scope-root",opts:{scope:"/"}},{label:"type-classic",opts:{type:"classic"}},{label:"type-classic-scope",opts:{type:"classic",scope:"/"}},{label:"updateViaCache-none",opts:{type:"classic",updateViaCache:"none",scope:"/"}}];let O=null;for(const X of z)try{const H=X.opts?navigator.serviceWorker.register("/sw.js",X.opts):navigator.serviceWorker.register("/sw.js");return await B(H,1e4,`Service worker registration timed out (${X.label})`)}catch(H){O=H}throw O instanceof Error?O:new Error("Service worker registration failed")},$=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const z=await navigator.serviceWorker.getRegistration();if(z)return z;const O=await Y();try{await O.update()}catch{}return await q(O),O},V=z=>{const O=z,X=[`type=${typeof z}`,`toString=${String(z)}`,`name=${String(O?.name??"")}`,`message=${String(O?.message??"")}`];let H="";try{H=JSON.stringify(z)}catch{}return{summary:X.filter(Boolean).join(" | "),json:H,stack:typeof O?.stack=="string"?O.stack:""}},oe=async()=>{const z=Yt();if(!z?.notifications){F.error("Notifications API not available");return}try{await z.notifications.notifyAgentCompletion({title:"Test Notification",body:"This is a test notification from PiChamber.",tag:"pichamber-test"})?F.success("Test notification sent successfully"):F.error("Failed to send test notification")}catch(O){console.error("Test notification failed:",O),F.error("Failed to send test notification")}},xe=async()=>{if(!P){F.error("Push notifications not supported");return}const z=Yt();if(!z?.push){F.error("Push API not available");return}k(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const K=await Notification.requestPermission();if(I(K),K!=="granted"){F.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){F.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const O=await z.push.getVapidPublicKey();if(!O?.publicKey){F.error("Failed to load push key");return}const X=await $();await q(X);const H=await X.pushManager.getSubscription();if(!("pushManager"in X)||!X.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const W=(H??await B(X.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:L(O.publicKey)}),15e3,"Push subscription timed out")).toJSON(),se=W.keys;if(!W.endpoint||!se?.p256dh||!se.auth)throw new Error("Push subscription missing keys");if(!(await B(z.push.subscribe({endpoint:W.endpoint,keys:{p256dh:se.p256dh,auth:se.auth},origin:typeof window<"u"?window.location.origin:void 0,platform:Br()}),15e3,"Push subscribe request timed out"))?.ok){F.error("Failed to enable background notifications");return}x(!0),F.success("Background notifications enabled")}catch(O){console.error("[Push] Enable failed:",O);const X=V(O);F.error("Failed to enable background notifications",{description:X.summary})}finally{k(!1)}},je=async()=>{if(!P){x(!1);return}const z=Yt();if(!z?.push){F.error("Push API not available");return}k(!0);try{const X=await(await $()).pushManager.getSubscription();if(!X){x(!1);return}const H=X.endpoint;await X.unsubscribe(),await z.push.unsubscribe({endpoint:H}),x(!1),F.success("Background notifications disabled")}finally{k(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(te,{settingsItem:"notifications.delivery",title:"Notification Delivery",divider:!1,children:[e.jsxs("div",{className:We,children:[e.jsx(ve,{checked:i&&v,onChange:z=>{m(z)},label:"Enable Notifications",info:n?"Your browser may ask for permission the first time.":void 0,ariaLabel:"Enable notifications"}),i&&v&&!s&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{checked:p==="always",onChange:z=>h(z?"always":"hidden-only"),label:"Notify While App is Focused",ariaLabel:"Notify while app is focused"}),e.jsx("div",{className:"py-2",children:e.jsx(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{oe()},children:"Send test notification"})})]})]}),n&&e.jsxs("div",{className:"mt-1",children:[A==="denied"&&e.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:"Notification permission denied. Enable it in your browser settings."}),A==="granted"&&!i&&e.jsx("p",{className:"typography-meta text-muted-foreground/70 mt-1",children:"Permission granted, but notifications are disabled."})]})]}),i&&v&&e.jsxs(e.Fragment,{children:[e.jsx(te,{settingsItem:"notifications.events",title:"Notification Events",children:e.jsxs("div",{className:We,children:[e.jsx(ve,{checked:w,onChange:c,label:"Agent Completion",ariaLabel:"Agent completion"}),e.jsx(ve,{checked:u,onChange:d,label:"Subagent Completion",ariaLabel:"Subagent completion"}),e.jsx(ve,{checked:g,onChange:r,label:"Agent Errors",ariaLabel:"Agent errors"}),e.jsx(ve,{checked:f,onChange:y,label:"Agent Questions",ariaLabel:"Agent questions"})]})}),!s&&e.jsx(te,{title:"Notification Templates",description:e.jsxs(e.Fragment,{children:["Variables:"," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{project_name}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{worktree}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{branch}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{session_name}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{agent_name}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{model_name}"})," ",e.jsx("code",{className:"text-[var(--primary-base)]",children:"{last_message}"})]}),children:e.jsx(yt,{className:"gap-2 md:grid-cols-2 md:gap-3 lg:gap-3",children:["completion","subtask","error","question"].map(z=>e.jsxs("section",{className:"p-2",children:[e.jsx(Cs,{className:"capitalize",children:yl[z]}),e.jsxs("div",{className:"mt-1.5 space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:"Title"}),e.jsx(ie,{value:b[z].title,onChange:O=>C(z,"title",O.target.value),className:"h-7",placeholder:Qa[z].titleKey})]}),e.jsxs("div",{children:[e.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:"Message"}),e.jsx(ie,{value:b[z].message,onChange:O=>C(z,"message",O.target.value),className:"h-7",placeholder:Qa[z].messageKey})]})]})]},z))})})]}),n&&e.jsx(te,{settingsItem:"notifications.push",title:"Background Push Notifications",children:e.jsx(ve,{checked:P?N:!1,disabled:!P||D,onChange:z=>{z?xe():je()},label:"Enable push notifications",description:P?void 0:"Push not supported. Desktop Chrome/Edge and Android support push. iOS requires an installed PWA.",info:P?"Receive alerts via your operating system background service":void 0,ariaLabel:"Enable push notifications",labelAccessory:D?e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-current text-muted-foreground animate-busy-pulse","aria-label":"Loading"}):null})})]})},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}],xs=[{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}],wl="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",kl="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",na=[{value:"quick",label:"Quick",tooltip:"Quick Tunnel is best effort and uptime is not guaranteed."},{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."}],Nl=[".yml",".yaml",".json"],Cl="Config file must use .yml, .yaml, or .json extension.",Qt=t=>{const s=t.trim().toLowerCase();return Nl.some(n=>s.endsWith(n))},Sl=()=>"cloudflared",An=()=>{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"},Pl=(t=An())=>t==="win32"?"winget install --id Cloudflare.cloudflared":t==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",Zs=(t,s)=>{const n=typeof s?.provider=="string"&&s.provider.trim().length>0?s.provider.trim().toLowerCase():t,i=typeof s?.dependency=="string"&&s.dependency.trim().length>0?s.dependency.trim():Sl(),o=typeof s?.platform=="string"&&s.platform.trim().length>0?s.platform.trim():An(),p=typeof s?.installCommand=="string"&&s.installCommand.trim().length>0?s.installCommand.trim():Pl(o);return{provider:n,dependency:i,installCommand:p}},Tl=t=>t==="cloudflare"?"Cloudflare":t,wt=t=>t==="quick"?"quick":t==="managed-remote"?"managed-remote":t==="managed-local"?"managed-local":"quick",ra=(t,s,n)=>t.find(o=>o.ms===s)?.value||n,Ja=(t,s,n)=>{const i=ra(t,s,n);return t.find(o=>o.value===i)?.label||i},Dn=t=>{const s=Math.max(0,t),n=Math.floor(s/1e3),i=Math.floor(n/3600),o=Math.floor(n%3600/60),p=n%60;return i>0?`${i}h ${o}m`:o>0?`${o}m ${p}s`:`${p}s`},Il=(t,s)=>Ci(t,s,{hour:"2-digit",precision:"second"}),Ns=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()}},El=t=>{if(!Array.isArray(t))return[];const s=new Set,n=new Set,i=[];for(const o of t){if(!o||typeof o!="object")continue;const p=o,h=typeof p.id=="string"?p.id.trim():"",u=typeof p.name=="string"?p.name.trim():"",d=Ns(typeof p.hostname=="string"?p.hostname:"");!h||!u||!d||s.has(h)||n.has(d)||(s.add(h),n.add(d),i.push({id:h,name:u,hostname:d}))}return i},Ml=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,Al=({provider:t})=>{const s=Tl(t),n=t==="cloudflare";return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(T,{name:"cloud",className:J("size-4 shrink-0",n?"text-[var(--status-warning)]":"text-muted-foreground")}),e.jsx("span",{children:s})]})},Dl=({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(T,{name:"information",className:"size-4 text-[var(--status-info)]"}),e.jsx("p",{className:xn,children:"Redeemed access links"})]}),e.jsx("div",{className:"space-y-1",children:t.map(n=>{const i=n.mode==="quick",o=n.mode==="managed-remote",p=i?"border-[var(--status-warning-border)] bg-[var(--status-warning-background)] text-[var(--status-warning)]":o?"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)]",h=n.isActive?i?"text-[var(--status-warning)]":o?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",u=i?"QUICK":o?"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(T,{name:"checkbox-blank-circle-fill",className:J("size-2.5 shrink-0",h)}),e.jsx("span",{className:J("typography-micro rounded border px-1.5 py-0.5 uppercase",p),children:u}),e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:`Redeemed ${Il(n.createdAt,s)}`}),e.jsx("span",{className:"typography-meta text-foreground",children:n.isActive?`Expires in ${n.remainingTextForSession}`:n.inactiveLabel==="Inactive"?"Inactive":`Inactive (${n.inactiveLabel})`})]},n.sessionId)})})]})}),Ll=({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(T,{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:xn,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})]})]})}),Rl=({bootstrapTtlMs:t,sessionTtlMs:s,tunnelMode:n,disabled:i,providerSupportsManagedModes:o,onBootstrapTtlChange:p,onSessionTtlChange:h})=>e.jsxs(e.Fragment,{children:[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:J(He,"shrink-0"),children:"Connect link TTL"}),e.jsxs(_e,{value:ra(fs,t,"1800000"),onValueChange:p,disabled:i,children:[e.jsx(Oe,{size:Ke,className:"max-w-[11rem] min-w-0",children:e.jsx(Ue,{className:"truncate",children:Ja(fs,t,"1800000")})}),e.jsx(Fe,{children:fs.map(u=>e.jsx(Ee,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:J(He,"shrink-0"),children:"Tunnel session TTL"}),e.jsxs(_e,{value:ra(xs,s,"28800000"),onValueChange:h,disabled:i,children:[e.jsx(Oe,{size:Ke,className:"max-w-[11rem] min-w-0",children:e.jsx(Ue,{className:"truncate",children:Ja(xs,s,"28800000")})}),e.jsx(Fe,{children:xs.map(u=>e.jsx(Ee,{value:u.value,children:u.label},u.value))})]})]})]}),n==="quick"&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning)]/35 bg-[var(--status-warning)]/10 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(T,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsxs("div",{children:[e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:"Quick Tunnel is best effort and uptime is not guaranteed."}),o&&e.jsx("p",{className:"typography-meta mt-1 text-[var(--status-warning)]",children:"For more reliable long-lived access, switch to Managed Remote or Managed Local tunnel mode."})]})]})})]}),zl=({suggestedConnectorPort:t,managedRemoteTunnelPresets:s,expandedManagedRemoteTunnels:n,sessionTokensByPresetId:i,savedTokenPresetIds:o,disabled:p,isAddingPreset:h,newPresetName:u,newPresetHostname:d,newPresetToken:w,managedRemoteValidationError:c,selectedPreset:g,onToggleAddPreset:r,onCancelAddPreset:f,onNewPresetNameChange:y,onNewPresetHostnameChange:b,onNewPresetTokenChange:j,onSaveNewPreset:A,onTogglePresetCollapse:I,onRemovePreset:P,onPresetTokenChange:E,onPersistToken:N})=>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(Cs,{children:"Saved managed remote tunnels"}),e.jsxs(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:r,disabled:p,children:[e.jsx(T,{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((x,D)=>{const k=i[x.id]||"",m=o.has(x.id),v=n[x.id]??!1;return e.jsx("div",{className:J(D<s.length-1&&"border-b border-[var(--surface-subtle)]"),children:e.jsxs($i,{open:v,onOpenChange:C=>I(x.id,C),className:"py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3",children:[e.jsxs(Gi,{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:p,children:[v?e.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):e.jsx(T,{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:x.name})]}),e.jsx(S,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":`Remove ${x.name}`,onClick:()=>P(x.id),disabled:p,children:e.jsx(T,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsx(Wi,{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:x.hostname})]}),e.jsx(ie,{type:"password",value:k,onChange:C=>E(x.id,C.target.value),onBlur:C=>{const L=C.currentTarget.value.trim();L&&N({presetId:x.id,presetName:x.name,hostname:x.hostname,token:L})},placeholder:m?"Saved token available (optional to replace)":"Paste token for this tunnel",className:"h-7",disabled:p}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",disabled:p||k.trim().length===0,onClick:()=>{N({presetId:x.id,presetName:x.name,hostname:x.hostname,token:k})},children:"Save token"})})]})})]})},x.id)})}):e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"No managed remote tunnels saved yet."}),h&&e.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[e.jsx(ie,{value:u,onChange:x=>y(x.target.value),placeholder:"Tunnel name (e.g. Production)",className:"h-7",disabled:p}),e.jsx(ie,{value:d,onChange:x=>b(x.target.value),placeholder:"Hostname (e.g. oc.example.com)",className:"h-7",disabled:p}),e.jsx(ie,{type:"password",value:w,onChange:x=>j(x.target.value),placeholder:"Token",className:"h-7",disabled:p}),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(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:A,disabled:p,children:"Save Changes"}),e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:f,disabled:p,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(vt,{children:"Tokens are saved in ~/.config/pichamber/cloudflare-managed-remote-tunnels.json."})]}),!g&&c&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:c})]}),_l=({managedLocalConfigPath:t,isManagedLocalConfigPathInvalid:s,managedLocalConfigExtensionError:n,disabled:i,fileInputRef:o,onInputChange:p,onInputBlur:h,onBrowse:u,onClear:d,onFileSelected:w})=>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:He,children:"Configuration file"}),e.jsx("input",{ref:o,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:w}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{value:t||"",onChange:c=>p(c.target.value),onBlur:h,placeholder:"Using default cloudflared config",className:"h-7",disabled:i}),e.jsx(S,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":"Browse config file",onClick:u,disabled:i,children:e.jsx(T,{name:"folder",className:"size-3.5"})}),t&&e.jsx(S,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":"Clear config file",onClick:d,disabled:i,children:e.jsx(T,{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:n})]})}),Ol=({tunnelMode:t,selectedPresetId:s,managedRemoteTunnelPresets:n,selectedPreset:i,willReplaceActiveTunnel:o,state:p,isSavingMode:h,isManagedLocalConfigPathInvalid:u,primaryCtaClass:d,onSelectPreset:w,onStart:c,onOpenDocUrl:g})=>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(T,{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:()=>{g(wl)},children:["Check documentation on how to configure a managed remote tunnel",e.jsx(T,{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:()=>{g(kl)},children:["Check documentation on managed local tunnel configuration",e.jsx(T,{name:"external-link",className:"size-3.5"})]})]}),e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:`Start a ${na.find(r=>r.value===t)?.label??"Quick"} 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:He,children:"Managed remote tunnel to connect"}),e.jsxs(_e,{value:s||(n[0]?.id??""),onValueChange:w,disabled:h||p==="starting"||p==="stopping"||n.length<=1,children:[e.jsx(Oe,{size:Ke,children:e.jsx(Ue,{placeholder:"Select saved tunnel",children:i?.name})}),e.jsx(Fe,{fitContent:!0,children:n.map(r=>e.jsx(Ee,{value:r.id,children:r.name},r.id))})]})]}),o&&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(T,{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(S,{size:"sm",variant:"outline",onClick:c,disabled:p==="starting"||h||t==="managed-remote"&&!i||t==="managed-local"&&u,className:J(d,p==="starting"&&"opacity-70"),children:p==="starting"?e.jsxs(e.Fragment,{children:[e.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Starting tunnel..."]}):"Start Tunnel"})]}),Ul=({tunnelInfo:t,isConnectLinkLive:s,copied:n,onCopyUrl:i,remainingText:o,qrDataUrl:p,onNewConnectLink:h,onStop:u,stopping:d,isSavingMode:w,isManagedLocalConfigPathInvalid:c,tunnelMode:g,primaryCtaClass:r})=>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(S,{size:"sm",variant:"ghost",onClick:i,className:"shrink-0 gap-1.5",children:[n?e.jsx(T,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):e.jsx(T,{name:"file-copy",className:"size-3.5"}),n?"Copied":"Copy all"]})]}),e.jsxs("p",{className:"typography-meta mt-1 text-muted-foreground/70",children:["Expires",": ",t.bootstrapExpiresAt?o:"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:[p?e.jsx("img",{src:p,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(S,{size:"sm",variant:"outline",onClick:h,disabled:d||w||g==="managed-local"&&c,className:r,children:[e.jsx(T,{name:"restart",className:"size-3.5"}),"New connect link"]}),e.jsx(S,{size:"sm",variant:"ghost",onClick:u,disabled:d||w,className:"gap-2 text-[var(--status-error)]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Stopping..."]}):"Stop Tunnel"})]})})]});function Fl({saveTunnelSettings:t,setManagedRemoteValidationError:s}){const[n,i]=a.useState([]),[o,p]=a.useState({}),[h,u]=a.useState(""),[d,w]=a.useState({}),[c,g]=a.useState(new Set),[r,f]=a.useState(!1),[y,b]=a.useState(""),[j,A]=a.useState(""),[I,P]=a.useState(""),E=a.useMemo(()=>n.find(v=>v.id===h)||n[0]||null,[n,h]),N=a.useCallback(async v=>{const C=v.token.trim();if(C)try{const L={...d,[v.presetId]:C};await ke({managedRemoteTunnelPresetTokens:L}),g(B=>{const q=new Set(B);return q.add(v.presetId),q})}catch{F.error("Failed to save managed remote tunnel token")}},[d]),x=a.useCallback(async(v,C)=>{try{await ke({managedRemoteTunnelPresets:C})}catch{F.error("Failed to save selected managed remote tunnel")}},[]),D=a.useCallback(v=>{const C=n.find(L=>L.id===v);C&&(u(C.id),s(null),x(C,n))},[n,x,s]),k=a.useCallback(async()=>{const v=y.trim(),C=Ns(j),L=I.trim();if(!v){F.error("Tunnel name is required");return}if(!C){F.error("Managed remote tunnel hostname is required");return}if(!L){F.error("Managed remote tunnel token is required");return}if(n.some(Y=>Y.hostname===C)){F.error("This hostname already exists");return}const B={id:Ml(),name:v,hostname:C},q=[...n,B];i(q),u(B.id),p(Y=>({...Y,[B.id]:!0})),w(Y=>({...Y,[B.id]:L})),s(null),f(!1),b(""),A(""),P(""),await t({tunnelMode:"managed-remote",managedRemoteTunnelPresets:q,managedRemoteTunnelPresetTokens:{...d,[B.id]:L}}),await N({presetId:B.id,presetName:B.name,hostname:B.hostname,token:L}),F.success("Managed remote tunnel saved")},[n,j,y,I,N,t,d,s]),m=a.useCallback(async v=>{const C=n.find($=>$.id===v);if(!C)return;const L=n.filter($=>$.id!==C.id),B=L[0]?.id||"",q=h===C.id?B:h,Y=Object.fromEntries(Object.entries(d).filter(([$,V])=>$!==C.id&&V.trim().length>0));i(L),u(q),p($=>{const V={...$};return delete V[C.id],V}),w($=>{const V={...$};return delete V[C.id],V}),g($=>{const V=new Set($);return V.delete(C.id),V}),s(null),await t({managedRemoteTunnelPresets:L,managedRemoteTunnelPresetTokens:Y}),F.success("Managed remote tunnel removed")},[n,t,h,d,s]);return{managedRemoteTunnelPresets:n,setManagedRemoteTunnelPresets:i,expandedManagedRemoteTunnels:o,setExpandedManagedRemoteTunnels:p,selectedPresetId:h,setSelectedPresetId:u,sessionTokensByPresetId:d,setSessionTokensByPresetId:w,savedTokenPresetIds:c,setSavedTokenPresetIds:g,isAddingPreset:r,setIsAddingPreset:f,newPresetName:y,setNewPresetName:b,newPresetHostname:j,setNewPresetHostname:A,newPresetToken:I,setNewPresetToken:P,selectedPreset:E,persistManagedRemoteTunnelToken:N,handleSelectPreset:D,handleSaveNewPreset:k,handleRemovePreset:m}}function Bl({saveTunnelSettings:t}){const[s,n]=a.useState(null),i=Cl,o=a.useRef(null),p=a.useMemo(()=>s?!Qt(s):!1,[s]),h=a.useCallback(async()=>{const g=await Hr({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(g.success&&typeof g.path=="string"&&g.path.trim().length>0){const r=g.path.trim();if(!Qt(r)){F.error(i);return}n(r),await t({managedLocalTunnelConfigPath:r});return}o.current?.click()},[i,t]),u=a.useCallback(g=>{const r=g.trim();n(r.length>0?r:null)},[]),d=a.useCallback(async()=>{if(s&&!Qt(s)){F.error(i);return}await t({managedLocalTunnelConfigPath:s})},[i,s,t]),w=a.useCallback(async()=>{n(null),await t({managedLocalTunnelConfigPath:null})},[t]),c=a.useCallback(async g=>{const r=g.target.files?.[0];if(!r)return;const f=r.name.trim();if(f.length!==0){if(!Qt(f)){F.error(i);return}n(f),await t({managedLocalTunnelConfigPath:f}),g.target.value=""}},[i,t]);return{managedLocalConfigPath:s,setManagedLocalConfigPath:n,managedLocalConfigExtensionError:i,managedLocalConfigFileInputRef:o,isManagedLocalConfigPathInvalid:p,handleBrowseManagedLocalConfig:h,handleManagedLocalConfigInputChange:u,handleManagedLocalConfigInputBlur:d,handleManagedLocalConfigClear:w,handleManagedLocalConfigFileSelected:c}}function Hl(){const[t,s]=a.useState(18e5),[n,i]=a.useState(480*60*1e3),[o,p]=a.useState(!1),h=a.useCallback(async(w,c)=>{p(!0);try{await ke({tunnelBootstrapTtlMs:w,tunnelSessionTtlMs:c})}catch{F.error("Failed to save tunnel TTL settings")}finally{p(!1)}},[]),u=a.useCallback(async w=>{const c=fs.find(g=>g.value===w);c&&(s(c.ms),await h(c.ms,n))},[h,n]),d=a.useCallback(async w=>{const c=xs.find(g=>g.value===w);!c||c.ms===null||(i(c.ms),await h(t,c.ms))},[t,h]);return{bootstrapTtlMs:t,setBootstrapTtlMs:s,sessionTtlMs:n,setSessionTtlMs:i,isSavingTtl:o,saveTtlSettings:h,handleBootstrapTtlChange:u,handleSessionTtlChange:d}}function Kl({tunnelInfo:t,state:s,setSessionRecords:n,setSavedTokenPresetIds:i,setLocalPort:o}){const[p,h]=a.useState(null),[u,d]=a.useState(""),[w,c]=a.useState(()=>Date.now());return a.useEffect(()=>{if(!t?.connectUrl){h(null);return}let g=!1;return bn.toDataURL(t.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(r=>{g||h(r)}).catch(()=>{g||h(null)}),()=>{g=!0}},[t?.connectUrl]),a.useEffect(()=>{if(!t?.bootstrapExpiresAt){d("No expiry");return}let g=null,r=Date.now();const f=()=>{const j=t.bootstrapExpiresAt?t.bootstrapExpiresAt-Date.now():0;j<=0?d("Expired"):d(Dn(j))},y=()=>{const j=Date.now();j-r>=1e3&&(f(),r=j),g=requestAnimationFrame(y)};f(),(typeof document>"u"||document.visibilityState==="visible")&&(g=requestAnimationFrame(y));const b=()=>{document.visibilityState==="visible"&&g===null?g=requestAnimationFrame(y):document.visibilityState!=="visible"&&g!==null&&(cancelAnimationFrame(g),g=null)};return document.addEventListener("visibilitychange",b),()=>{document.removeEventListener("visibilitychange",b),g!==null&&cancelAnimationFrame(g)}},[t?.bootstrapExpiresAt]),a.useEffect(()=>{let g=null,r=Date.now();const f=()=>{const b=Date.now();b-r>=1e3&&(c(b),r=b),g=requestAnimationFrame(f)};(typeof document>"u"||document.visibilityState==="visible")&&(g=requestAnimationFrame(f));const y=()=>{document.visibilityState==="visible"&&g===null?g=requestAnimationFrame(f):document.visibilityState!=="visible"&&g!==null&&(cancelAnimationFrame(g),g=null)};return document.addEventListener("visibilitychange",y),()=>{document.removeEventListener("visibilitychange",y),g!==null&&cancelAnimationFrame(g)}},[]),a.useEffect(()=>{if(s==="starting"||s==="stopping"||s==="checking")return;let g=!1;const r=async()=>{try{const y=await Be("/api/pichamber/tunnel/status");if(!y.ok||g)return;const b=await y.json();if(g)return;n(Array.isArray(b.activeSessions)?b.activeSessions:[]),i(()=>new Set(Array.isArray(b.managedRemoteTunnelTokenPresetIds)?b.managedRemoteTunnelTokenPresetIds:[])),o(typeof b.localPort=="number"?b.localPort:null)}catch{}},f=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||r()},5e3);return()=>{g=!0,window.clearInterval(f)}},[o,i,n,s]),{qrDataUrl:p,remainingText:u,nowTs:w}}function $l(){const t=_(ue=>ue.timeFormatPreference),[s,n]=a.useState("checking"),[i,o]=a.useState(null),[p,h]=a.useState(null),[u,d]=a.useState(null),[w,c]=a.useState(null),[g,r]=a.useState(!1),[f,y]=a.useState(!1),[b,j]=a.useState("cloudflare"),[A,I]=a.useState(()=>Zs("cloudflare")),[P,E]=a.useState([]),[N,x]=a.useState("quick"),[D,k]=a.useState([]),[m,v]=a.useState(null),{bootstrapTtlMs:C,setBootstrapTtlMs:L,sessionTtlMs:B,setSessionTtlMs:q,isSavingTtl:Y,handleBootstrapTtlChange:$,handleSessionTtlChange:V}=Hl(),oe=a.useCallback(async ue=>{y(!0);try{await ke(ue),Object.prototype.hasOwnProperty.call(ue,"tunnelMode")&&ue.tunnelMode&&x(ue.tunnelMode),Object.prototype.hasOwnProperty.call(ue,"tunnelProvider")&&typeof ue.tunnelProvider=="string"&&j(ue.tunnelProvider)}catch{F.error("Failed to save tunnel settings")}finally{y(!1)}},[]),xe=Fl({saveTunnelSettings:oe,setManagedRemoteValidationError:c}),{managedRemoteTunnelPresets:je,setManagedRemoteTunnelPresets:z,expandedManagedRemoteTunnels:O,setExpandedManagedRemoteTunnels:X,selectedPresetId:H,setSelectedPresetId:M,sessionTokensByPresetId:W,setSessionTokensByPresetId:se,savedTokenPresetIds:ye,setSavedTokenPresetIds:K,isAddingPreset:re,setIsAddingPreset:fe,newPresetName:be,setNewPresetName:pe,newPresetHostname:Q,setNewPresetHostname:U,newPresetToken:ae,setNewPresetToken:R,selectedPreset:Z,persistManagedRemoteTunnelToken:le,handleSelectPreset:ce,handleSaveNewPreset:G,handleRemovePreset:ne}=xe,de=Bl({saveTunnelSettings:oe}),{managedLocalConfigPath:Ne,setManagedLocalConfigPath:me,managedLocalConfigExtensionError:Pe,managedLocalConfigFileInputRef:Je,isManagedLocalConfigPathInvalid:Ye,handleBrowseManagedLocalConfig:he,handleManagedLocalConfigInputChange:De,handleManagedLocalConfigInputBlur:st,handleManagedLocalConfigClear:qe,handleManagedLocalConfigFileSelected:jt}=de,ts=a.useCallback(ue=>{K(ue)},[K]),{qrDataUrl:Ft,remainingText:ss,nowTs:gt}=Kl({tunnelInfo:i,state:s,setSessionRecords:k,setSavedTokenPresetIds:ts,setLocalPort:v}),as=a.useMemo(()=>D.map(ue=>{const Te=ue.expiresAt<=gt,$e=ue.status==="active"&&!Te,we=$e?Dn(ue.expiresAt-gt):ue.inactiveReason==="expired"||Te?"expired":"inactive",pt=we==="expired"?"Expired":ue.inactiveReason==="tunnel-revoked"?"Revoked":"Inactive",Xe=wt(ue.mode);return{...ue,isActive:$e,mode:Xe,remainingTextForSession:we,inactiveLabel:pt}}),[gt,D]),Ts=a.useMemo(()=>i?.connectUrl?i.bootstrapExpiresAt===null?!0:i.bootstrapExpiresAt>gt:!1,[gt,i?.bootstrapExpiresAt,i?.connectUrl]),ns=a.useMemo(()=>!i||s!=="active"&&s!=="stopping"?!1:p===N,[p,s,i,N]),Is=a.useMemo(()=>!i||s!=="active"||!p?!1:p!==N,[p,s,i,N]),rs=a.useMemo(()=>{if(typeof m=="number"&&Number.isFinite(m)&&m>0)return m;if(typeof window>"u")return null;const Te=Ut()||window.location.href;let $e=0;try{$e=Number(new URL(Te).port)}catch{$e=Number(window.location.port)}return Number.isFinite($e)&&$e>0?$e:null},[m]),Bt=a.useMemo(()=>P.find(ue=>ue.provider===b)??null,[P,b]),Ht=a.useMemo(()=>{const ue=new Set(Bt?.modes?.map(Te=>Te.key).filter(Te=>Te==="quick"||Te==="managed-remote"||Te==="managed-local"));return ue.size===0?na:na.filter(Te=>ue.has(Te.value))},[Bt]),Tt=a.useMemo(()=>Ht.some(ue=>ue.value==="managed-remote"||ue.value==="managed-local"),[Ht]),Es=a.useMemo(()=>A.provider===b?A:Zs(b),[A,b]),Ms=a.useCallback(async ue=>{await on(ue)},[]),Kt=a.useCallback((ue,Te)=>(I(Zs(Te,ue)),ue.available===!0),[]),$t=a.useCallback(async ue=>{try{const[Te,$e,we,pt]=await Promise.all([Be("/api/pichamber/tunnel/check",{signal:ue}),Be("/api/pichamber/tunnel/status",{signal:ue}),Be("/api/pi/ui-settings",{signal:ue,headers:{Accept:"application/json"}}),Be("/api/pichamber/tunnel/providers",{signal:ue})]),Xe=await Te.json(),Se=await $e.json(),Ze=we.ok?await we.json():{},is=pt.ok?await pt.json():{},zs=Se.ttlConfig?.bootstrapTtlMs??(Ze?.tunnelBootstrapTtlMs===null?null:typeof Ze?.tunnelBootstrapTtlMs=="number"?Ze.tunnelBootstrapTtlMs:1800*1e3),_s=typeof Se.ttlConfig?.sessionTtlMs=="number"?Se.ttlConfig.sessionTtlMs:typeof Ze?.tunnelSessionTtlMs=="number"?Ze.tunnelSessionTtlMs:480*60*1e3,Os=wt(Se.mode??Ze?.tunnelMode),os="cloudflare",Us=typeof Ze?.managedLocalTunnelConfigPath=="string"&&Ze.managedLocalTunnelConfigPath.trim()||null,Fs=Kt(Xe,os),ls=El(Se?.managedRemoteTunnelPresets),It=typeof Se.managedRemoteTunnelHostname=="string"?Se.managedRemoteTunnelHostname:"",cs=ls.length>0?ls:It?[{id:`legacy-${Ns(It)}`,name:It,hostname:Ns(It)}]:[],Bs=cs[0]?.id||"";if(L(zs),q(_s),j(os),E(Array.isArray(is?.providers)?is.providers:[]),x(Os),me(Us),z(cs),M(Bs),k(Array.isArray(Se.activeSessions)?Se.activeSessions:[]),h(Se.activeTunnelMode?wt(Se.activeTunnelMode):Se.active&&Se.mode?wt(Se.mode):null),K(new Set(Array.isArray(Se.managedRemoteTunnelTokenPresetIds)?Se.managedRemoteTunnelTokenPresetIds:[])),v(typeof Se.localPort=="number"?Se.localPort:null),Se.active&&Se.url){o({url:Se.url,connectUrl:null,bootstrapExpiresAt:typeof Se.bootstrapExpiresAt=="number"?Se.bootstrapExpiresAt:null}),n("active");return}n(Fs?"idle":"not-available")}catch{ue.aborted||(n("error"),d("Failed to check tunnel availability"))}},[Kt,L,me,z,K,M,q]);a.useEffect(()=>{const ue=new AbortController;return $t(ue.signal),()=>ue.abort()},[$t]);const As=a.useCallback(async()=>{if(d(null),c(null),N==="managed-local"&&Ne&&!Qt(Ne)){d(Pe),F.error(Pe);return}n("starting");try{let ue="",Te="";if(N==="managed-remote"){if(!Z){n("idle"),c("Select or add a managed remote tunnel first"),F.error("Select or add a managed remote tunnel first");return}ue=Z.hostname,Te=(W[Z.id]||"").trim(),await oe({tunnelMode:"managed-remote",managedRemoteTunnelPresets:je})}const $e=await Be("/api/pichamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,mode:N,...N==="managed-remote"&&Z?{managedRemoteTunnelPresetId:Z.id,managedRemoteTunnelPresetName:Z.name}:{},...N==="managed-remote"&&ue?{managedRemoteTunnelHostname:ue}:{},...N==="managed-remote"&&Te?{managedRemoteTunnelToken:Te}:{},...N==="managed-local"&&Ne?{configPath:Ne}:{}})}),we=await $e.json();if(!$e.ok||!we.ok){if(N==="managed-remote"&&typeof we.error=="string"&&we.error.includes("Managed remote tunnel token is required")){n("idle"),c("Managed remote tunnel token is required before starting"),F.error("Add a managed remote tunnel token before starting");return}n("error"),d(we.error||"Failed to start tunnel"),F.error(we.error||"Failed to start tunnel");return}const pt=typeof we.url=="string"?we.url:"";if(!pt){n("error"),d("Tunnel started but no public URL was returned"),F.error("Tunnel started but no public URL was returned");return}if(o({url:pt,connectUrl:typeof we.connectUrl=="string"?we.connectUrl:null,bootstrapExpiresAt:typeof we.bootstrapExpiresAt=="number"?we.bootstrapExpiresAt:null}),h(we.activeTunnelMode?wt(we.activeTunnelMode):we.mode?wt(we.mode):N),k(Array.isArray(we.activeSessions)?we.activeSessions:[]),Array.isArray(we.managedRemoteTunnelTokenPresetIds)&&K(new Set(we.managedRemoteTunnelTokenPresetIds)),typeof we.localPort=="number"&&v(we.localPort),typeof we.mode=="string"&&x(wt(we.mode)),n("active"),we.replacedTunnel){const Xe=typeof we.revokedBootstrapCount=="number"?we.revokedBootstrapCount:0,Se=typeof we.invalidatedSessionCount=="number"?we.invalidatedSessionCount:0;Xe===1&&Se===1?F.warning("Replaced previous tunnel: revoked 1 link, invalidated 1 session."):Xe===1?F.warning(`Replaced previous tunnel: revoked 1 link, invalidated ${Se} sessions.`):Se===1?F.warning(`Replaced previous tunnel: revoked ${Xe} links, invalidated 1 session.`):F.warning(`Replaced previous tunnel: revoked ${Xe} links, invalidated ${Se} sessions.`)}else F.success("Tunnel link ready")}catch{n("error"),d("Failed to start tunnel"),F.error("Failed to start tunnel")}},[Pe,Ne,je,oe,Z,W,c,K,N,b]),Ds=a.useCallback(async()=>{n("stopping");try{await Be("/api/pichamber/tunnel/stop",{method:"POST"});const ue=await Be("/api/pichamber/tunnel/status");if(ue.ok){const Te=await ue.json();k(Array.isArray(Te.activeSessions)?Te.activeSessions:[]),K(new Set(Array.isArray(Te.managedRemoteTunnelTokenPresetIds)?Te.managedRemoteTunnelTokenPresetIds:[])),v(typeof Te.localPort=="number"?Te.localPort:null)}o(null),h(null),n("idle"),F.success("Tunnel stopped")}catch{n("error"),d("Failed to stop tunnel"),F.error("Failed to stop tunnel")}},[K]),Ls=a.useCallback(async()=>{if(i?.connectUrl)try{await navigator.clipboard.writeText(i.connectUrl),r(!0),F.success("Connect link copied"),setTimeout(()=>r(!1),2e3)}catch{F.error("Failed to copy URL")}},[i?.connectUrl]),Rs=a.useCallback(async ue=>{c(null),d(null),s!=="active"&&s!=="stopping"&&s!=="starting"&&n("idle"),await oe({tunnelMode:ue,managedRemoteTunnelPresets:je})},[je,oe,c,s]);return{timeFormatPreference:t,state:s,tunnelInfo:i,activeTunnelMode:p,qrDataUrl:Ft,errorMessage:u,managedRemoteValidationError:w,setManagedRemoteValidationError:c,copied:g,isSavingTtl:Y,isSavingMode:f,tunnelProvider:b,dependencyInstallInfo:A,providerCapabilities:P,tunnelMode:N,managedLocalConfigPath:Ne,managedRemoteTunnelPresets:je,expandedManagedRemoteTunnels:O,setExpandedManagedRemoteTunnels:X,selectedPresetId:H,sessionTokensByPresetId:W,setSessionTokensByPresetId:se,savedTokenPresetIds:ye,isAddingPreset:re,setIsAddingPreset:fe,newPresetName:be,setNewPresetName:pe,newPresetHostname:Q,setNewPresetHostname:U,newPresetToken:ae,setNewPresetToken:R,bootstrapTtlMs:C,sessionTtlMs:B,remainingText:ss,sessionRecords:D,nowTs:gt,localPort:m,managedLocalConfigExtensionError:Pe,managedLocalConfigFileInputRef:Je,isManagedLocalConfigPathInvalid:Ye,selectedPreset:Z,renderedSessionRecords:as,isConnectLinkLive:Ts,isSelectedModeTunnelReady:ns,willReplaceActiveTunnel:Is,suggestedConnectorPort:rs,selectedProviderCapability:Bt,tunnelModeOptions:Ht,providerSupportsManagedModes:Tt,displayedDependencyInstallInfo:Es,openExternal:Ms,handleBrowseManagedLocalConfig:he,handleManagedLocalConfigInputChange:De,handleManagedLocalConfigInputBlur:st,handleManagedLocalConfigClear:qe,handleManagedLocalConfigFileSelected:jt,handleStart:As,handleStop:Ds,handleCopyUrl:Ls,handleBootstrapTtlChange:$,handleSessionTtlChange:V,handleModeChange:Rs,handleSelectPreset:ce,handleSaveNewPreset:G,handleRemovePreset:ne,persistManagedRemoteTunnelToken:le}}const Gl=()=>{const{timeFormatPreference:t,state:s,tunnelInfo:n,qrDataUrl:i,errorMessage:o,managedRemoteValidationError:p,setManagedRemoteValidationError:h,copied:u,isSavingTtl:d,isSavingMode:w,tunnelMode:c,managedLocalConfigPath:g,managedRemoteTunnelPresets:r,expandedManagedRemoteTunnels:f,setExpandedManagedRemoteTunnels:y,selectedPresetId:b,sessionTokensByPresetId:j,setSessionTokensByPresetId:A,savedTokenPresetIds:I,isAddingPreset:P,setIsAddingPreset:E,newPresetName:N,setNewPresetName:x,newPresetHostname:D,setNewPresetHostname:k,newPresetToken:m,setNewPresetToken:v,bootstrapTtlMs:C,sessionTtlMs:L,remainingText:B,managedLocalConfigExtensionError:q,managedLocalConfigFileInputRef:Y,isManagedLocalConfigPathInvalid:$,selectedPreset:V,renderedSessionRecords:oe,isConnectLinkLive:xe,isSelectedModeTunnelReady:je,willReplaceActiveTunnel:z,suggestedConnectorPort:O,tunnelModeOptions:X,providerSupportsManagedModes:H,displayedDependencyInstallInfo:M,openExternal:W,handleBrowseManagedLocalConfig:se,handleManagedLocalConfigInputChange:ye,handleManagedLocalConfigInputBlur:K,handleManagedLocalConfigClear:re,handleManagedLocalConfigFileSelected:fe,handleStart:be,handleStop:pe,handleCopyUrl:Q,handleBootstrapTtlChange:U,handleSessionTtlChange:ae,handleModeChange:R,handleSelectPreset:Z,handleSaveNewPreset:le,handleRemovePreset:ce,persistManagedRemoteTunnelToken:G}=$l(),ne="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(te,{title:"External Tunnel",info:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{children:"Configure secure remote access with quick links or your own managed remote 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(Dl,{records:oe,timeFormatPreference:t}),s==="not-available"&&e.jsx(Ll,{installInfo:M}),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:He,children:"Provider"}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-foreground",children:e.jsx(Al,{provider:"cloudflare"})})]}),e.jsxs("div",{"data-settings-item":"tunnel.type",className:"space-y-1.5",children:[e.jsx("p",{className:He,children:"Tunnel type"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1",children:X.map(de=>e.jsxs(hn,{children:[e.jsx(gn,{asChild:!0,children:e.jsx(S,{variant:"chip",size:"xs","aria-pressed":c===de.value,className:"!font-normal",onClick:()=>{R(de.value)},disabled:w||s==="starting"||s==="stopping",children:de.label})}),e.jsx(Si,{sideOffset:8,className:"max-w-xs",children:de.tooltip})]},de.value))})]})]}),e.jsx(Rl,{bootstrapTtlMs:C,sessionTtlMs:L,tunnelMode:c,disabled:d||w||s==="starting"||s==="stopping",providerSupportsManagedModes:H,onBootstrapTtlChange:de=>{U(de)},onSessionTtlChange:de=>{ae(de)}}),c==="managed-remote"&&e.jsx(zl,{suggestedConnectorPort:O,managedRemoteTunnelPresets:r,expandedManagedRemoteTunnels:f,sessionTokensByPresetId:j,savedTokenPresetIds:I,disabled:s==="starting"||s==="stopping"||w,isAddingPreset:P,newPresetName:N,newPresetHostname:D,newPresetToken:m,managedRemoteValidationError:p,selectedPreset:V,onToggleAddPreset:()=>E(de=>!de),onCancelAddPreset:()=>{E(!1),x(""),k(""),v("")},onNewPresetNameChange:x,onNewPresetHostnameChange:k,onNewPresetTokenChange:v,onSaveNewPreset:()=>{le()},onTogglePresetCollapse:(de,Ne)=>{y(me=>({...me,[de]:Ne})),Ne&&Z(de)},onRemovePreset:de=>{ce(de)},onPresetTokenChange:(de,Ne)=>{h(null),A(me=>({...me,[de]:Ne}))},onPersistToken:de=>{G(de)}}),c==="managed-local"&&e.jsx(_l,{managedLocalConfigPath:g,isManagedLocalConfigPathInvalid:$,managedLocalConfigExtensionError:q,disabled:s==="starting"||s==="stopping"||w,fileInputRef:Y,onInputChange:ye,onInputBlur:()=>{K()},onBrowse:()=>{se()},onClear:()=>{re()},onFileSelected:de=>{fe(de)}}),!je&&e.jsx(Ol,{tunnelMode:c,selectedPresetId:b,managedRemoteTunnelPresets:r,selectedPreset:V,willReplaceActiveTunnel:z,state:s,isSavingMode:w,isManagedLocalConfigPathInvalid:$,primaryCtaClass:ne,onSelectPreset:de=>{Z(de)},onStart:be,onOpenDocUrl:de=>{W(de)}})]}),je&&n&&e.jsx(Ul,{tunnelInfo:n,isConnectLinkLive:xe,copied:u,onCopyUrl:Q,remainingText:B,qrDataUrl:i,onNewConnectLink:be,onStop:pe,stopping:s==="stopping",isSavingMode:w,isManagedLocalConfigPathInvalid:$,tunnelMode:c,primaryCtaClass:ne}),s==="error"&&o&&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:o}),e.jsx(S,{size:"sm",variant:"ghost",onClick:be,children:"Retry"})]})]})})},Ln=()=>{const t=Re()&&es(),s=t&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[n,i]=ge.useState(!1),[o,p]=ge.useState(!1),[h,u]=ge.useState(""),[d,w]=ge.useState(""),[c,g]=ge.useState(!1),[r,f]=ge.useState(!1),[y,b]=ge.useState(null),[j,A]=ge.useState(!0),[I,P]=ge.useState(!1),[E,N]=ge.useState(!1),[x,D]=ge.useState(!1),[k,m]=ge.useState(!1),[v,C]=ge.useState(!1),[L,B]=ge.useState(!1),[q,Y]=ge.useState(!1),[$,V]=ge.useState(!0),[oe,xe]=ge.useState(!0),[je,z]=ge.useState(!1),[O,X]=ge.useState(!1),[H,M]=ge.useState(!1),[W,se]=ge.useState(null),[ye,K]=ge.useState(null);ge.useEffect(()=>{if(!t){A(!1);return}let G=!1;return(async()=>{try{const ne=await Be("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!ne.ok)throw new Error("Failed to load desktop settings");const de=await ne.json().catch(()=>null);if(G)return;const Ne=de?.desktopLanAccessEnabled===!0,me=typeof de?.desktopUiPassword=="string"?de.desktopUiPassword:"";i(Ne),p(Ne),u(me),w(me),f(de?.desktopLanAccessActive===!0),b(typeof de?.desktopLanAccessBlockedReason=="string"?de.desktopLanAccessBlockedReason:null);const Pe=de?.desktopMacMenuBarEnabled!==!1;V(Pe),xe(Pe),se(null)}catch(ne){G||se(ne instanceof Error?ne.message:"Failed to load desktop settings")}finally{G||A(!1)}})(),()=>{G=!0}},[t]),ge.useEffect(()=>{if(!t){N(!1);return}let G=!1;return(async()=>{const ne=await Kr();G||(N(ne?.supported===!0),D(ne?.enabled===!0))})(),()=>{G=!0}},[t]),ge.useEffect(()=>{if(!t){C(!1);return}let G=!1;return(async()=>{const ne=await $r();G||(C(ne?.supported===!0),B(ne?.enabled===!0))})(),()=>{G=!0}},[t]),ge.useEffect(()=>{if(!t){z(!1);return}let G=!1;return(async()=>{const ne=await Gr();G||(z(ne?.supported===!0),X(ne?.enabled===!0))})(),()=>{G=!0}},[t]),ge.useEffect(()=>{if(!t||!o){K(null);return}let G=!1;return(async()=>{const ne=await tn();G||K(ne)})(),()=>{G=!0}},[o,t]);const re=o!==n||d!==h||oe!==$,fe=ge.useMemo(()=>{if(typeof window>"u")return null;const ne=Ut()||window.location.href;let de=0;try{de=Number(new URL(ne).port)}catch{de=Number(window.location.port)}return Number.isFinite(de)&&de>0?de:null},[]),be=o&&r&&ye&&fe?`http://${ye}:${fe}`:null,pe=o&&!d.trim(),Q=n&&!r&&y==="missing-password",U=j||I||!re||pe,ae=ge.useCallback(G=>{w(G),G.trim()||p(!1)},[]),R=ge.useCallback(async()=>{if(!E||k)return;const G=!x;D(G),m(!0),se(null);try{const ne=await Wr(G);if(!ne?.supported)throw new Error("Launch at login is not supported on this system");D(ne.enabled)}catch(ne){D(!G),se(ne instanceof Error?ne.message:"Failed to update launch at login setting")}finally{m(!1)}},[k,x,E]),Z=ge.useCallback(async()=>{if(!v||q)return;const G=!L;B(G),Y(!0),se(null);try{const ne=await Vr(G);if(!ne)throw new Error("Failed to update system tray setting");if(!ne.supported)throw new Error("System tray background mode is not supported on this system");B(ne.enabled)}catch(ne){B(!G),se(ne instanceof Error?ne.message:"Failed to update system tray setting")}finally{Y(!1)}},[q,L,v]),le=ge.useCallback(async()=>{if(!je||H)return;const G=!O;X(G),M(!0),se(null);try{const ne=await qr(G);if(!ne?.supported)throw new Error("Preventing sleep is not supported on this system");X(ne.enabled)}catch(ne){X(!G),se(ne instanceof Error?ne.message:"Failed to update keep awake setting")}finally{M(!1)}},[H,O,je]),ce=ge.useCallback(async()=>{if(re){P(!0),se(null);try{if(!(await Be("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:o,desktopUiPassword:d,desktopMacMenuBarEnabled:oe})})).ok)throw new Error("Failed to save desktop settings");if(i(o),u(d),V(oe),!await Qr())throw new Error("Saved, but failed to restart app")}catch(G){se(G instanceof Error?G.message:"Failed to save desktop settings"),P(!1)}}},[oe,d,o,re]);return t?e.jsx(te,{title:"Desktop Network Access",children:e.jsxs("div",{className:"space-y-3",children:[E||s||v||je?e.jsxs("div",{className:We,children:[E?e.jsx(ve,{settingsItem:"sessions.desktop-launch-at-login",checked:x,onChange:G=>{G!==x&&R()},disabled:k,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,s?e.jsx(ve,{settingsItem:"sessions.desktop-mac-menu-bar",checked:oe,onChange:xe,disabled:j||I,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,v?e.jsx(ve,{settingsItem:"sessions.desktop-minimize-to-tray",checked:L,onChange:G=>{G!==L&&Z()},disabled:q,label:"Minimize and close to the system tray",info:"Keeps PiChamber running in the system tray when the main window is minimized or closed.",ariaLabel:"Minimize and close PiChamber to the system tray"}):null,je?e.jsx(ve,{settingsItem:"sessions.desktop-keep-awake",checked:O,onChange:G=>{G!==O&&le()},disabled:H,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,e.jsxs(Me,{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(ie,{id:"desktop-ui-password",type:c?"text":"password",className:"h-8 min-w-0 flex-1",value:d,onChange:G=>ae(G.target.value),placeholder:"No password required",disabled:j||I,required:o,"aria-invalid":pe}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>g(G=>!G),className:Ge,"aria-label":c?"Hide password":"Show password","aria-pressed":c,children:e.jsx(T,{name:c?"eye-off":"eye",className:"h-4 w-4"})})]}),e.jsx("div",{className:We,children:e.jsx(ve,{settingsItem:"sessions.desktop-lan-access",checked:o,onChange:p,disabled:j||I,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."}),pe||Q?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"})}),W?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:W}):null,be?e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[re&&!n?"After restart, open from another device: ":"Open from another device: ",e.jsx("span",{className:"font-mono text-foreground",children:be})]}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(S,{type:"button",size:"xs",onClick:ce,disabled:U,className:"shrink-0 !font-normal",children:I?"Saving...":"Save + Restart"})})]})}):null},Rn=new Set(["shift","control","alt","meta"]),Wl=t=>{if(Rn.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 n=oa(t.key);return n?(s.push(n),rt(s.join("+"))):null},Vl=t=>{const s=[];if((t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt"),Rn.has(t.key.toLowerCase()))return s.length>0?rt(s.join("+")):null;const n=oa(t.key);return n?(s.push(n),s.length>0?rt(s.join("+")):null):null},ql={add_selection_to_chat:"Add selection to chat",cycle_agent:"Cycle agent",cycle_favorite_model_backward:"Cycle favorite model backward",cycle_favorite_model_forward:"Cycle favorite model forward",cycle_services_tab:"Cycle services tab",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_go_to_line:"Go to line (files editor)",open_help:"Open keyboard shortcuts",open_model_selector:"Open model selector",open_right_sidebar_files:"Open Files surface",open_right_sidebar_git:"Open Git surface",open_settings:"Open settings",open_timeline_dialog:"Open conversation timeline",switch_context_surface:"Switch context panel surface",toggle_prompt_navigator:"Toggle prompt navigator",toggle_right_sidebar:"Toggle context panel",toggle_services_menu:"Toggle services menu",toggle_sidebar:"Toggle sidebar",toggle_terminal:"Toggle terminal dock",toggle_terminal_expanded:"Toggle terminal expanded"},Ql=()=>{const t=_(N=>N.shortcutOverrides),s=_(N=>N.setShortcutOverride),n=_(N=>N.clearShortcutOverride),i=_(N=>N.resetAllShortcutOverrides),o=a.useMemo(()=>Jr(),[]),p=a.useCallback((N,x)=>ql[N]??x,[]),[h,u]=a.useState(null),[d,w]=a.useState({}),[c,g]=a.useState(""),[r,f]=a.useState(""),[y,b]=a.useState(null),j=a.useCallback(N=>{ke({shortcutOverrides:N})},[]),A=a.useCallback((N,x)=>{const D=rt(x);for(const k of o){if(k.id===N)continue;const m=Pa(k.id,t);if(rt(m)===D)return k.id}return null},[o,t]),I=a.useCallback((N,x)=>{const D=rt(x),k=A(N,D);if(k){b({actionId:N,combo:D,conflictActionId:k}),g("");return}const m={...t,[N]:D};s(N,D),j(m),b(null),g(""),f(Ta(D)?"This shortcut can conflict with browser defaults. It is still saved.":""),w(v=>{const C={...v};return delete C[N],C})},[A,j,s,t]),P=a.useCallback(()=>{if(!y)return;const N={...t,[y.conflictActionId]:Vs,[y.actionId]:y.combo};s(y.conflictActionId,Vs),s(y.actionId,y.combo),j(N),b(null),g(""),f(Ta(y.combo)?"This shortcut can conflict with browser defaults. It is still saved.":""),w(x=>{const D={...x};return delete D[y.actionId],D})},[y,j,s,t]),E=a.useCallback(N=>{const x={...t};delete x[N],n(N),j(x),w(D=>{const k={...D};return delete k[N],k}),b(null),g(""),f("")},[n,j,t]);return e.jsxs(te,{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(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{i(),j({}),w({}),b(null),g(""),f("")},children:"Reset All"}),children:[(c||r||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(S,{type:"button",size:"xs",className:"!font-normal",onClick:P,children:"Overwrite"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>b(null),children:"Cancel"})]})]}),c&&e.jsx("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3 typography-meta text-foreground",children:c}),r&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 typography-meta text-foreground",children:r})]}),e.jsx("div",{children:o.map((N,x)=>{const D=N.id==="switch_context_surface",k=D?Yr(N.id,t):Pa(N.id,t),m=d[N.id],v=m??k,C=typeof m=="string"&&rt(m)!==rt(k),L=v===""||rt(v)===Vs,B=h===N.id?"Press keys...":D&&!L?`${Ia(v)} + 1…0`:Ia(v);return e.jsx("div",{className:J("py-1.5",x>0&&"border-t border-border/40"),children:e.jsxs(ze,{label:p(N.id,N.label),alignEnd:!1,children:[e.jsx(ie,{readOnly:!0,value:B,onFocus:()=>{u(N.id),g("")},onBlur:()=>{h===N.id&&u(null)},onKeyDown:q=>{if(q.preventDefault(),q.stopPropagation(),q.key==="Escape"){u(null);return}const Y=D?Vl(q):Wl(q);Y&&(w($=>({...$,[N.id]:Y})),u(null),b(null),g(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),e.jsx(S,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const q=d[N.id];if(!q){g("Capture a shortcut first.");return}I(N.id,q)},disabled:!C,children:"Save Changes"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>E(N.id),children:"Reset"})]})},N.id)})})]})},Jl=new Set(["shift","control","alt","meta"]),Yl=t=>{if(Jl.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 n=oa(t.key);if(!n)return null;s.push(n);const i=rt(s.join("+"));return s.length>1?i:null},Xl=({trigger:t,index:s,onChange:n,onRemove:i})=>{const o="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(ie,{value:t.label,placeholder:"Label","aria-label":`Trigger ${s+1} label`,onChange:p=>n({...t,label:p.target.value}),className:J(o,"@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(ie,{value:t.command,placeholder:"command","aria-label":`Trigger ${s+1} command`,onChange:p=>n({...t,command:p.target.value}),className:J(o,"w-40")})]}),e.jsx(ie,{value:t.args??"",placeholder:"Arguments (optional)","aria-label":`Trigger ${s+1} arguments`,onChange:p=>n({...t,args:p.target.value}),className:J(o,"flex-1")}),e.jsx("input",{value:t.combo?t.combo.replace(/\+/g,"+"):"",placeholder:"Keybinding","aria-label":`Trigger ${s+1} keybinding`,readOnly:!0,onKeyDown:p=>{const h=Yl(p);h&&(p.preventDefault(),n({...t,combo:h}))},className:J(o,"w-32 rounded-md border")}),e.jsx(S,{variant:"ghost",size:"icon",onClick:i,"aria-label":`Remove trigger ${t.label}`,children:e.jsx(T,{name:"close",className:"size-4"})})]})},Zl=()=>{const t=_(p=>p.commandTriggers),s=a.useCallback(async p=>{_.setState({commandTriggers:p});try{await ke({commandTriggers:p})}catch{ot("error")}},[]),n=(p,h)=>{const u=t.map((d,w)=>w===p?h:d);s(Xr(u)??[])},i=p=>{const h=t.filter((u,d)=>d!==p);s(h)},o=()=>{t.length>=Ea||s([...t,{id:`trigger-${Date.now().toString(36)}`,label:"",command:""}])};return e.jsxs(te,{title:"Command triggers",divider:!1,settingsItem:"shortcuts.command-triggers",children:[e.jsx(ze,{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(S,{size:"sm",variant:"outline",onClick:o,disabled:t.length>=Ea,children:"Add trigger"})}),t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 pb-1",children:t.map((p,h)=>e.jsx(Xl,{trigger:p,index:h,onChange:u=>n(h,u),onRemove:()=>i(h)},p.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."})]})},zn=()=>{const[t,s]=a.useState(0);return a.useEffect(()=>ia(()=>s(n=>n+1)),[]),t},ec=({section:t})=>{const{isMobile:s}=Ve();zn();const n=s&&bt(),i=Re()&&es();if(!t)return e.jsxs(Ie,{className:"pichamber-page-body space-y-3 sm:space-y-6",children:[e.jsx(Ps,{}),e.jsx(Mn,{}),i&&e.jsx(Ln,{}),e.jsx(In,{}),bt()&&!Re()&&!rn()&&e.jsx(En,{}),n&&e.jsx(yn,{})]});const o=()=>{switch(t){case"general":return e.jsx(sc,{});case"visual":return e.jsx(ac,{});case"chat":return e.jsx(nc,{});case"sessions":return e.jsx(rc,{});case"shortcuts":return e.jsx(tc,{});case"git":return e.jsx(ic,{});case"github":return e.jsx(oc,{});case"notifications":return e.jsx(lc,{});case"tunnel":return e.jsx(cc,{});default:return null}},p={general:"General",visual:"Appearance",chat:"Chat",sessions:"Sessions",shortcuts:"Shortcuts",git:"Git",github:"Git",notifications:"Notifications",tunnel:"External Tunnel"}[t],h={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(Ie,{title:s?void 0:p,description:s?void 0:h,className:"pichamber-page-body",children:o()})},tc=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ql,{}),e.jsx(Zl,{})]}),sc=()=>{zn();const t=Re()&&es(),s=bt()&&!Re()&&!rn();return e.jsxs(e.Fragment,{children:[t&&e.jsx(Ln,{}),s&&e.jsx(En,{}),e.jsx(Ps,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar","terminalQuickKeys","terminalShell","terminalLoginShell","perfHud"]})]})},ac=()=>e.jsx(Ps,{visibleSettings:["theme","windowControlsPosition","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat","weekStart","fontSize","terminalFontSize","editorFontSize","spacing","inputBarOffset"]}),nc=()=>e.jsx(Ps,{visibleSettings:["userMessageRendering","mermaidRendering","reasoning","showToolFileIcons","showTurnChangedFiles","expandedTools","collapsibleUserMessages","stickyUserHeader","promptNavigatorEnabled","wideChatLayout","codeBlockLineWrap","splitAssistantMessageActions","diffLayout","dotfiles","fileViewerPreview","followUpBehavior","persistDraft","inputSpellcheck"]}),rc=()=>e.jsxs(e.Fragment,{children:[e.jsx(Mn,{}),e.jsx(In,{})]}),ic=()=>e.jsx(pa,{}),oc=()=>e.jsx(pa,{}),lc=()=>e.jsx(jl,{}),cc=()=>e.jsx(Gl,{}),Wt="openai-compatible",dc=t=>`${Math.round(t/1024/1024)} MB`;function uc(){const[t,s]=a.useState(null),[n,i]=a.useState(null),[o,p]=a.useState(""),[h,u]=a.useState(""),[d,w]=a.useState(""),[c,g]=a.useState(null),[r,f]=a.useState(!1),y=a.useCallback(async()=>{const P=await Be("/api/stt/status");if(!P.ok)throw new Error("Could not load dictation settings");const E=await P.json();s(E),i(null);const N=E.config.providers.find(x=>x.id===Wt);N&&(p(N.baseUrl),u(N.model))},[]);a.useEffect(()=>{y().catch(P=>i(P.message))},[y]),a.useEffect(()=>{if(!t?.models.some(E=>E.downloading))return;const P=window.setInterval(()=>{y().catch(()=>{})},1500);return()=>window.clearInterval(P)},[y,t?.models]);const b=a.useCallback(async P=>{ot("saving");try{const E=await Be("/api/stt/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!E.ok)throw new Error((await E.json().catch(()=>null))?.error||"Could not save dictation settings");const N=await E.json();s(x=>x&&{...x,config:N.config}),ot("saved")}catch(E){throw ot("error"),E}},[]),j=async(P,E)=>{g(P);try{const N=E==="POST"?"/download":"",x=await Be(`/api/stt/models/${encodeURIComponent(P)}${N}`,{method:E});if(!x.ok)throw new Error((await x.json().catch(()=>null))?.error||"Model action failed");await y()}catch(N){i(N instanceof Error?N.message:String(N))}finally{g(null)}},A=async()=>{f(!0);try{await b({remoteProvider:{id:Wt,label:"OpenAI-compatible",baseUrl:o,model:h,apiKey:d||void 0},providerConfigId:Wt}),w("")}catch(P){i(P instanceof Error?P.message:String(P))}finally{f(!1)}};if(!t)return e.jsx(Ie,{title:"Dictation",children:e.jsx("div",{className:"py-8 typography-ui text-muted-foreground",children:n||"Loading dictation settings..."})});const I=t.config.providers.find(P=>P.id===Wt);return e.jsxs(Ie,{title:"Dictation",description:"Record speech and insert the final transcript into the composer.",children:[e.jsxs(te,{title:"Recording",divider:!1,settingsItem:"dictation.enabled",contentClassName:"space-y-4",children:[e.jsx(ve,{checked:t.config.enabled,onChange:P=>{b({enabled:P}).catch(E=>i(E.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(ze,{label:"Transcription provider",settingsItem:"dictation.provider",children:e.jsxs(_e,{value:t.config.providerConfigId,onValueChange:P=>{b({providerConfigId:P}).catch(E=>i(E.message))},children:[e.jsx(Oe,{size:Ke,className:ca,"aria-label":"Transcription provider",children:e.jsx(Ue,{})}),e.jsxs(Fe,{children:[e.jsx(Ee,{value:"local",children:"Local model"}),e.jsx(Ee,{value:Wt,disabled:!I,children:"OpenAI-compatible"})]})]})}),e.jsx(ze,{label:"Language",info:"Optional language code such as en or fr. Leave blank for automatic detection.",settingsItem:"dictation.language",children:e.jsx(ie,{value:t.config.language,onChange:P=>s(E=>E&&{...E,config:{...E.config,language:P.target.value}}),onBlur:()=>{b({language:t.config.language}).catch(P=>i(P.message))},placeholder:"Auto-detect",className:"h-8 w-full max-w-48","aria-label":"Dictation language"})})]}),e.jsx(te,{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(P=>e.jsxs("div",{className:"flex min-h-10 items-center gap-3 py-1.5",children:[e.jsx(fn,{checked:t.config.localModelId===P.id,onChange:()=>{b({localModelId:P.id,providerConfigId:"local"}).catch(E=>i(E.message))},ariaLabel:`Use ${P.description}`}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{b({localModelId:P.id,providerConfigId:"local"}).catch(E=>i(E.message))},children:[e.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:P.description}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:dc(P.sizeBytes)})]}),P.downloading?e.jsx("span",{className:"typography-meta tabular-nums text-muted-foreground",children:P.downloadProgress===null?"Downloading...":`Downloading ${P.downloadProgress}%`}):P.installed?e.jsxs(e.Fragment,{children:[e.jsx(T,{name:"check",className:"size-4 text-[var(--status-success)]","aria-label":"Installed"}),e.jsx(S,{className:Ge,variant:"ghost",size:"icon",disabled:c===P.id,onClick:()=>{j(P.id,"DELETE")},title:"Delete model","aria-label":`Delete ${P.description}`,children:e.jsx(T,{name:"delete-bin",className:"size-4"})})]}):e.jsx(S,{variant:"outline",size:"sm",disabled:c===P.id,onClick:()=>{j(P.id,"POST")},children:P.corrupt||P.downloadError?"Retry":"Download"})]},P.id))}),e.jsxs(te,{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(Me,{label:"Server URL",children:e.jsx(ie,{value:o,onChange:P=>p(P.target.value),placeholder:"https://api.openai.com/v1",className:"h-8"})}),e.jsx(Me,{label:"Model",children:e.jsx(ie,{value:h,onChange:P=>u(P.target.value),placeholder:"whisper-1",className:"h-8"})}),e.jsx(Me,{label:"API key",info:I?.apiKeyConfigured?"A key is already stored. Leave this blank to keep it.":"Optional for servers that do not require authentication.",children:e.jsx(ie,{type:"password",value:d,onChange:P=>w(P.target.value),placeholder:I?.apiKeyConfigured?"Stored key":"Optional",className:"h-8",autoComplete:"off"})}),e.jsx("div",{className:St,children:e.jsx(S,{onClick:()=>{A()},disabled:r||!o.trim()||!h.trim(),children:r?"Saving...":"Save Provider"})})]}),n?e.jsx("p",{role:"alert",className:"pb-6 typography-meta text-[var(--status-error)]",children:n}):null]})}const Ya=256,Xa=280,mc=["general","appearance","chat","dictation","notifications","sessions","shortcuts","about","projects","remote-instances","tunnel","git","providers","behavior","snippets","prompt-templates","skills.installed"];function _n(t,s){return t.isAvailable?.(s)??!0}function pc(t,s){return{isWeb:!t&&bt(),isDesktop:t,isMobile:s}}function Za(t,s){const n=new Set(s);let i=t,o=1;for(;n.has(i);)i=`${t}-${o}`,o+=1;return i}function hc(){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:_i,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 gs({slug:t,isMobile:s,runtimeCtx:n,openChamberSectionBySlug:i}){const o=Xt(t);if(o&&!_n(o,n))return e.jsx(hc,{});switch(t){case"projects":return e.jsx(ao,{});case"remote-instances":return e.jsx(go,{});case"behavior":return e.jsx(Xi,{});case"skills.installed":return e.jsx(to,{});case"providers":return e.jsx(Do,{});case"about":return e.jsx(Ie,{title:s?void 0:"About",children:e.jsx(yn,{})});case"snippets":return e.jsx(zo,{});case"prompt-templates":return e.jsx(Bo,{});case"dictation":return e.jsx(uc,{});case"git":return e.jsx(Wo,{});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"tunnel":{const p=i[t]??"visual";return e.jsx(ec,{section:p})}default:return null}}const gc=["general","projects","agent"];function fc({isMobile:t,isMobileSettingsSearchOpen:s,settingsSearchQuery:n,setSettingsSearchQuery:i,handleSettingsSearchKeyDown:o,settingsSearchResults:p,groupedSettingsSearchResults:h,activeSearchResultIndex:u,setActiveSearchResultIndex:d,searchResultRefs:w,keyboardSearchNavigationRef:c,openSearchResult:g,sortedFilteredPages:r,settingsSlug:f,mobileStage:y,openPage:b,getPageTitle:j,activeRemoteLabel:A,mobileAppActions:I}){const P=n.trim().length>0,E=t?s&&P:P;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[t?E?null:e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>{if(I?.openInstances){I.openInstances();return}b("remote-instances")},className:J("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",A?"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:A?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:A}),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 instances & 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 instances & pair devices"})]})}),e.jsx(T,{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(T,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{value:n,onChange:N=>i(N.target.value),onKeyDown:o,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"}),P&&e.jsx("button",{type:"button",onClick:()=>i(""),"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(T,{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:E?p.length>0?(()=>{let N=0;return h.map(x=>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:x.pageTitle}),x.results.map(D=>{const k=N;N+=1;const m=k===u,v=!!D.description;return e.jsxs("button",{type:"button",ref:C=>{w.current[k]=C},onMouseMove:()=>{c.current=!1,d(k)},onClick:()=>g(D),className:J("flex w-full flex-col rounded-md px-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",v?"min-h-11 py-1.5":"py-2",m?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:D.title}),v&&e.jsx("span",{className:"typography-micro text-muted-foreground/70 line-clamp-2",children:D.description})]},D.id)})]},x.page))})():e.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:"No matching settings"}):(()=>{const N=new Map;for(const D of r){const k=D.group,m=N.get(k);m?m.push(D):N.set(k,[D])}return gc.map(D=>({group:D,pages:N.get(D)??[]})).filter(D=>D.pages.length>0).map(({group:D,pages:k},m)=>{const v=D==="projects"?"Workspace":D==="agent"?"Agent":null;return e.jsxs("div",{className:"space-y-0.5",children:[v?e.jsx("div",{className:J("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",m===0?"pt-1":"pt-4 sm:pt-3"),children:v}):null,k.map(C=>{const L=f===C.slug&&!(t&&y==="nav"),B=Oi(C.slug);return B?e.jsx(hn,{children:e.jsx(gn,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>b(C.slug),"aria-current":L?"page":void 0,className:J("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",L?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[e.jsx(T,{name:B,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:j(C.slug)}),C.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"})]})]})})},C.slug):null})]},D)})})()})})]})}function xc(t){const[s,n]=a.useState(null);return a.useEffect(()=>{const i=async()=>{try{const{loadMobileConnections:h,isActiveRuntimeConnection:u}=await Zt(async()=>{const{loadMobileConnections:c,isActiveRuntimeConnection:g}=await import("./renderMobileApp-C5CdsYP6.js").then(r=>r.m);return{loadMobileConnections:c,isActiveRuntimeConnection:g}},__vite__mapDeps([79,2,3,80,81,4,1,5,6,7,8,82,0,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,83,84,85,86,87,88,89])),w=(await h().catch(()=>[])).find(c=>u(c));if(w){n(w.label);return}}catch{}if(t){n(t);return}try{const{desktopHostsGet:h}=await Zt(async()=>{const{desktopHostsGet:y}=await import("./index-CaP8oFLB.js").then(b=>b.ch);return{desktopHostsGet:y}},__vite__mapDeps([4,1,2,3,5,6,7,8])),{buildLocalDesktopHost:u,getLocalDesktopOrigin:d,resolveCurrentDesktopHost:w}=await Zt(async()=>{const{buildLocalDesktopHost:y,getLocalDesktopOrigin:b,resolveCurrentDesktopHost:j}=await import("./index-CaP8oFLB.js").then(A=>A.ci);return{buildLocalDesktopHost:y,getLocalDesktopOrigin:b,resolveCurrentDesktopHost:j}},__vite__mapDeps([4,1,2,3,5,6,7,8])),c=await h().catch(()=>({hosts:[]})),r=[u(d()),...c.hosts],f=w(r);if(f&&f.label&&f.label!=="Instance"){n(f.label);return}}catch{}const o=Ut(),p=it();if(p==="local"){n("Local");return}if(p.startsWith("relay:")){const h=p.split(":")[1]?.split("@")[0];n(h?`Relay ${h.slice(0,8)}`:"Private relay");return}if(p.startsWith("host:")){n(p.replace("host:",""));return}if(o)try{const h=new URL(o);n(h.host);return}catch{n(o);return}n(null)};return i(),ia(()=>{i()})},[t]),s}const bc=[{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.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.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:"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:"chat.reasoning-traces",page:"chat",title:"Show Reasoning Traces",keywords:["thinking","reasoning"]},{id:"chat.collapsible-reasoning",page:"chat",title:"Enable Collapsible Reasoning Blocks",keywords:["thinking","reasoning","collapse","expand"]},{id:"chat.collapsed-reasoning-default",page:"chat",title:"Collapsed by Default",description:"Open thinking while it streams, then fold it. Turn off to keep a one-line trace unless you expand it.",keywords:["thinking","reasoning","collapse","default"]},{id:"chat.reasoning",page:"chat",title:"Reasoning",keywords:["thinking","traces"]},{id:"chat.sticky-user-header",page:"chat",title:"Sticky User Header",keywords:["messages","header"]},{id:"chat.prompt-navigator",page:"chat",title:"Prompt Navigator",keywords:["prompt","navigator","navigation","timeline","scroll"]},{id:"chat.collapsible-user-messages",page:"chat",title:"Collapse Long User Messages",keywords:["collapse","expand","clamp","long messages","user messages"]},{id:"chat.wide-layout",page:"chat",title:"Wide Chat Layout",keywords:["layout","wide","messages"]},{id:"chat.message-appearance",page:"chat",title:"Message Appearance",keywords:["layout","messages","appearance"]},{id:"chat.code-block-line-wrap",page:"chat",title:"Wrap Code Block Lines",keywords:["code","wrap","line wrap","markdown"]},{id:"chat.inline-assistant-actions",page:"chat",title:"Inline Assistant Actions",description:"Show Copy Answer, Save as image, and Read aloud on assistant text blocks that appear before later tool calls in the same response.",keywords:["copy","save image","read aloud"]},{id:"chat.draft-starters-visible",page:"chat",title:"Show Starters on New Session Screen",keywords:["starter","starters","new session","welcome","suggestions"]},{id:"chat.tool-file-icons",page:"chat",title:"Show Tool File Icons",keywords:["tools","files","icons"]},{id:"chat.tools-and-files",page:"chat",title:"Tools & Files",keywords:["tools","files","dotfiles"]},{id:"chat.changed-files",page:"chat",title:"Show Changed Files for Completed Turns",keywords:["changed files","turns"]},{id:"chat.dotfiles",page:"chat",title:"Show Dotfiles",keywords:["hidden files"]},{id:"chat.follow-up-behavior",page:"chat",title:"Follow-up behavior",description:"Choose what happens when you press Enter on a follow-up message while the agent is still responding.",keywords:["follow up","queue","steer","send immediately"]},{id:"chat.persist-drafts",page:"chat",title:"Persist Draft Messages",keywords:["draft","message"]},{id:"chat.composer",page:"chat",title:"Composer",keywords:["input","draft","spellcheck"]},{id:"chat.spellcheck",page:"chat",title:"Enable Spellcheck in Text Inputs",keywords:["spelling","input"]},{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.isDesktopLocalOrigin},{id:"sessions.desktop-window-controls-position",page:"appearance",title:"Window controls position",description:"Choose where minimize, maximize, and close buttons appear. Defaults to the right.",keywords:["desktop","window","controls","minimize","maximize","close","titlebar","linux","windows"],isAvailable:t=>t.isDesktop&&(t.isWindows||!t.isMac)},{id:"sessions.desktop-window-controls-style",page:"appearance",title:"Style",keywords:["desktop","window","controls","style","traffic","lights","classic","macos","titlebar"],isAvailable:t=>t.isDesktop&&(t.isWindows||!t.isMac)},{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 and close to the system tray",description:"Keeps PiChamber running in the system tray when the main window is minimized or closed.",keywords:["desktop","tray","system tray","minimize","close","background","windows","linux"],isAvailable:t=>t.isDesktopLocalOrigin&&(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.isDesktopLocalOrigin},{id:"sessions.desktop-ui-password",page:"general",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"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-lan-access",page:"general",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"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"git.github-account",page:"git",title:"Connect GitHub",keywords:["github","account","oauth","prs","issues"]},{id:"git.identities",page:"git",title:"Identities",description:"Create one to manage Git author settings per project",keywords:["identity","profile","author","email","credentials","signing","commit signing","ssh signing","gpg"]},{id:"git.changes-view",page:"git",title:"Changes View",keywords:["changes","flat list","tree view"]},{id:"git.gitmoji",page:"git",title:"Enable Gitmoji Picker",keywords:["commit","emoji"]},{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-instances.client-auth",page:"remote-instances",title:"Connect to this server",description:"Create a secure link or token so PiChamber Desktop can connect to this server.",keywords:["pairing link","client token","connect desktop","remote access","relay","devices","connect from anywhere"]},{id:"remote-instances.direct-hosts",page:"remote-instances",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 url","connection token","import link","host switcher","additional headers","request headers","cloudflare access","service token"],isAvailable:t=>t.isDesktop},{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 quick links or your own managed remote Cloudflare tunnel.",keywords:["remote access","cloudflare"]},{id:"tunnel.type",page:"tunnel",title:"Tunnel type",keywords:["quick","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","system notifications"]},{id:"notifications.events",page:"notifications",title:"Notification Events",keywords:["completion","subtasks","errors","questions"]},{id:"notifications.push",page:"notifications",title:"Background Push Notifications",keywords:["background","push"],isAvailable:t=>t.isWeb&&!t.isDesktop}];function en(t){return t.trim().toLocaleLowerCase()}function vc({query:t,runtimeCtx:s,visiblePageSlugs:n,getPageTitle:i}){const o=en(t);if(!o)return[];const p=n?new Set(n):null,h=o.split(/\s+/).filter(Boolean);return bc.flatMap(u=>{if(p&&!p.has(u.page))return[];const d=Xt(u.page);if(!d||d.isAvailable&&!d.isAvailable(s)||u.isAvailable&&!u.isAvailable(s))return[];const w=u.title,c=u.description??null,g=en([w,c,i(u.page),...u.keywords??[]].filter(Boolean).join(" "));return h.every(r=>g.includes(r))?[{...u,title:w,description:c,pageTitle:i(u.page)}]:[]})}function yc({runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n,openPage:i,isMobile:o,setMobileStage:p,containerRef:h,settingsSlug:u}){const[d,w]=a.useState(""),[c,g]=a.useState(!1),r=a.useRef(null),[f,y]=a.useState(null),[b,j]=a.useState(0),A=a.useRef([]),I=a.useRef(0),P=a.useRef(!1),E=a.useMemo(()=>vc({query:d,runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n}),[n,t,d,s]),N=a.useCallback(m=>{if(m.id.startsWith("snippets.")){const v=et.getState(),C=Za("new-snippet",v.snippets.map(L=>L.name));return v.setSnippetDraft({name:C,scope:"global"}),v.setSelectedSnippet(null),m.id==="snippets.create"?"snippets.content":m.id}if(m.id.startsWith("prompt-templates.")){const v=tt.getState(),C=Za("new-prompt",v.prompts.map(L=>L.name));return v.setPromptDraft({name:C,location:"global"}),v.setSelectedPrompt(null),m.id==="prompt-templates.create"?"prompt-templates.content":m.id}return m.id==="providers.connect"&&sa.getState().setSelectedProviderId(null),m.id},[]),x=a.useMemo(()=>{const m=[],v=new Map;for(const C of E){let L=v.get(C.page);L||(L={page:C.page,pageTitle:C.pageTitle,results:[]},v.set(C.page,L),m.push(L)),L.results.push(C)}return m},[E]);a.useEffect(()=>{j(0),I.current=0,P.current=!1},[d]),a.useEffect(()=>{I.current=b},[b]),a.useEffect(()=>{A.current[b]?.scrollIntoView({block:"nearest"})},[b]),a.useEffect(()=>{b>=E.length&&j(Math.max(0,E.length-1)),A.current.length=E.length},[b,E.length]);const D=a.useCallback(m=>{const v=N(m);y(v),i(m.page),o&&p("page-content")},[o,i,N,p]),k=a.useCallback(m=>{if(m.key==="Escape"){if(m.preventDefault(),d.trim()){w("");return}o&&c&&g(!1);return}if(d.trim()&&E.length!==0){if(m.key==="ArrowDown"){m.preventDefault(),P.current=!0,j(v=>(v+1)%E.length);return}if(m.key==="ArrowUp"){m.preventDefault(),P.current=!0,j(v=>(v-1+E.length)%E.length);return}if(m.key==="Enter"){m.preventDefault();const v=(I.current%E.length+E.length)%E.length,C=E[v]??E[0];C&&D(C)}}},[o,c,D,d,E]);return a.useEffect(()=>{const m=f;if(!m)return;let v=!1;const C=window.requestAnimationFrame(()=>{if(v)return;const L=typeof CSS<"u"&&CSS.escape?CSS.escape(m):m.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),B=h.current?.querySelector(`[data-settings-item="${L}"]`);B&&(y(null),B.scrollIntoView({block:"center",behavior:"smooth"}),B.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{B.removeAttribute("data-settings-search-highlight")},1600))});return()=>{v=!0,window.cancelAnimationFrame(C)}},[h,f,u]),{settingsSearchQuery:d,setSettingsSearchQuery:w,isMobileSettingsSearchOpen:c,setIsMobileSettingsSearchOpen:g,mobileSettingsSearchInputRef:r,activeSearchResultIndex:b,setActiveSearchResultIndex:j,searchResultRefs:A,keyboardSearchNavigationRef:P,settingsSearchResults:E,groupedSettingsSearchResults:x,openSearchResult:D,handleSettingsSearchKeyDown:k}}const jc=({mobileStage:t,activePageMeta:s,getPageTitle:n,showBackButton:i,mobileBackButtonLabel:o,onBack:p,showOpenPageSidebarButton:h,onOpenPageSidebar:u,isMobileSettingsSearchOpen:d,setIsMobileSettingsSearchOpen:w,mobileSettingsSearchInputRef:c,settingsSearchQuery:g,setSettingsSearchQuery:r,handleSettingsSearchKeyDown:f,onClose:y,shortcutKey:b})=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:J("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:[i?e.jsx("button",{type:"button",onClick:p,"aria-label":o,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(T,{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?n(s.slug):"Settings"}),h&&e.jsx("button",{type:"button",onClick:u,"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(T,{name:"list-unordered",className:"h-5 w-5"})}),t==="nav"?e.jsx("button",{type:"button",onClick:()=>{const j=!d;w(j),j?window.setTimeout(()=>c.current?.focus(),0):r("")},"aria-label":d?"Close search":"Search settings","aria-expanded":d,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(T,{name:d?"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(T,{name:"close",className:"h-5 w-5"})})]}),t==="nav"&&d?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(T,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{ref:c,value:g,onChange:j=>r(j.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"}),g.trim().length>0?e.jsx("button",{type:"button",onClick:()=>r(""),"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(T,{name:"close",className:"h-3.5 w-3.5"})}):null]})}):null]}),wc=({onClose:t,forceMobile:s,isWindowed:n,visiblePageSlugs:i,initialMobileStage:o="nav"})=>{const p=Ve(),h=s??p.isMobile,u=Pi(),d=xc(u?.instanceLabel),w=_(ce=>ce.settingsPage),c=_(ce=>ce.isSettingsDialogOpen),g=_(ce=>ce.setSettingsPage),r=Ui(w),[f,y]=a.useState(o),b=a.useRef(o==="nav"?r:null);a.useEffect(()=>{!h&&r==="home"&&g("general")},[h,g,r]);const j=a.useRef(null),A=a.useMemo(()=>Re(),[]),I=a.useMemo(()=>Re()&&es(),[]),P=a.useMemo(()=>Re()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),E=a.useMemo(()=>Re()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="win32",[]),N=a.useMemo(()=>Re()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="linux",[]),x=a.useMemo(()=>Zr(),[]),D=a.useMemo(()=>pc(A,h),[A,h]),k=a.useMemo(()=>{const ce=i?new Set(i):null;return Fi.filter(G=>G.slug!=="home").filter(G=>!ce||ce.has(G.slug)).filter(G=>_n(G,D)).filter(G=>!(h&&G.slug==="remote-instances"))},[h,D,i]),m=a.useMemo(()=>{const ce=new Map(mc.map((G,ne)=>[G,ne]));return k.slice().sort((G,ne)=>(ce.get(G.slug)??999)-(ce.get(ne.slug)??999))},[k]),v=bs(ce=>ce.activeProjectId);a.useEffect(()=>{!c&&!n||r==="skills.installed"&&kt.getState().loadSkills()},[v,c,n,r]);const C=a.useCallback(ce=>{if(g(ce),b.current=ce,!h)return;const G=Xt(ce);if(!G||G.slug==="home"){y("nav");return}y(G.kind==="split"?"page-sidebar":"page-content")},[h,g]),L=a.useMemo(()=>Xt(r),[r]),B=a.useMemo(()=>({general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",tunnel:"tunnel"}),[]),q=a.useCallback(ce=>{switch(ce){case"general":return"General";case"projects":return"Projects";case"remote-instances":return"Remote Instances";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"}},[]),Y=a.useMemo(()=>({...D,isDesktopLocalOrigin:I,isMac:P,isWindows:E,isLinux:N,isWindowsArm64:x}),[I,N,P,E,x,D]),{settingsSearchQuery:$,setSettingsSearchQuery:V,isMobileSettingsSearchOpen:oe,setIsMobileSettingsSearchOpen:xe,mobileSettingsSearchInputRef:je,activeSearchResultIndex:z,setActiveSearchResultIndex:O,searchResultRefs:X,keyboardSearchNavigationRef:H,settingsSearchResults:M,groupedSettingsSearchResults:W,openSearchResult:se,handleSettingsSearchKeyDown:ye}=yc({runtimeCtx:Y,visiblePageSlugs:i,getPageTitle:q,openPage:C,isMobile:h,setMobileStage:y,containerRef:j,settingsSlug:r});a.useEffect(()=>{if(!h||f!=="nav"||r==="home"||b.current===r)return;const ce=Xt(r);!ce||ce.slug==="home"||(b.current=r,y(ce.kind==="split"?"page-sidebar":"page-content"))},[h,f,r]);const K=h&&f!=="nav",re=f==="page-content"&&L?.kind==="split",fe=K?"Back to Settings":"Close settings",be=ei(),pe=a.useCallback(()=>{y("page-content")},[]),Q=a.useCallback(()=>{y("nav")},[]),U=a.useCallback(()=>{y("page-sidebar")},[]);a.useEffect(()=>{(!h||f!=="nav")&&xe(!1)},[h,f,xe]);const ae=a.useCallback((ce,G)=>null,[]),R=()=>e.jsx(fc,{isMobile:h,isMobileSettingsSearchOpen:oe,settingsSearchQuery:$,setSettingsSearchQuery:V,handleSettingsSearchKeyDown:ye,settingsSearchResults:M,groupedSettingsSearchResults:W,activeSearchResultIndex:z,setActiveSearchResultIndex:O,searchResultRefs:X,keyboardSearchNavigationRef:H,openSearchResult:se,sortedFilteredPages:m,settingsSlug:r,mobileStage:f,openPage:C,getPageTitle:q,activeRemoteLabel:d,mobileAppActions:u}),Z=()=>{if(f==="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(ft,{children:R()})})});if(!L)return e.jsx("div",{className:"flex-1 bg-background"});if(f==="page-sidebar"){if(L.kind!=="split"){const ce=e.jsx(gs,{slug:r,isMobile:h,runtimeCtx:D,openChamberSectionBySlug:B});return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(ft,{children:ce})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(ft,{children:ae(r,{onItemSelect:pe})})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(ft,{children:e.jsx(gs,{slug:r,isMobile:h,runtimeCtx:D,openChamberSectionBySlug:B})})})},le=()=>!L||r==="home"?null:L.kind==="split"?e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[e.jsx("div",{className:J("border-r","bg-sidebar"),style:{width:Xa,minWidth:Xa,borderColor:"var(--interactive-border)"},children:e.jsx(ft,{children:ae(r,{})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(ft,{children:e.jsx(gs,{slug:r,isMobile:h,runtimeCtx:D,openChamberSectionBySlug:B})})})]}):e.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(ft,{children:e.jsx(gs,{slug:r,isMobile:h,runtimeCtx:D,openChamberSectionBySlug:B})})});return e.jsxs("div",{ref:j,"data-settings-view":"true",className:J("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),children:[h?e.jsx(jc,{mobileStage:f,activePageMeta:L,getPageTitle:q,showBackButton:K,mobileBackButtonLabel:fe,onBack:Q,showOpenPageSidebarButton:!!re,onOpenPageSidebar:U,isMobileSettingsSearchOpen:oe,setIsMobileSettingsSearchOpen:xe,mobileSettingsSearchInputRef:je,settingsSearchQuery:$,setSettingsSearchQuery:V,handleSettingsSearchKeyDown:ye,onClose:t,shortcutKey:be}):e.jsx(e.Fragment,{children:K&&e.jsx("div",{className:J("absolute left-3 z-50",n?"top-2":"top-3"),children:e.jsx("button",{type:"button",onClick:Q,"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(T,{name:"arrow-left-s",className:"h-5 w-5"})})})}),e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:h?Z():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:J("relative flex h-full min-h-0 flex-col overflow-hidden border-r","bg-sidebar"),style:{width:`${Ya}px`,minWidth:`${Ya}px`,borderColor:"var(--interactive-border)"},children:e.jsx(ft,{children:R()})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:le()})]})})]})},Ac=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:wc},Symbol.toStringTag,{value:"Module"}));export{yn as A,wc as S,Ac as a};
|