@pi-chamber/web 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bin/lib/cli-startup.js +53 -10
  2. package/bin/lib/cli-startup.test.js +42 -0
  3. package/dist/assets/{CommitSection-BpbMC0et.js → CommitSection-DLIvjYbM.js} +1 -1
  4. package/dist/assets/{DiagramEditor-dFTMKHuO.js → DiagramEditor-Tw3ZWHML.js} +1 -1
  5. package/dist/assets/{DiagramView-DVw_8Px1.js → DiagramView-CK6R7taL.js} +1 -1
  6. package/dist/assets/{DiffView-CkoY1oAM.js → DiffView-vrxi5oWp.js} +2 -2
  7. package/dist/assets/{FilesView-C0hyg2pa.js → FilesView-BD_h3EVr.js} +6 -6
  8. package/dist/assets/{GitView-D36hpDsb.js → GitView-BwNKqK0K.js} +4 -4
  9. package/dist/assets/{JsonTreeView-BF8S-bPN.js → JsonTreeView-CmY7QgEX.js} +1 -1
  10. package/dist/assets/{MarkdownRendererImpl-BVNChdig.js → MarkdownRendererImpl-CpI-25Xk.js} +1 -1
  11. package/dist/assets/{PatchDiff-B--OaNB1.js → PatchDiff-CrIWbYj7.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-0Qkp9ICt.js → PierreDiffViewer-B410mdbq.js} +2 -2
  13. package/dist/assets/{SessionSwitcherDropdown-cFWgy1td.js → SessionSwitcherDropdown-DROjbyIu.js} +100 -100
  14. package/dist/assets/SettingsView-CsJItYZh.js +4 -0
  15. package/dist/assets/{SettingsWindow-BuJCvYoR.js → SettingsWindow-C9s4AX72.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-Bi9BoEe7.js → ToolOutputDialog-b_R4tAZu.js} +5 -5
  17. package/dist/assets/{ToolPartDiffPreview-DGX7N4zr.js → ToolPartDiffPreview-CfnliaE9.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-CxraYoDZ.js → VirtualizedFileDiff-CQz2fSZI.js} +4 -4
  19. package/dist/assets/{collapsible-d4-HChej.js → collapsible-CR4U9tjw.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-BuD14qFL.js → computeVirtualFileMetrics-C7vXPUYT.js} +2 -2
  21. package/dist/assets/{contextFileOpenGuard-DirV-hCs.js → contextFileOpenGuard-DtTHRnq1.js} +1 -1
  22. package/dist/assets/{index-DEYblXCW.js → index-BAqpUCjs.js} +5 -5
  23. package/dist/assets/{index-BWmmf5yJ.js → index-DZG82DE1.js} +1 -1
  24. package/dist/assets/{index-DLKBsLKY.css → index-riABQmQ_.css} +1 -1
  25. package/dist/assets/{isDiffPlainText-LoMmNzmX.js → isDiffPlainText-zTq-4A04.js} +1 -1
  26. package/dist/assets/{isFilePlainText-3Hj9i02t.js → isFilePlainText-CLgIdzE5.js} +1 -1
  27. package/dist/assets/{main-BsszlAdQ.js → main-BVWtJYSk.js} +2 -2
  28. package/dist/assets/main-DXYHsqzA.js +133 -0
  29. package/dist/assets/{markdownCore-sGxk8jrc.js → markdownCore-CN0pApQE.js} +2 -2
  30. package/dist/assets/{miniChat-C6SDQL4G.js → miniChat-BrbRq5NQ.js} +2 -2
  31. package/dist/assets/{mobile-DBW3XDmZ.js → mobile-DTPtCn5N.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-B1_fTdN-.js → renderElectronMiniChatApp-CM8qBaye.js} +1 -1
  33. package/dist/assets/{renderMobileApp-CFxZc_1a.js → renderMobileApp-KS_pt-qc.js} +4 -4
  34. package/dist/assets/{runtimeSurface-9aJdtQbh.js → runtimeSurface-CkHYYg0E.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-Cl--s6vE.js → useInlineCommentController-CwNNjgc7.js} +2 -2
  36. package/dist/assets/usePanelSlide-DkorgQJ5.js +56 -0
  37. package/dist/assets/{useWindowTitle-C-AZD713.js → useWindowTitle-B9wt_3ZQ.js} +3 -3
  38. package/dist/assets/{vendor-codemirror-language-data-HC9JT4I3.js → vendor-codemirror-language-data-x89A7Wy0.js} +2 -2
  39. package/dist/assets/{vendor-sonner-dWA7qvjr.js → vendor-sonner-CW8w438f.js} +1 -1
  40. package/dist/assets/{web-components-skJ_VpnT.js → web-components-BEPfE4kU.js} +2 -2
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/index.js +33 -0
  46. package/server/lib/pi/routes.js +24 -2
  47. package/server/lib/pi/routes.test.js +14 -6
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -3
  49. package/server/lib/pi/session-daemon/message-entry-aliases.js +100 -0
  50. package/server/lib/pi/session-daemon/session-daemon.js +176 -46
  51. package/server/lib/pi/session-daemon/session-daemon.test.js +364 -6
  52. package/server/lib/pi/session-daemon/supervisor.js +20 -1
  53. package/server/lib/pi/session-daemon/supervisor.test.js +43 -0
  54. package/server/lib/pi/settings-store.js +17 -0
  55. package/server/lib/pi/settings-store.test.js +33 -0
  56. package/server/lib/server/core-routes.js +36 -4
  57. package/server/lib/server/tunnel-service.DOCUMENTATION.md +74 -0
  58. package/server/lib/server/tunnel-service.js +228 -0
  59. package/server/lib/server/tunnel-service.test.js +61 -0
  60. package/server/lib/ui-auth/DOCUMENTATION.md +2 -0
  61. package/server/lib/ui-auth/ui-auth.js +5 -1
  62. package/server/lib/ui-auth/ui-auth.test.js +17 -0
  63. package/dist/assets/SettingsView-D3ZZyjU3.js +0 -4
  64. package/dist/assets/main-CUvZIN16.js +0 -133
  65. package/dist/assets/usePanelSlide-D5ffPTGM.js +0 -56
@@ -0,0 +1,4 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionSwitcherDropdown-DROjbyIu.js","assets/index-BAqpUCjs.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-riABQmQ_.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-CkHYYg0E.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-x89A7Wy0.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-CW8w438f.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/renderMobileApp-KS_pt-qc.js","assets/vendor-katex-CHD9BdDO.js","assets/vendor-katex-Cp579UoJ.css","assets/useWindowTitle-B9wt_3ZQ.js","assets/usePanelSlide-DkorgQJ5.js","assets/permissionStore-BRcQ9Jgt.js","assets/usePanelSlide-BV3KOtdA.css","assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/CommitSection-DLIvjYbM.js","assets/PierreDiffViewer-B410mdbq.js","assets/web-components-BEPfE4kU.js","assets/computeVirtualFileMetrics-C7vXPUYT.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/VirtualizedFileDiff-CQz2fSZI.js","assets/isDiffPlainText-zTq-4A04.js","assets/vendor-diff-C3JhlQdm.js","assets/useInlineCommentController-CwNNjgc7.js","assets/collapsible-CR4U9tjw.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-remixicon-react-CzPq62YO.js"])))=>i.map(i=>d[i]);
2
+ import{_ as pa}from"./vendor-vite-runtime-DD1OZmLC.js";import{R as s,j as e,r as he}from"./vendor-react-DYyjh7Q0.js";import{B as h,I as f,o as Nn,aQ as Mt,t as R,P as oi,D as wt,w as jt,x as Pt,y as Tt,z as It,A as ga,ay as Sn,f as J,bf as Nr,dY as Ns,Y as ne,as as Sr,at as Cr,au as Pr,az as Tr,b as La,a_ as li,C as Ir,av as en,dZ as ci,d_ as di,aI as ui,bg as Mn,bw as Qe,bx as Ye,by as Je,bz as Xe,bA as Me,d$ as mi,bD as Er,a5 as We,e0 as Ra,e1 as Ar,e2 as Mr,e3 as Lr,e4 as Da,e5 as tn,e6 as Ln,e7 as pi,e8 as hi,e9 as gi,ea as fi,eb as Ot,aL as xi,ec as bi,ed as vi,ee as yi,ef as wi,eg as sn,eh as Rn,ei as ji,ej as ki,ek as Ni,el as Si,bG as Ci,T as Rr,q as Dr,s as Pi,em as Ti,en as Ii,eo as ns,b2 as Dn,ep as _n,eq as an,aR as Ei,b1 as On,er as _r,cs as Ai,dF as Mi,X as us}from"./SessionSwitcherDropdown-DROjbyIu.js";import{r as ht,au as et,a as Zt,u as T,J as at,al as zn,b7 as Fn,ba as Un,am as oa,p as Li,bK as Ri,k as Di,b6 as Hs,bL as _i,ar as Oi,b9 as zi,bM as Fi,bN as Ui,s as Bi,e as qs,b8 as Hi,Q as fa,bO as Or,S as Ws,B as Vi,T as Ie,bP as $i,q as ha,A as Ki,a4 as Bn,bE as Wi,bz as Gi,az as qi,K as ps,bQ as Qi,w as Cn,bR as Hn,bD as Vn,bS as $n,ac as Kn,bT as Yi,bU as Ji,by as Xi,bV as Wn,b as Zi,a9 as eo,bW as to,bX as so,bY as ao,bZ as no,b_ as ro,b$ as io,c0 as oo,i as zr,c1 as lo}from"./index-BAqpUCjs.js";import{u as co,G as uo,U as Gn,I as te,J as st,K as hn,L as mo,N as Fr,O as Ur,Q as po,R as lt,V as _a,W as Xt,X as ho,Y as tt,Z as rs,_ as qn,$ as qe,a0 as Gs,a1 as yt,a2 as ct,a3 as Br,a4 as Et,a5 as Vs,a6 as Ss,a7 as Cs,a8 as ve,a9 as ua,p as go,q as fo,t as xo,v as bo,aa as ms,ab as Oa,ac as Aa,ad as js,ae as Qn,af as $s,ag as Ks,ah as nn,ai as Yn,aj as ma,ak as Hr,z as vo,al as yo,B as wo}from"./usePanelSlide-DkorgQJ5.js";import{Q as Vr}from"./vendor-qrcode-COsmt6jn.js";import{W as jo,X as ko}from"./vendor-base-ui-DL8r2fgQ.js";import{C as $r,a as Kr,b as Wr}from"./collapsible-CR4U9tjw.js";import{u as Gr,c as qr}from"./vendor-zustand-CnsBKjP5.js";import{g as No,s as So}from"./runtimeSurface-CkHYYg0E.js";const Jn=()=>{const[t,r]=s.useState(null);s.useEffect(()=>{let o=!1;const c=typeof AbortController<"u"?new AbortController:void 0;return(async()=>{try{const v=await ht("/api/system/info",{signal:c?.signal,headers:{Accept:"application/json"}});if(!v.ok)return;const x=await v.json().catch(()=>null);if(!x||o)return;const g=typeof x.port=="number"&&Number.isFinite(x.port)&&x.port>0?x.port:null,L=typeof x.tunnelUrl=="string"&&x.tunnelUrl.trim().length>0?x.tunnelUrl.trim():null;r({port:g,tunnelUrl:L})}catch{}})(),()=>{o=!0,c?.abort()}},[]);const i=[];return t?.port!==null&&t?.port!==void 0&&i.push({key:"application",label:"Application",url:`http://localhost:${t.port}/`}),t?.tunnelUrl&&i.push({key:"tunnel",label:"Tunnel",url:t.tunnelUrl}),i.length===0?null:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:i.map(o=>e.jsxs(h,{type:"button",variant:"outline",size:"sm",title:o.label,className:"max-w-full gap-1.5 px-2.5",onClick:()=>{Nn(o.url)},children:[e.jsx(f,{name:"external-link",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"max-w-64 truncate font-mono typography-micro",children:o.url})]},o.key))})},gn="https://github.com/RyderAsKing/PiChamber",fn="https://pi.dev/",Co=800,Qr=({initialUpdateDialogOpen:t=!1})=>{const[r,i]=s.useState(t),[o,c]=s.useState(!1),[w,v]=s.useState(null),x=co(Gr(u=>({info:u.info,checking:u.checking,available:u.available,error:u.error,downloading:u.downloading,downloaded:u.downloaded,progress:u.progress,runtimeType:u.runtimeType,checkForUpdates:u.checkForUpdates,downloadUpdate:u.downloadUpdate,restartToUpdate:u.restartToUpdate}))),{isMobile:g}=Mt(),L=w||x.info?.currentVersion||"unknown";s.useEffect(()=>{let u=!1;return(async()=>{try{const A=await ht("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!A.ok)return;const F=await A.json().catch(()=>null),H=typeof F?.pichamberVersion=="string"&&F.pichamberVersion.trim().length>0?F.pichamberVersion.trim():null;u||v(H)}catch{u||v(null)}})(),()=>{u=!0}},[]);const p=s.useRef(!1);s.useEffect(()=>{if(x.checking)c(!0),p.current=!0;else if(o){const u=setTimeout(()=>{c(!1),p.current&&!x.available&&!x.error&&(R.success("You are on the latest version"),p.current=!1)},Co);return()=>clearTimeout(u)}},[x.checking,o,x.available,x.error]);const j=x.checking||o;return g?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(oi,{width:72,height:72}),e.jsx("h2",{className:`mt-4 ${uo}`,children:"PiChamber"}),e.jsx("div",{className:"mt-2 space-y-1 typography-ui text-muted-foreground",children:e.jsx("p",{children:`PiChamber version ${L}`})}),e.jsx(Jn,{})]}),e.jsxs("div",{className:"flex justify-center",children:[!x.available&&!x.error&&e.jsxs(h,{type:"button",variant:"outline",size:"sm",onClick:()=>x.checkForUpdates(),disabled:j,className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[j?e.jsx(f,{name:"loader",className:"size-4 animate-spin"}):e.jsx(f,{name:"refresh",className:"size-4"}),j?"Checking...":"Check for updates"]}),!j&&x.available&&e.jsxs(h,{type:"button",variant:"default",size:"sm",onClick:()=>i(!0),className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[e.jsx(f,{name:"download",className:"size-4"}),`Update to ${x.info?.version||""}`]})]}),x.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:x.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:gn,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(f,{name:"github-fill",className:"size-5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:fn,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(f,{name:"information",className:"size-5"}),e.jsx("span",{children:"Pi Agent"})]})]})}),e.jsx(Xn,{}),e.jsx("p",{className:"text-center typography-ui text-muted-foreground/60",children:"Made with care for the community"}),e.jsx(Gn,{open:r,onOpenChange:i,info:x.info,downloading:x.downloading,downloaded:x.downloaded,progress:x.progress,error:x.error,onDownload:x.downloadUpdate,onRestart:x.restartToUpdate,runtimeType:x.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:st,children:"Version"}),e.jsx("span",{className:"typography-meta text-muted-foreground font-mono",children:L})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[x.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(f,{name:"loader",className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!x.checking&&x.available&&e.jsxs(h,{size:"sm",variant:"default",onClick:()=>i(!0),children:[e.jsx(f,{name:"download",className:"h-4 w-4 mr-1"}),`Update to ${x.info?.version||""}`]}),!x.checking&&!x.available&&!x.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"}),e.jsx(h,{size:"sm",variant:"outline",onClick:()=>x.checkForUpdates(),disabled:x.checking,children:"Check for updates"})]})]}),x.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:x.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:st,children:"Instance URLs"}),e.jsx(Jn,{})]}),e.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[e.jsxs("a",{href:gn,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(f,{name:"github-fill",className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:fn,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(f,{name:"information",className:"h-4 w-4"}),e.jsx("span",{children:"Pi Agent"})]})]})]}),e.jsx(Gn,{open:r,onOpenChange:i,info:x.info,downloading:x.downloading,downloaded:x.downloaded,progress:x.progress,error:x.error,onDownload:x.downloadUpdate,onRestart:x.restartToUpdate,runtimeType:x.runtimeType})]}),e.jsx(Xn,{})]})},Xn=()=>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:fn,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:gn,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"})]})})]}),is=({onResolved:t})=>{const[r,i]=s.useState(!1),[o,c]=s.useState(!1);s.useEffect(()=>{let v=!0;return et.getSettings({runtimeKey:Zt()}).then(x=>{v&&i(x.pi.project.requiresTrust===!0)}).catch(()=>{}),()=>{v=!1}},[]);const w=async v=>{c(!0);try{await et.setPiSettings({scope:"project",trust:v},{runtimeKey:Zt()}),i(!1),t?.()}finally{c(!1)}};return e.jsx(wt,{open:r,onOpenChange:()=>{},children:e.jsxs(jt,{className:"max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Trust this project?"}),e.jsx(It,{children:"This project contains Pi settings, skills, prompts, or extensions. Trusting it allows Pi to load those project resources."})]}),e.jsxs(ga,{children:[e.jsx(h,{variant:"ghost",size:"sm",disabled:o,onClick:()=>{w(!1)},children:"Keep untrusted"}),e.jsx(h,{size:"sm",disabled:o,onClick:()=>{w(!0)},children:"Trust project"})]})]})})},Be=({children:t,className:r,outerClassName:i,title:o,titleLeading:c,titleAccessory:w,description:v,headerEnd:x})=>{const g=o!=null||v!=null||x!=null,L=typeof o=="string"||typeof o=="number",p=c!=null||w!=null;return e.jsx(Sn,{outerClassName:J("h-full",i),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",r),children:[g&&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:[o!=null?L?p?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c,e.jsx("h1",{className:J(hn,"min-w-0 truncate"),children:o}),e.jsx("span",{className:"shrink-0",children:w})]}):e.jsx("h1",{className:hn,children:o}):o:null,v!=null?typeof v=="string"||typeof v=="number"?e.jsx("p",{className:mo,children:v}):v:null]}),e.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-3",children:x})]}),t]})})},Pn=({value:t,onChange:r,readOnly:i=!1,initialMode:o="preview",placeholder:c="Enter the prompt template text... Use markdown to format your snippet. It will expand as #name in the composer.",settingsItem:w,minHeight:v=220,hideExpandsNote:x=!1})=>{const[g,L]=s.useState(()=>i?"preview":o),p=t.trim().length>0;s.useEffect(()=>{i&&g==="write"&&L("preview")},[i,g,p]);const j=g==="write"&&!i;return e.jsxs("div",{"data-settings-item":w,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(h,{variant:"chip",size:"xs","aria-pressed":g==="preview",onClick:()=>L("preview"),children:[e.jsx(f,{name:"eye",className:"size-3.5","aria-hidden":!0}),"Preview"]}),e.jsxs(h,{variant:"chip",size:"xs","aria-pressed":g==="write",disabled:i,onClick:()=>L("write"),className:J(i&&"opacity-50"),children:[e.jsx(f,{name:"edit",className:"size-3.5","aria-hidden":!0}),"Write"]})]}),i?e.jsx("span",{className:"hidden typography-micro text-muted-foreground @xl:inline",children:"Read-only"}):null]}),j?e.jsx("div",{className:"p-0",children:e.jsx(Fr,{value:t,onChange:u=>r(u.target.value),placeholder:c,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:v},"aria-label":"Snippet content"})}):e.jsx("div",{className:"min-h-[220px] px-4 py-4 @xl:px-6",style:{minHeight:v},children:p?e.jsx(Nr,{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(f,{name:"file-text",className:"size-6 text-muted-foreground/50","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:i?"No content":"Nothing to preview"}),i?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Start writing in the Write tab to see a live preview."})]})}),i?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:[x?e.jsx("span",{}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(f,{name:"information",className:"size-3.5 shrink-0 opacity-60","aria-hidden":!0}),"Expands as ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["#","`{name}`"]})," in the composer"]}),e.jsxs("span",{className:"tabular-nums",children:[t.length," chars"]})]})]})},Po=()=>{const{isMobile:t}=Mt(),[r,i]=s.useState(null),[o,c]=s.useState({}),[w,v]=s.useState(null),[x,g]=s.useState(!1),L=s.useCallback(async()=>{const j=await et.listResources({runtimeKey:Zt()});i(j.agents),c(Object.fromEntries(j.agents.map(u=>[u.id,u.content??""]))),g(!1)},[]);s.useEffect(()=>{L().catch(()=>g(!0))},[L]);const p=async j=>{v(j.id);try{const u=await et.updateResource({resourceId:j.id,content:o[j.id]??""},{runtimeKey:Zt()});i(u.agents),c(Object.fromEntries(u.agents.map(P=>[P.id,P.content??""]))),R.success("Behavior saved successfully")}catch{R.error("Failed to save behavior")}finally{v(null)}};return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{L().catch(()=>g(!0))}}),e.jsxs(Be,{title:t?void 0:"Behavior",description:t?void 0:"Guide how the agent responds.",children:[x?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,(r??[]).map((j,u)=>{const P=o[j.id]??"",A=j.location==="global"?"Global AGENTS.md":`Project ${j.name}`,F=j.editable===!0,H=P!==(j.content??"");return e.jsxs(te,{title:A,divider:u>0,settingsItem:j.location==="global"?"behavior.global-agents":"behavior.project-agents",contentClassName:"space-y-3",info:F?"Markdown supported. Changes apply to new sessions.":"Read-only — this file is managed by a package or template.",children:[e.jsx(Pn,{value:P,onChange:_=>c(W=>({...W,[j.id]:_})),readOnly:!F,placeholder:F?"Describe how the agent should behave. Use markdown for structure.":void 0,settingsItem:j.location==="global"?"behavior.global-agents":"behavior.project-agents",hideExpandsNote:!0,minHeight:260}),F?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:H?"Unsaved changes":"No changes"}),e.jsx(h,{size:"xs",onClick:()=>{p(j)},disabled:w!==null||!H,children:w===j.id?"Saving...":"Save Changes"})]}):null]},j.id)})]})]})},To=({skill:t,onSelect:r,showLocationPill:i=!0})=>{const o=t.location==="project"?"Project":t.location==="global"?"Global":t.location,c=t.description?.trim()||"No description";return e.jsxs("button",{type:"button",onClick:()=>r(t.name),"aria-label":`${t.name} skill, ${o}`,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:[i?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:o})}):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:c})]})]})},Io=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((r,i)=>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"})]})]},i))}),Eo=()=>{const{isMobile:t}=Mt(),r=Ns(k=>k.selectedSkillName),i=Ns(k=>k.setSelectedSkill),o=Ns(k=>k.skills),c=Ns(k=>k.isLoading),w=Ns(k=>k.loadSkills),[v,x]=s.useState(""),[g,L]=s.useState("all"),[p,j]=s.useState(!1),u=s.useMemo(()=>o.find(k=>k.name===r)??null,[o,r]),P=Ns(k=>k.updateSkillContent),[A,F]=s.useState(!1),[H,_]=s.useState(""),[W,Q]=s.useState(!1);s.useEffect(()=>{u&&_(u.content??""),F(!1)},[u?.id,u?.content]);const M=s.useCallback(async()=>{if(!p){j(!0);try{const{invalidateSkillsLoadCache:k}=await pa(async()=>{const{invalidateSkillsLoadCache:l}=await import("./SessionSwitcherDropdown-DROjbyIu.js").then(y=>y.e_);return{invalidateSkillsLoadCache:l}},__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 w()}finally{j(!1)}}},[w,p]);s.useEffect(()=>{w()},[w]);const C=s.useMemo(()=>[...o].sort((k,l)=>{if(k.location!==l.location){if(k.location==="project")return-1;if(l.location==="project")return 1;if(k.location==="global")return-1;if(l.location==="global")return 1}return k.name.localeCompare(l.name,void 0,{sensitivity:"base"})}),[o]),b=s.useMemo(()=>{let k=C;g!=="all"&&(k=k.filter(y=>y.location===g));const l=v.trim().toLowerCase();return l?k.filter(y=>{const U=y.name.toLowerCase(),K=(y.description??"").toLowerCase();return U.includes(l)||K.includes(l)}):k},[C,g,v]),S=s.useMemo(()=>{let k=0,l=0;for(const y of o)y.location==="project"?k+=1:y.location==="global"&&(l+=1);return{all:o.length,project:k,global:l}},[o]);if(u){const k=u.location==="project"?"Project":u.location==="global"?"Global":u.location,l=typeof u.content=="string"&&u.content.trim().length>0,y=u.editable===!0,U=H!==(u.content??""),K=async()=>{if(!y||W)return;Q(!0);const ae=await P(u.name,H);Q(!1),ae?(R.success("Skill saved"),F(!1)):R.error("Failed to save skill")},G=()=>{_(u.content??""),F(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{w()}}),e.jsxs(Be,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>i(null),"aria-label":"Back to skills",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(f,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:u.name})]}),description:u.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:u.description}):void 0,headerEnd:y&&!A?e.jsxs(h,{variant:"outline",size:"xs",onClick:()=>F(!0),children:[e.jsx(f,{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}),y?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(f,{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"]})]}),y?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:A?"Markdown supported. Preview your changes before saving.":"Rendered from the SKILL.md markdown file discovered by Pi.",headerAction:y&&A?e.jsx("span",{className:"typography-micro text-muted-foreground",children:U?"Unsaved changes":"No changes"}):void 0,children:[A?e.jsxs(e.Fragment,{children:[e.jsx(Pn,{value:H,onChange:_,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(h,{variant:"ghost",size:"xs",onClick:G,disabled:W,children:"Cancel"}),e.jsx(h,{size:"xs",onClick:()=>{K()},disabled:W||!U,children:W?"Saving...":"Save Changes"})]})]}):l?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(Nr,{content:u.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(f,{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."}),y?e.jsxs(h,{variant:"outline",size:"xs",onClick:()=>F(!0),className:"mt-2",children:[e.jsx(f,{name:"edit",className:"size-3.5"}),"Add content"]}):null]}),y&&!A&&l?e.jsx("div",{className:"flex justify-end pt-3",children:e.jsxs(h,{variant:"outline",size:"xs",onClick:()=>F(!0),children:[e.jsx(f,{name:"edit",className:"size-3.5"}),"Edit"]})}):null]})]})]})}return c&&o.length===0?e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{w()}}),e.jsx(Be,{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(h,{variant:"ghost",size:"icon",onClick:()=>{M()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(f,{name:"refresh",className:J("size-4",p&&"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(Io,{count:6})})})})]}):b.length===0&&v.trim()===""&&o.length===0?e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{w()}}),e.jsx(Be,{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(f,{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(ne,{value:v,onChange:k=>x(k.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),v?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(f,{name:"close",className:"size-4"})}):null]}),e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{M()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(f,{name:"refresh",className:J("size-4",p&&"animate-spin")})})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(f,{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.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{w()}}),e.jsx(Be,{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(f,{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(ne,{value:v,onChange:k=>x(k.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),v?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(f,{name:"close",className:"size-4"})}):null]}),e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{M()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(f,{name:"refresh",className:J("size-4",p&&"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(h,{variant:"chip",size:"xs","aria-pressed":g==="all",onClick:()=>L("all"),children:["All ",S.all]}),e.jsxs(h,{variant:"chip",size:"xs","aria-pressed":g==="project",onClick:()=>L("project"),children:["Project ",S.project]}),e.jsxs(h,{variant:"chip",size:"xs","aria-pressed":g==="global",onClick:()=>L("global"),children:["Global ",S.global]})]}),b.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:v.trim()?`No skills match “${v}”.`:`No ${g} skills.`}),e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>{x(""),L("all")},children:"Clear filters"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:b.map(k=>e.jsx(To,{skill:k,onSelect:i,showLocationPill:g==="all"},k.id))})]})})]})},Ao=({header:t,footer:r,children:i,className:o,variant:c="sidebar"})=>{const w=s.useRef(null),[v,x]=s.useState(!1),[g,L]=s.useState(!1),p=c==="background"?"bg-background":"bg-sidebar",j=p==="bg-background"?"var(--surface-background)":"var(--surface-muted)",u=s.useCallback(()=>{const P=w.current;if(!P){x(!1),L(!1);return}if(!(P.scrollHeight>P.clientHeight+1)){x(!1),L(!1);return}x(P.scrollTop>1),L(P.scrollTop+P.clientHeight<P.scrollHeight-1)},[]);return s.useEffect(()=>{u()},[i,u]),s.useEffect(()=>{const P=w.current;if(!P)return;const A=()=>u();return P.addEventListener("scroll",A,{passive:!0}),()=>P.removeEventListener("scroll",A)},[u]),e.jsxs("div",{className:J("flex h-full flex-col",p,o),children:[t,e.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[e.jsx(Sn,{ref:w,outerClassName:"flex-1 min-h-0",className:"space-y-1.5 px-3 py-3 overflow-x-hidden",children:i}),v&&e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-4",style:{background:`linear-gradient(to bottom, ${j} 0%, transparent 100%)`}}),g&&e.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-6",style:{background:`linear-gradient(to top, ${j} 0%, transparent 100%)`}})]}),r]})},Mo=({title:t,metadata:r,selected:i=!1,onSelect:o,icon:c,actions:w,className:v})=>{const x=w&&w.length>0;return e.jsx("div",{className:J("group relative flex items-center rounded-lg px-2 py-2 transition-colors duration-150",i?"bg-interactive-selection":"hover:bg-interactive-hover",v),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:o,className:"flex min-w-0 flex-1 flex-col gap-0.5 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c,e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t})]}),r&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:r})]}),x&&e.jsxs(Sr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(h,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(f,{name:"more-2",className:"h-3.5 w-3.5"})})}),e.jsx(Pr,{align:"end",className:"w-fit min-w-20",children:w.map(g=>{const L=g.icon;return e.jsxs(Tr,{onClick:p=>{p.stopPropagation(),g.onClick()},className:J(g.destructive&&"text-destructive focus:text-destructive"),children:[L&&e.jsx(f,{name:L,className:"h-4 w-4 mr-px"}),g.label]},g.label)})})]})]})})},Lo=({onItemSelect:t})=>{const{isMobile:r}=Mt(),i=La(v=>v.projects),o=T(v=>v.settingsProjectsSelectedId),c=T(v=>v.setSettingsProjectsSelectedId),w=s.useCallback(()=>{li.requestDirectoryDialog()},[]);return s.useEffect(()=>{if(i.length===0){o!==null&&c(null);return}o&&i.some(v=>v.id===o)||c(i[0].id)},[i,o,c]),e.jsx(Ao,{variant:"background",header:e.jsxs("div",{className:J("border-b px-3","pt-4 pb-3"),children:[!r&&e.jsx("h2",{className:`${Ur} mb-3`,children:"Projects"}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:`Total ${i.length}`}),e.jsx(h,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,"aria-label":"Add project",children:e.jsx(f,{name:"add",className:"size-4"})})]})]}),children:i.map(v=>{const x=v.id===o,g=e.jsx(f,{name:"folder",className:J("h-4 w-4",x?"text-foreground":"text-muted-foreground/70")});return e.jsx(Mo,{title:v.label||v.path,metadata:v.label?v.path:void 0,icon:g,selected:x,onSelect:()=>{c(v.id),t?.()}},v.id)})})},Ro=()=>{const{isMobile:t}=Mt(),r=La(g=>g.projects),i=La(g=>g.updateProjectMeta),o=T(g=>g.settingsProjectsSelectedId),c=T(g=>g.setSettingsProjectsSelectedId),w=s.useMemo(()=>o?r.find(g=>g.id===o)??null:null,[r,o]);s.useEffect(()=>{if(r.length===0){c(null);return}o&&r.some(g=>g.id===o)||c(r[0].id)},[r,o,c]);const v=s.useCallback(async g=>{w&&i(w.id,{label:g.label,defaultModel:g.defaultModel??null})},[w,i]);if(!w)return e.jsx(Be,{title:t?void 0:"Projects",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No projects available."})});const x=w.label??"Project Settings";return e.jsx(Be,{title:x,description:w.path,outerClassName:"bg-background",children:e.jsx(po,{project:w,onIdentitySave:v})})};function Zn(t,r,i){return Math.min(i,Math.max(r,t))}function Do(t){if(!Number.isFinite(t))return 0;const r=String(t);if(r.includes("e-")){const[,o]=r.split("e-");return Number(o)||0}const i=r.split(".");return i.length===2?i[1].length:0}function er(t,r){const i=Do(r);return i<=0?t:Number(t.toFixed(i))}const At=he.forwardRef(({value:t,onValueChange:r,min:i=-1/0,max:o=1/0,step:c=1,className:w,containerClassName:v,onBlur:x,disabled:g,fallbackValue:L,onClear:p,emptyLabel:j="—",...u},P)=>{const[A,F]=he.useState(()=>t==null?"":String(t)),{isMobile:H}=Mt(),_=he.useRef(!1),W=he.useRef(null),Q=he.useCallback(()=>{if(typeof document>"u"||typeof window>"u")return;W.current?.();const ge=de=>{de.preventDefault(),de.stopPropagation(),de.stopImmediatePropagation?.(),W.current?.()},le=window.setTimeout(()=>{W.current?.()},700),re=()=>{window.clearTimeout(le),document.removeEventListener("click",ge,!0),W.current=null};W.current=re,document.addEventListener("click",ge,!0)},[]);he.useEffect(()=>()=>{W.current?.()},[]),he.useEffect(()=>{F(t==null?"":String(t))},[t]);const M=he.useMemo(()=>t!==void 0?t:L!==void 0?L:Number.isFinite(i)?i:0,[L,i,t]),C=he.useRef(M);he.useEffect(()=>{C.current=M},[M]);const b=he.useCallback(ge=>{const le=Zn(ge,i,o),re=er(le,c);C.current=re,r(re)},[o,i,r,c]),S=he.useCallback(ge=>{const le=ge.target.value;if(F(le),le.trim()===""){p?.();return}const re=Number(le);Number.isFinite(re)&&b(re)},[b,p]),k=he.useCallback(ge=>{if(A.trim()===""){p||F(t==null?"":String(t)),x?.(ge);return}const le=Number(A);if(!Number.isFinite(le))F(t==null?"":String(t));else{const re=Zn(le,i,o),de=er(re,c);de!==t?b(le):C.current=de,F(String(de))}x?.(ge)},[b,A,o,i,x,p,c,t]),l=!!(g||M>=o),y=!!(g||M<=i),U=()=>{y||b(C.current-c)},K=()=>{l||b(C.current+c)},G=ge=>le=>{le.preventDefault(),le.stopPropagation(),_.current=!0,Q(),ge()},ae=ge=>le=>{if(_.current){_.current=!1,le.preventDefault(),le.stopPropagation();return}ge()};return H?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",v),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:y,onTouchStart:G(U),onClick:ae(U),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",!y&&"active:bg-interactive-hover"),children:e.jsx(f,{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]",w),"aria-live":"polite",children:t==null?j:A}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:l,onTouchStart:G(K),onClick:ae(K),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",!l&&"active:bg-interactive-hover"),children:e.jsx(f,{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",v),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:y,onClick:()=>b(C.current-c),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(f,{name:"subtract",className:"block h-3.5 w-3.5"})}),e.jsx("input",{...u,ref:P,type:"text",inputMode:u.inputMode??"numeric",value:A,onChange:S,onBlur:k,disabled:g,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",w)}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:l,onClick:()=>b(C.current+c),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(f,{name:"add",className:"block h-3.5 w-3.5"})})]})});At.displayName="NumberInput";const xn=he.forwardRef(({className:t,...r},i)=>e.jsx(jo,{className:J("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[checked]:bg-primary data-[unchecked]:bg-[var(--interactive-border)]",t),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:i,children:e.jsx(ko,{className:J("pointer-events-none block rounded-full bg-background shadow-none ring-0 transition-transform data-[checked]:translate-x-4 data-[unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}})}));xn.displayName="Switch";const bn=()=>Math.floor(2e4+Math.random()*3e4),_o=t=>{const r=(t instanceof Error?t.message:String(t)).toLowerCase();return r.includes("address already in use")||r.includes("eaddrinuse")||r.includes("port already in use")},Oo=()=>{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"},tr=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}},sr=t=>{switch(t){case"config_resolved":return"Resolving configuration";case"auth_check":return"Checking authentication";case"master_connecting":return"Establishing SSH connection";case"remote_probe":return"Checking remote machine";case"installing":return"Installing PiChamber";case"updating":return"Updating PiChamber";case"server_detecting":return"Detecting server";case"server_starting":return"Starting server";case"forwarding":return"Forwarding ports";case"ready":return"Ready";case"degraded":return"Reconnecting";case"error":return"Error";default:return"Idle"}},zo=new Set(["config_resolved","auth_check","master_connecting","remote_probe","installing","updating","server_detecting","server_starting","forwarding"]),Yr=t=>!!(t&&zo.has(t)),ar=t=>t==="ready"?"bg-[var(--status-success)] animate-pulse":t==="error"?"bg-[var(--status-error)] animate-pulse":t==="degraded"||Yr(t)?"bg-[var(--status-warning)] animate-pulse":"bg-muted-foreground/40",Fo=t=>t.type==="dynamic"?`${t.localHost||"127.0.0.1"}:${t.localPort||0}`:t.type==="remote"?`${t.remoteHost||"127.0.0.1"}:${t.remotePort||0} -> ${t.localHost||"127.0.0.1"}:${t.localPort||0}`:`${t.localHost||"127.0.0.1"}:${t.localPort||0} -> ${t.remoteHost||"127.0.0.1"}:${t.remotePort||0}`,Uo=()=>({id:`forward-${Date.now()}-${Math.random().toString(16).slice(2)}`,enabled:!0,type:"local",localHost:"127.0.0.1",localPort:bn(),remoteHost:"127.0.0.1",remotePort:80}),Bo=t=>t.trim().replace(/\*/g,"host").replace(/\?/g,"x")||"user@host",as=({label:t,hint:r})=>e.jsxs("span",{className:`inline-flex items-center gap-1 ${st}`,children:[e.jsx("span",{children:t}),e.jsx(Xt,{contentClassName:"max-w-xs",children:r})]}),Ho=t=>{switch(t){case"remote":return"Open a port on the remote machine that connects back to your computer.";case"dynamic":return"Open a local SOCKS proxy through the SSH connection.";default:return"Open a local port that connects to something on the remote machine."}},nr=(t,r)=>{const i=(t||"").trim();return`${!i||i==="127.0.0.1"||i==="::1"?"localhost":i}:${r||0}`},Vo=t=>{const r=(t||"").trim();return!r||r==="0.0.0.0"||r==="::"?"127.0.0.1":r},$o=t=>{const r=t.match(/^\[(\d{10,})\]\s*(?:\[([A-Z]+)\]\s*)?(.*)$/);if(!r)return t;const i=Number(r[1]),o=Number.isFinite(i)?new Date(i).toISOString():r[1],c=(r[2]||"INFO").toUpperCase(),w=r[3]||"";return`[${o}] [${c}] ${w}`},vn=(t="",r="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:t,value:r}),Ko=t=>t.trim().toLowerCase()==="authorization",rn=t=>{const r={};for(const i of t){const o=i.name.trim(),c=i.value.trim();o&&c&&!Ko(o)&&(r[o]=c)}return Object.keys(r).length>0?r:void 0},Wo=t=>Object.entries(t||{}).map(([r,i])=>vn(r,i)),Jr=()=>{if(typeof window>"u")return null;const r=qs()||window.location.href;try{const i=Number(new URL(r).port||window.location.port);return Number.isFinite(i)&&i>0?i:null}catch{const i=Number(window.location.port);return Number.isFinite(i)&&i>0?i:null}},rr=t=>{try{const r=new URL(t).hostname.toLowerCase();return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},Go=async()=>{const t=Hs(qs())||window.location.origin;if(!at()||!fa())return t;let r;try{r=await ht("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}})}catch{return t}if(!r.ok||(await r.json().catch(()=>null))?.desktopLanAccessActive!==!0)return t;const o=await Or(),c=Jr();return!o||!c?t:`http://${o}:${c}`},on=t=>{const r=t.trim();if(r)try{window.location.assign(r)}catch{window.location.href=r}},qo=t=>{const r=t.sshCommand.trim(),i=t.nickname?.trim(),o=t.portForwards.map(c=>({...c,localHost:c.localHost?.trim()||"127.0.0.1",localPort:typeof c.localPort=="number"?Math.max(1,Math.min(65535,Math.round(c.localPort))):void 0,remoteHost:c.remoteHost?.trim(),remotePort:typeof c.remotePort=="number"?Math.max(1,Math.min(65535,Math.round(c.remotePort))):void 0}));return{...t,sshCommand:r,...i?{nickname:i}:{nickname:void 0},connectionTimeoutSec:Math.max(5,Math.min(240,Math.round(t.connectionTimeoutSec||60))),localForward:{...t.localForward,bindHost:t.localForward.bindHost==="localhost"||t.localForward.bindHost==="0.0.0.0"?t.localForward.bindHost:"127.0.0.1",preferredLocalPort:typeof t.localForward.preferredLocalPort=="number"?Math.max(1,Math.min(65535,Math.round(t.localForward.preferredLocalPort))):void 0},remoteOpenchamber:{...t.remoteOpenchamber,preferredPort:typeof t.remoteOpenchamber.preferredPort=="number"?Math.max(1,Math.min(65535,Math.round(t.remoteOpenchamber.preferredPort))):void 0},portForwards:o}},Qo=()=>{const{isMobile:t}=Mt(),r=T(a=>a.timeFormatPreference),{clientAuth:i}=Ir(),o=at(),c=lt(a=>a.instances),w=lt(a=>a.statusesById),v=lt(a=>a.importCandidates),x=lt(a=>a.isLoading),g=lt(a=>a.isImportsLoading),L=lt(a=>a.isSaving),p=lt(a=>a.error),j=lt(a=>a.load),u=lt(a=>a.loadImports),P=lt(a=>a.refreshStatuses),A=lt(a=>a.upsertInstance),F=lt(a=>a.createFromCommand),H=lt(a=>a.removeInstance),_=lt(a=>a.connect),W=lt(a=>a.disconnect),Q=lt(a=>a.retry),M=T(a=>a.settingsRemoteInstancesSelectedId),C=T(a=>a.setSettingsRemoteInstancesSelectedId),b=s.useMemo(()=>M&&c.find(a=>a.id===M)||null,[c,M]),[S,k]=s.useState(null),[l,y]=s.useState(!1),[U,K]=s.useState(!1),[G,ae]=s.useState(null),[ge,le]=s.useState([]),[re,de]=s.useState(null),[we,ke]=s.useState(""),[D,q]=s.useState(!1),[ce,ie]=s.useState({}),[I,fe]=s.useState(!1),[Se,V]=s.useState(!1),[ye,Te]=s.useState(()=>Date.now()),[ue,Fe]=s.useState([]),[Ve,kt]=s.useState({}),[Re,rt]=s.useState("local"),[Lt,gt]=s.useState(!1),[N,me]=s.useState(!1),[z,ee]=s.useState(""),[xe,Ue]=s.useState(""),[He,O]=s.useState(""),[X,pe]=s.useState([]),[Ee,Ce]=s.useState(""),[$e,De]=s.useState(null),[Oe,nt]=s.useState(!1),[dt,ut]=s.useState(!1),[mt,pt]=s.useState(null),[ze,zt]=s.useState(""),[Vt,hs]=s.useState(""),[gs,fs]=s.useState(""),[xs,es]=s.useState([]),[it,Ps]=s.useState([]),[ts,bs]=s.useState([]),[Ts,Is]=s.useState(!1),[os,ls]=s.useState(""),[$t,ft]=s.useState(null),[Kt,d]=s.useState(null),[B,se]=s.useState(null),[Z,je]=s.useState(null),[Ne,oe]=s.useState(!1),[_e,Wt]=s.useState(!1),[Gt,Es]=s.useState("configure"),[As,vs]=s.useState(!1),[qt,ys]=s.useState("relay"),[Qt,Yt]=s.useState(!0),[ot,Qs]=s.useState(null),Ua=s.useMemo(()=>it.filter(a=>!!a.revokedAt).length,[it]),[Ba,Ms]=s.useState(!1),[Ls,xa]=s.useState("ssh user@example.com"),[Ys,ba]=s.useState("");s.useEffect(()=>{j(),u()},[j,u]);const va=s.useCallback(async()=>{gt(!0),De(null);try{const a=await zn();Fe(a.hosts||[]),rt(a.defaultHostId||"local")}catch(a){De(a instanceof Error?a.message:String(a))}finally{gt(!1)}},[]);s.useEffect(()=>{va()},[va]);const Nt=s.useCallback(async(a,m=Re)=>{me(!0),De(null);try{await Fn({hosts:a,defaultHostId:m,initialHostChoiceCompleted:!0}),Fe(a),rt(m)}catch($){De($ instanceof Error?$.message:String($))}finally{me(!1)}},[Re]),Ha=s.useCallback(async()=>{const a=Un(xe);if(!a){De("Invalid URL (must be http/https)");return}const m=a.persistedUrl,Y={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:z.trim()||oa(m),url:m,apiUrl:m,...He.trim()?{clientToken:He.trim()}:{},...rn(X)?{requestHeaders:rn(X)}:{}};await Nt([Y,...ue],Re),ee(""),Ue(""),O(""),pe([]),nt(!1),a.redeemUrl&&on(a.redeemUrl)},[Re,X,ue,z,He,xe,Nt]),Rs=s.useCallback(async()=>{const a=Li(Ee);if(!a){De("Invalid PiChamber connection link.");return}const m=await Ri().catch(()=>""),$=JSON.stringify({pairingId:a.pairingId,secret:a.secret,clientLabel:a.label||"PiChamber Desktop",clientKind:"desktop",deviceName:"PiChamber Desktop",devicePlatform:Oo(),...m?{dedupeKey:`desktop:${m}`}:{}}),Y={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:$},Le=async Ae=>{if(!Ae.ok)return null;const Ct=await Ae.json().catch(()=>null);return(typeof Ct?.clientToken=="string"?Ct.clientToken.trim():"")||null},Ht=[...a.candidates].sort((Ae,Ct)=>(Ae.type==="relay"?1:0)-(Ct.type==="relay"?1:0));let Ge=null;for(const Ae of Ht){if(Ae.type==="relay"){const ia=Di({relayUrl:Ae.relayUrl,serverId:Ae.serverId,hostEncPubJwk:Ae.hostEncPubJwk,...Ae.grant?{grant:Ae.grant}:{}});try{const Ca=await ia.fetch("/api/client-auth/pairing/redeem",Y),An=await Le(Ca);if(An){Ge={kind:"relay",relay:{relayUrl:Ae.relayUrl,serverId:Ae.serverId,hostEncPubJwk:Ae.hostEncPubJwk},token:An};break}}catch{}finally{ia.close()}continue}const Ct=Hs(Ae.url);if(Ct)try{const ia=await fetch(`${Ct}/api/client-auth/pairing/redeem`,Y),Ca=await Le(ia);if(Ca){Ge={kind:"direct",url:Ct,token:Ca};break}}catch{}}if(!Ge){De("Invalid URL (must be http/https)");return}const ds=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,ws=a.candidates.find(Ae=>Ae.type==="relay"),ss=Ge.kind==="relay"?Ge.relay:ws?{relayUrl:ws.relayUrl,serverId:ws.serverId,hostEncPubJwk:ws.hostEncPubJwk}:void 0,Xa=a.candidates.filter(Ae=>Ae.type!=="relay").map(Ae=>Hs(Ae.url)).find(Ae=>!!Ae),na=Ge.kind==="direct"?Ge.url:Xa,{token:Za}=Ge,Pe=na||(ss?_i(ss.serverId):null);if(!Pe){De("Invalid URL (must be http/https)");return}const Ke={url:Pe,apiUrl:na||void 0,clientToken:Za,...ss?{relay:ss}:{}},ra=ue.find(Ae=>ss?Ae.relay?.serverId===ss.serverId:!Ae.relay&&Hs(Ae.apiUrl||Ae.url)===Pe);if(ra){const Ae=ue.map(Ct=>Ct.id===ra.id?{...Ct,label:a.label||Ct.label,...Ke}:Ct);await Nt(Ae,Re)}else await Nt([{id:ds(),label:a.label||oa(Pe),...Ke},...ue],Re);Ce(""),De(null),ut(!1)},[Ee,Re,ue,Nt]),Ds=s.useCallback(async a=>{const m=ue.filter(Y=>Y.id!==a);await Nt(m,Re===a?"local":Re),mt===a&&pt(null)},[Re,mt,ue,Nt]),Js=s.useCallback(a=>{pt(a.id),zt(a.label),hs(a.apiUrl||a.url),fs(a.clientToken||""),es(Wo(a.requestHeaders)),De(null)},[]),Xs=s.useCallback(async()=>{if(!mt)return;const a=Un(Vt);if(!a){De("Invalid URL (must be http/https)");return}const m=a.persistedUrl,$=ue.map(Y=>Y.id===mt?{...Y,label:ze.trim()||oa(m),url:m,apiUrl:m,clientToken:gs.trim()||void 0,requestHeaders:rn(xs)}:Y);await Nt($,Re),pt(null),a.redeemUrl&&on(a.redeemUrl)},[Re,xs,ze,gs,Vt,mt,ue,Nt]),_s=s.useCallback(async()=>{const a=Ls.trim();if(!a){R.error("SSH command is required");return}const m=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{await F(m,a,Ys.trim()||"New SSH connection"),C(m),Ms(!1),xa("ssh user@example.com"),ba(""),R.success("Instance created")}catch($){R.error("Failed to create SSH connection",{description:$ instanceof Error?$.message:String($)})}},[F,C,Ls,Ys]),E=s.useCallback(async a=>{await Nt(ue,a)},[ue,Nt]);s.useEffect(()=>{if(!o||ue.length===0)return;let a=!1;return Promise.all(ue.map(async m=>{const $=()=>Hi(m.relay,{clientToken:m.clientToken||null,requestHeaders:m.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(m.relay&&!m.apiUrl)return[m.id,await $()];const Y=Hs(Oi(m));if(!Y)return[m.id,m.relay?await $():{status:"unreachable",latencyMs:0}];const Le=await zi(Y,{clientToken:m.clientToken||null,requestHeaders:m.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Le.status==="unreachable"&&m.relay){const Ht=await $();if(Ht.status==="ok")return[m.id,Ht]}return[m.id,Le]})).then(m=>{a||kt(Object.fromEntries(m))}),()=>{a=!0}},[ue,o]);const xt=s.useCallback(async a=>{if(i){a?.silent||Is(!0),a?.silent||ft(null);try{const[m,$]=await Promise.all([i.listClients(),i.listPendingPairings().catch(()=>null)]);Ps(m),$&&bs($)}catch(m){a?.silent||ft(m instanceof Error?m.message:String(m))}finally{a?.silent||Is(!1)}}},[i]),Os=s.useRef(!1);s.useEffect(()=>{if(!(!_e||Gt!=="result"||!B)){if(ts.some(a=>a.id===B)){Os.current=!0;return}Os.current&&(se(null),Wt(!1),it.some(a=>a.pairingId===B)&&R.success("Device connected."))}},[_e,Gt,B,ts,it]);const Va=s.useCallback(async a=>{if(i)try{await i.cancelPairing(a),bs(m=>m.filter($=>$.id!==a)),await xt({silent:!0})}catch(m){ft(m instanceof Error?m.message:String(m))}},[i,xt]);s.useEffect(()=>{if(!i)return;xt();const a=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||xt({silent:!0})},5e3);return()=>window.clearInterval(a)},[i,xt]);const Zs=s.useCallback(async()=>{if(i?.getPairingTransports)try{const Y=await i.getPairingTransports();return{localUrl:Y.local,lanUrl:Y.lan,relayAvailable:Y.relayAvailable}}catch{}const a=Jr(),m=a?`http://127.0.0.1:${a}`:rr(window.location.origin)?window.location.origin:null;let $=null;try{const Y=Hs(await Go());$=Y&&!rr(Y)?Y:null}catch{}return{localUrl:m,lanUrl:$,relayAvailable:!0}},[i]),ya=s.useCallback(async()=>{ft(null),d(null),je(null),oe(!1),se(null),Es("configure"),Yt(!0),Wt(!0);const a=await Zs();Qs(a),ys(a.relayAvailable?"relay":a.lanUrl?"lan":"local")},[Zs]),wa=s.useCallback(async()=>{if(!(!i?.createPairingSession||!ot)){ft(null),vs(!0);try{const a=os.trim()||void 0;let m,$,Y=!0;qt==="local"?(m=ot.localUrl??void 0,$=!1):qt==="lan"?(m=ot.lanUrl??void 0,$=Qt):Qt&&ot.lanUrl?(m=ot.lanUrl,$=!0):(Y=!1,$=!0);const{pairing:Le,server:Ht}=await i.createPairingSession({label:a,allowedClientKinds:["mobile","desktop"],serverUrl:m,includeRelay:$,includeDirect:Y}),Ge=Fi({pairingId:Le.id,secret:Le.secret,label:Ht.label,fingerprint:Le.fingerprint??void 0,expiresAt:Le.expiresAt,candidates:Ht.candidates}),ds=Ui(Ge);d(ds),je(await Vr.toDataURL(ds,{width:1024,margin:2,errorCorrectionLevel:"L"})),oe(!1),Os.current=!1,se(Le.id),Es("result"),await xt({silent:!0})}catch(a){ft(a instanceof Error?a.message:String(a))}finally{vs(!1)}}},[i,ot,qt,Qt,os,xt]),ja=s.useCallback(()=>{Kt&&en(Kt).then(a=>{a.ok&&(oe(!0),window.setTimeout(()=>oe(!1),2e3))})},[Kt]),$a=s.useCallback(async a=>{if(!i)return;const m=a.clientKind==="desktop-local";ft(null);try{if(await i.revokeClient(a.id),m&&at()){const $=await zn();await Fn({hosts:$.hosts,defaultHostId:$.defaultHostId,initialHostChoiceCompleted:$.initialHostChoiceCompleted,localClientToken:null}),Ps(Y=>Y.map(Le=>Le.id===a.id?{...Le,revokedAt:new Date().toISOString()}:Le)),Bi({apiBaseUrl:qs(),clientToken:null,runtimeKey:"local"});return}await xt()}catch($){ft($ instanceof Error?$.message:String($))}},[i,xt]),ka=s.useCallback(async()=>{if(i){ft(null);try{await i.purgeRevokedClients(),await xt()}catch(a){ft(a instanceof Error?a.message:String(a))}}},[i,xt]);s.useEffect(()=>{k(b)},[b]),s.useEffect(()=>{if(!M)return;const a=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||P()},2e3);return()=>{window.clearInterval(a)}},[P,M]),s.useEffect(()=>{let a=null,m=Date.now();const $=()=>{const Le=Date.now();Le-m>=1e3&&(Te(Le),m=Le),a=requestAnimationFrame($)};(typeof document>"u"||document.visibilityState==="visible")&&(a=requestAnimationFrame($));const Y=()=>{document.visibilityState==="visible"&&a===null?a=requestAnimationFrame($):document.visibilityState!=="visible"&&a!==null&&(cancelAnimationFrame(a),a=null)};return document.addEventListener("visibilitychange",Y),()=>{document.removeEventListener("visibilitychange",Y),a!==null&&cancelAnimationFrame(a)}},[]);const bt=M?w[M]:null,Ft=bt?.phase,Ut=Ft==="ready",vt=Ft==="degraded",St=Yr(Ft),Jt=Ut||(St||vt),ta=bt?Math.max(0,ye-bt.updatedAtMs):0,zs=vt&&ta>12e3,Ka=s.useMemo(()=>!S||!b?!1:JSON.stringify(S)!==JSON.stringify(b),[S,b]),Ze=s.useCallback(a=>{k(m=>m&&a(m))},[]),Wa=s.useCallback(async()=>{if(!S)return;const a=qo(S);if(!a.sshCommand.trim()){R.error("SSH command is required");return}if(!(a.localForward.bindHost==="0.0.0.0"&&!window.confirm("Binding to 0.0.0.0 exposes forwarded ports to your local network. Continue?"))){if(a.auth.sshPassword?.enabled&&a.auth.sshPassword.value?.trim()&&a.auth.sshPassword.store!=="settings"){const m=window.confirm("Store SSH password in plaintext on disk?");a.auth.sshPassword.store=m?"settings":"never",m||(a.auth.sshPassword.value=void 0)}if(a.auth.pichamberPassword?.enabled&&a.auth.pichamberPassword.value?.trim()&&a.auth.pichamberPassword.store!=="settings"){const m=window.confirm("Store UI password in plaintext on disk?");a.auth.pichamberPassword.store=m?"settings":"never",m||(a.auth.pichamberPassword.value=void 0)}try{await A(a),R.success("Instance saved")}catch(m){R.error("Failed to save instance",{description:m instanceof Error?m.message:String(m)})}}},[S,A]),Fs=s.useCallback(async(a,m)=>{const $=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{return await F($,`ssh ${m}`,a),C($),R.success("Instance created"),!0}catch(Y){return R.error("Failed to create SSH connection",{description:Y instanceof Error?Y.message:String(Y)}),!1}},[F,C]),Us=s.useCallback(()=>{D||(de(null),ke(""))},[D]),sa=s.useCallback((a,m)=>{if(m){de(a),ke(Bo(a));return}Fs(a,a)},[Fs]),Na=s.useCallback(async()=>{const a=re,m=we.trim();if(a){if(!m){R.error("Destination is required");return}q(!0);try{await Fs(a,m)&&(de(null),ke(""))}finally{q(!1)}}},[Fs,we,re]),cs=s.useCallback(async()=>{if(b)try{await _(b.id);return}catch(a){if(!_o(a)||!window.confirm("Local port is already in use. Pick a random free local port and retry?"))throw a;const $={...b,localForward:{...b.localForward,preferredLocalPort:bn()}};await A($),await _($.id),R.success("Retried with a random local port")}},[_,b,A]),Rt=s.useCallback(async a=>(await ci(a,600)).map($=>$o($)),[]),Bs=s.useCallback(async()=>{if(S){y(!0),K(!0),ae(null);try{const a=await Rt(S.id);le(a)}catch(a){le([]),ae(a instanceof Error?a.message:String(a))}finally{K(!1)}}},[S,Rt]);s.useEffect(()=>{if(!l||!S)return;let a=!1;const m=async()=>{try{const Y=await Rt(S.id);a||(le(Y),ae(null))}catch(Y){a||ae(Y instanceof Error?Y.message:String(Y))}};m();const $=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||m()},1e3);return()=>{a=!0,window.clearInterval($)}},[S,l,Rt]);const Bt=s.useMemo(()=>ge.join(`
3
+ `),[ge]),Ga=s.useCallback(()=>{if(!Bt.trim()){R.error("No logs to copy");return}en(Bt).then(a=>{a.ok&&R.success("Logs copied")})},[Bt]),qa=s.useCallback(async()=>{if(S)try{await di(S.id),le([]),R.success("Logs cleared")}catch(a){R.error("Failed to clear logs",{description:a instanceof Error?a.message:String(a)})}},[S]),Qa=s.useCallback(async()=>{if(!bt?.localUrl){R.error("Instance URL is unavailable");return}const a=bt.localUrl.trim();if(!a){R.error("Instance URL is unavailable");return}on(a)},[bt?.localUrl]),Ya=s.useCallback(()=>{if(!S)return;fe(!0),(Jt?W(S.id):cs()).catch(m=>{const $=Jt?Ut?"Failed to disconnect instance":"Failed to cancel connection":"Failed to connect instance";R.error($,{description:m instanceof Error?m.message:String(m)})}).finally(()=>{fe(!1)})},[Jt,cs,W,S,Ut]),Ja=s.useCallback(()=>{if(!S||St)return;V(!0),(vt?W(S.id).then(()=>cs()):Q(S.id)).catch(m=>{R.error("Failed to retry connection",{description:m instanceof Error?m.message:String(m)})}).finally(()=>{V(!1)})},[cs,W,S,St,vt,Q]),aa=St?"Connecting...":vt?zs?"Reconnect now":"Reconnecting...":"Retry",Sa=!I&&!Se&&(Ft==="error"||Ft==="idle"||!Ft||vt&&zs)&&!St,n=Ut?"Disconnect":Jt?"Cancel":"Connect";if(!S)return e.jsxs(Be,{title:t?void 0:"Remote Instances",children:[i?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(h,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{ya()},children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add a device"]})}),e.jsxs("div",{className:"space-y-2.5",children:[Ua>0?e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{ka()},children:"Clear revoked"})}):null,Ts&&it.length===0&&ts.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading tokens..."}):it.length===0&&ts.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No devices connected yet."}):e.jsxs(e.Fragment,{children:[ts.map(a=>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:a.label||"Device name — e.g. My iPhone"}),a.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(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Va(a.id)},children:"Cancel"})]},`pending-${a.id}`)),it.map(a=>{const m=a.clientKind==="desktop-local",$=a.lastUsedAt?Date.parse(a.lastUsedAt):Number.NaN,Y=!a.revokedAt&&(m||Number.isFinite($)&&Date.now()-$<9e4),Le=a.revokedAt?"Revoked":Y?a.lastTransport==="relay"&&!m?"Connected · Relay":"Connected · Local network":Number.isFinite($)?`Last used ${ui($,r,{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",a.revokedAt?"bg-muted-foreground/20":Y?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:a.label}),tr(a.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:tr(a.devicePlatform)}):null,m?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",Y&&!a.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:Le})]})}),e.jsx(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{$a(a)},disabled:!!a.revokedAt,children:"Revoke"})]},a.id)})]})]}),$t?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:$t}):null]}):null,o?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(h,{type:"button",size:"xs",className:"!font-normal",onClick:()=>ut(!0),disabled:N,children:"Import Link"}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>nt(!0),disabled:N,children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add Server"]})]}),children:[e.jsx("div",{className:"space-y-2.5",children:Lt?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading instances..."}):ue.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No other servers added yet."}):ue.map(a=>{const m=Ve[a.id],$=m?m.status==="ok"?"Connected":m.status==="auth"?"Auth required":m.status==="update-recommended"?"Update recommended":m.status==="incompatible"?"Incompatible":m.status==="wrong-service"?"Wrong service":"Unreachable":"Checking",Y=m?.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",m?Y?"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:oa(a.label)}),Re===a.id?e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"Default"}):null,e.jsxs("span",{className:J("typography-micro shrink-0",Y?"text-[var(--status-success)]":"text-muted-foreground"),children:[$,Y&&typeof m?.latencyMs=="number"?` · ${Math.max(0,Math.round(m.latencyMs))}ms ping`:""]})]}),e.jsx("p",{className:J("typography-micro text-muted-foreground truncate",a.apiUrl&&"font-mono"),children:a.relay&&!a.apiUrl?"via PiChamber Relay":oa(a.apiUrl||a.url)})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{E(a.id)},disabled:N||Re===a.id,"aria-label":"Set as default",children:Re===a.id?e.jsx(f,{name:"star-fill",className:"h-3.5 w-3.5"}):e.jsx(f,{name:"star",className:"h-3.5 w-3.5"})}),a.relay&&!a.apiUrl?null:e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>Js(a),disabled:N,children:[e.jsx(f,{name:"pencil",className:"h-3.5 w-3.5"}),"Edit"]}),e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Ds(a.id)},disabled:N,children:[e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"}),"Delete"]})]})]})},a.id)})}),$e?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:$e}):null]}):null,o?e.jsx(wt,{open:Oe,onOpenChange:nt,children:e.jsxs(jt,{className:"sm:max-w-lg",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Add Server"}),e.jsx(It,{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:a=>{a.preventDefault(),Ha()},children:[e.jsx(ne,{className:"h-8",value:z,onChange:a=>ee(a.target.value),placeholder:"Label (optional)",disabled:N}),e.jsx(ne,{className:"h-8",value:xe,onChange:a=>Ue(a.target.value),placeholder:"https://host:port",disabled:N,autoFocus:!0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"h-8",value:He,onChange:a=>O(a.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:N}),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(_a,{children:"Additional headers"}),e.jsx(Xt,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),X.map(a=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ne,{className:"h-8 font-mono text-xs",value:a.name,onChange:m=>pe($=>$.map(Y=>Y.id===a.id?{...Y,name:m.target.value}:Y)),placeholder:"Header name",disabled:N}),e.jsx(ne,{className:"h-8 font-mono text-xs",value:a.value,onChange:m=>pe($=>$.map(Y=>Y.id===a.id?{...Y,value:m.target.value}:Y)),placeholder:"Header value",type:"password",disabled:N}),e.jsx("button",{type:"button",onClick:()=>pe(m=>m.filter($=>$.id!==a.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:N,children:e.jsx(f,{name:"close",className:"h-4 w-4"})})]},a.id)),e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>pe(a=>[...a,vn()]),disabled:N,children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>nt(!1),disabled:N,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:N||!xe.trim(),children:"Add Server"})]})]})]})}):null,o?e.jsx(wt,{open:!!mt,onOpenChange:a=>{a||pt(null)},children:e.jsxs(jt,{className:"sm:max-w-lg",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Edit"}),e.jsx(It,{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:a=>{a.preventDefault(),Xs()},children:[e.jsx(ne,{className:"h-8",value:ze,onChange:a=>zt(a.target.value),placeholder:"Label (optional)",disabled:N}),e.jsx(ne,{className:"h-8",value:Vt,onChange:a=>hs(a.target.value),placeholder:"https://host:port",disabled:N,autoFocus:!0}),e.jsx(ne,{className:"h-8",value:gs,onChange:a=>fs(a.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:N}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(_a,{children:"Additional headers"}),e.jsx(Xt,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),xs.map(a=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ne,{className:"h-8 font-mono text-xs",value:a.name,onChange:m=>es($=>$.map(Y=>Y.id===a.id?{...Y,name:m.target.value}:Y)),placeholder:"Header name",disabled:N}),e.jsx(ne,{className:"h-8 font-mono text-xs",value:a.value,onChange:m=>es($=>$.map(Y=>Y.id===a.id?{...Y,value:m.target.value}:Y)),placeholder:"Header value",type:"password",disabled:N}),e.jsx("button",{type:"button",onClick:()=>es(m=>m.filter($=>$.id!==a.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:N,children:e.jsx(f,{name:"close",className:"h-4 w-4"})})]},a.id)),e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>es(a=>[...a,vn()]),disabled:N,children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>pt(null),disabled:N,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:N,children:"Save Changes"})]})]})]})}):null,o?e.jsx(wt,{open:dt,onOpenChange:ut,children:e.jsxs(jt,{className:"sm:max-w-lg",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Import Link"}),e.jsx(It,{children:"Paste a connection link from another PiChamber server."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:a=>{a.preventDefault(),Rs()},children:[e.jsx(ne,{className:"h-8",value:Ee,onChange:a=>Ce(a.target.value),placeholder:"pichamber://connect?...",disabled:N,autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>ut(!1),disabled:N,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:N||!Ee.trim(),children:"Import Link"})]})]})]})}):null,e.jsx(wt,{open:_e,onOpenChange:Wt,children:e.jsxs(jt,{className:Gt==="result"?"sm:max-w-lg":"sm:max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:Gt==="result"?"Scan to connect":"Add a device"}),e.jsx(It,{children:Gt==="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."})]}),Gt==="configure"?e.jsxs("form",{className:"space-y-4",onSubmit:a=>{a.preventDefault(),wa()},children:[e.jsx(ne,{className:"h-8",value:os,onChange:a=>ls(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:!!ot?.relayAvailable},{key:"lan",label:"Home network only",hint:"Connects directly over your Wi-Fi. Does not work away from this network.",available:!!ot?.lanUrl},{key:"local",label:"This computer only",hint:"For apps running on this same machine.",available:!!ot?.localUrl}].map(a=>{const m=qt===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&&ys(a.key)},role:"presentation",children:[e.jsx(ho,{checked:m,disabled:!a.available,onChange:()=>ys(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",m?"text-foreground":"text-foreground/70"),children:a.label}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:a.hint})]})]},a.key)})}),qt==="lan"?e.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[e.jsx(Mn,{checked:Qt,onChange:Yt,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,qt==="relay"&&ot?.lanUrl?e.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[e.jsx(Mn,{checked:Qt,onChange:Yt,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]}),$t?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:$t}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Wt(!1),disabled:As,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:As||!ot,children:"Create QR code"})]})]}):e.jsxs("div",{className:"space-y-3",children:[Z?e.jsx("div",{className:"flex justify-center",children:e.jsx("img",{src:Z,alt:"PiChamber connection QR code",className:"w-full max-w-[420px] rounded-md bg-white p-4"})}):null,Kt?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:Kt}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:ja,children:[e.jsx(f,{name:Ne?"check":"file-copy",className:J("h-3.5 w-3.5",Ne&&"text-[var(--status-success)]")}),Ne?"Copied":"Copy all"]})]}):null,e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",size:"xs",className:"!font-normal",onClick:()=>Wt(!1),children:"Done"})})]})]})}),o?e.jsx(te,{headerAction:e.jsxs(h,{type:"button",size:"xs",className:"!font-normal",onClick:()=>Ms(!0),children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add SSH connection"]}),contentClassName:"space-y-2.5",children:x?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading SSH hosts..."}):c.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No SSH hosts found."}):c.map(a=>{const m=w[a.id],$=a.nickname?.trim()||a.sshParsed?.destination||a.id,Y=m?.phase,Le=Y==="ready";return 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 rounded-full ${ar(Y)}`}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:$})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground truncate",children:[sr(Y),m?.localUrl?` · ${m.localUrl}`:""]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{(Le?W(a.id):_(a.id)).catch(Ge=>R.error(Le?"Failed to disconnect instance":"Failed to connect instance",{description:Ge instanceof Error?Ge.message:String(Ge)}))},children:[Le?e.jsx(f,{name:"stop",className:"h-3.5 w-3.5"}):e.jsx(f,{name:"plug-2",className:"h-3.5 w-3.5"}),Le?"Disconnect":"Connect"]}),e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>C(a.id),children:[e.jsx(f,{name:"pencil",className:"h-3.5 w-3.5"}),"Edit"]}),e.jsxs(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{window.confirm("Remove this remote instance?")&&H(a.id).catch(Ge=>R.error("Failed to remove instance",{description:Ge instanceof Error?Ge.message:String(Ge)}))},children:[e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"}),"Delete"]})]})]},a.id)})}):null,o?e.jsx(wt,{open:Ba,onOpenChange:Ms,children:e.jsxs(jt,{className:"sm:max-w-lg",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Add SSH connection"}),e.jsx(It,{children:"Choose the SSH command and a display name for this connection."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:a=>{a.preventDefault(),_s()},children:[e.jsx(ne,{className:"h-8",value:Ys,onChange:a=>ba(a.target.value),placeholder:"Work laptop",disabled:L}),e.jsx(ne,{className:"h-8",value:Ls,onChange:a=>xa(a.target.value),placeholder:"ssh user@host",disabled:L,autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ms(!1),disabled:L,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:L||!Ls.trim(),children:"Create"})]})]})]})}):null,o?e.jsx(te,{title:"Saved SSH hosts",children:g?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading SSH hosts..."}):v.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No SSH hosts found."}):e.jsx("div",{children:v.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--surface-subtle)] py-3 last:border-b-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"typography-ui-label font-medium text-foreground truncate",children:[a.host,a.pattern?" (pattern)":""]}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:a.sshCommand})]}),e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{sa(a.host,a.pattern)},children:"Import"})]},`${a.source}:${a.host}`))})}):null,e.jsx(wt,{open:!!re,onOpenChange:a=>{a||Us()},children:e.jsxs(jt,{className:"sm:max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Choose an SSH destination"}),e.jsx(It,{children:re?`${re} requires a concrete destination.`:"Enter destination."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:a=>{a.preventDefault(),Na()},children:[e.jsx(ne,{value:we,onChange:a=>ke(a.target.value),placeholder:"user@host",autoFocus:!0}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Us,disabled:D,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:D,children:"Create"})]})]})]})})]});const be=S.remoteOpenchamber.mode==="managed",Dt=S.nickname?.trim()||S.sshParsed?.destination||S.id;return e.jsx(wt,{open:!!S,onOpenChange:a=>{a||C(null)},children:e.jsxs(jt,{className:"sm:max-w-4xl max-h-[90vh] overflow-auto",children:[e.jsxs("div",{className:"mb-6 px-1",children:[e.jsx("h1",{className:`${hn} truncate`,children:Dt}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${ar(Ft)}`}),e.jsx("span",{children:sr(Ft)}),bt?.localUrl?e.jsx("span",{className:"font-mono text-foreground/80",children:bt.localUrl}):null,zs?e.jsx("span",{children:"Reconnection looks stuck. You can retry now."}):null]})]}),e.jsxs(te,{title:"Actions",info:"Connect, reconnect, view logs, or remove this connection.",divider:!1,contentClassName:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(h,{type:"button",variant:Jt?"outline":"default",size:"xs",className:"!font-normal",onClick:Ya,disabled:I||Se,children:[Jt?e.jsx(f,{name:"stop",className:"h-3.5 w-3.5"}):e.jsx(f,{name:"plug-2",className:"h-3.5 w-3.5"}),n]}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Ja,disabled:!Sa,children:[e.jsx(f,{name:"refresh",className:`h-3.5 w-3.5 ${St||vt&&!zs?"animate-spin":""}`}),aa]}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Bs()},children:[e.jsx(f,{name:"terminal-window",className:"h-3.5 w-3.5"}),"SSH Logs"]}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal text-[var(--status-error)] border-[var(--status-error)]/30 hover:text-[var(--status-error)]",onClick:()=>{window.confirm("Remove this remote instance?")&&H(S.id).then(()=>{C(null),R.success("Instance removed")}).catch(m=>{R.error("Failed to remove instance",{description:m instanceof Error?m.message:String(m)})})},children:[e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"}),"Remove"]})]}),bt?.localUrl?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx("span",{children:"Current local URL:"}),e.jsx("span",{className:"font-mono text-foreground/90",children:bt.localUrl})]}):null]}),e.jsxs(te,{title:"Instance",info:"Choose the SSH command and a display name for this connection.",contentClassName:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:"SSH command"}),e.jsx(ne,{className:"h-7 md:max-w-xl",value:S.sshCommand,onChange:a=>Ze(m=>({...m,sshCommand:a.target.value})),placeholder:"ssh user@host"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:"Nickname"}),e.jsx(ne,{className:"h-7 md:max-w-sm",value:S.nickname||"",onChange:a=>Ze(m=>({...m,nickname:a.target.value})),placeholder:"Work laptop"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:"Connection timeout (seconds)"}),e.jsx(At,{containerClassName:"w-fit",min:5,max:240,step:1,className:"w-16 tabular-nums",value:S.connectionTimeoutSec,onValueChange:a=>{Ze(m=>({...m,connectionTimeoutSec:Number.isFinite(a)?a:m.connectionTimeoutSec}))}})]})]}),e.jsxs(te,{title:"PiChamber on the remote machine",info:"Choose how PiChamber should run after SSH connects.",contentClassName:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Mode",hint:"Choose whether PiChamber should start the server for you, or connect to one that is already running."})}),e.jsxs(Qe,{value:S.remoteOpenchamber.mode,onValueChange:a=>Ze(m=>({...m,remoteOpenchamber:{...m.remoteOpenchamber,mode:a==="external"?"external":"managed"}})),children:[e.jsx(Ye,{size:tt,className:"w-fit min-w-[140px]",children:e.jsx(Je,{placeholder:"Select mode"})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"managed",children:"Start it for me"}),e.jsx(Me,{value:"external",children:"Already running"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Preferred remote port",hint:"Port to use on the remote machine. Leave empty to choose one automatically."})}),e.jsx(At,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:S.remoteOpenchamber.preferredPort,onValueChange:a=>{Ze(m=>({...m,remoteOpenchamber:{...m.remoteOpenchamber,preferredPort:Number.isFinite(a)&&a>0?a:void 0}}))},onClear:()=>{Ze(a=>({...a,remoteOpenchamber:{...a.remoteOpenchamber,preferredPort:void 0}}))},emptyLabel:"Auto"})]}),be?e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Install method",hint:"How PiChamber should be placed on the remote machine when this app starts it for you."})}),e.jsxs(Qe,{value:S.remoteOpenchamber.installMethod,onValueChange:a=>Ze(m=>({...m,remoteOpenchamber:{...m.remoteOpenchamber,installMethod:a==="npm"||a==="download_release"||a==="upload_bundle"?a:"bun"}})),children:[e.jsx(Ye,{size:tt,className:"w-fit min-w-[140px]",children:e.jsx(Je,{placeholder:"Select install method"})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"bun",children:"bun"}),e.jsx(Me,{value:"npm",children:"npm"}),e.jsx(Me,{value:"download_release",children:"Download release"}),e.jsx(Me,{value:"upload_bundle",children:"Upload bundle"})]})]})]}):null,be?e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Keep server running",hint:"Keep PiChamber running on the remote machine after you disconnect."})}),e.jsx("div",{className:"flex w-full items-center gap-2 md:max-w-xs",children:e.jsx(xn,{checked:S.remoteOpenchamber.keepRunning,onCheckedChange:a=>Ze(m=>({...m,remoteOpenchamber:{...m.remoteOpenchamber,keepRunning:a}}))})})]}):null]}),e.jsxs(te,{title:"Local access",info:"Choose the local address used to open this remote PiChamber server.",contentClassName:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Bind host",hint:"Where the local connection should listen. Use 127.0.0.1 or localhost unless you need LAN access."})}),e.jsxs(Qe,{value:S.localForward.bindHost,onValueChange:a=>{a==="0.0.0.0"&&!window.confirm("Binding to 0.0.0.0 exposes forwarded ports to your local network. Continue?")||Ze(m=>({...m,localForward:{...m.localForward,bindHost:a==="localhost"||a==="0.0.0.0"?a:"127.0.0.1"}}))},children:[e.jsx(Ye,{size:tt,className:"w-fit min-w-[140px]",children:e.jsx(Je,{placeholder:"Select bind host"})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"127.0.0.1",children:"127.0.0.1"}),e.jsx(Me,{value:"localhost",children:"localhost"}),e.jsx(Me,{value:"0.0.0.0",children:"0.0.0.0"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Preferred local port",hint:"Local port to open for this connection. Leave empty to choose one automatically."})}),e.jsxs("div",{className:"flex w-full items-center gap-2 md:max-w-sm",children:[e.jsx(At,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:S.localForward.preferredLocalPort,onValueChange:a=>{Ze(m=>({...m,localForward:{...m.localForward,preferredLocalPort:Number.isFinite(a)&&a>0?a:void 0}}))},onClear:()=>{Ze(a=>({...a,localForward:{...a.localForward,preferredLocalPort:void 0}}))},emptyLabel:"Auto"}),e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal h-7 w-7 px-0",title:"Pick random port",onClick:()=>Ze(a=>({...a,localForward:{...a.localForward,preferredLocalPort:bn()}})),children:e.jsx(f,{name:"shuffle",className:"h-3.5 w-3.5"})})]})]})]}),e.jsxs(te,{title:"Authentication",info:"Optional credentials for SSH and the remote PiChamber UI.",contentClassName:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:"SSH password (optional)"}),e.jsx(ne,{className:"h-7 md:max-w-sm",type:"password",value:S.auth.sshPassword?.value||"",onChange:a=>Ze(m=>({...m,auth:{...m.auth,sshPassword:{enabled:a.target.value.trim().length>0,value:a.target.value,store:m.auth.sshPassword?.store||"never"}}})),placeholder:"Enter SSH password"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:"UI password (optional)"}),e.jsx(ne,{className:"h-7 md:max-w-sm",type:"password",value:S.auth.pichamberPassword?.value||"",onChange:a=>Ze(m=>({...m,auth:{...m.auth,pichamberPassword:{enabled:a.target.value.trim().length>0,value:a.target.value,store:m.auth.pichamberPassword?.store||"never"}}})),placeholder:"Enter UI password"})]})]}),e.jsxs(te,{title:"Port Forwards",info:"Optional extra ports to make available through this SSH connection.",contentClassName:"space-y-2",children:[S.portForwards.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground/80",children:"No extra port forwards configured."}):null,S.portForwards.map((a,m)=>{const $=Pe=>{Ze(Ke=>({...Ke,portForwards:Ke.portForwards.map((ra,Ae)=>Ae===m?Pe(ra):ra)}))},Y=a.type==="remote"?"Local target":"Local listen",Le=a.type==="remote"?"Local host and port on your machine that receives traffic from remote -R listener.":"Local host and port where this forward listens on your machine.",Ht=a.type==="remote"?"Remote listen":"Remote target",Ge=a.type==="remote"?"Remote host and port where SSH creates the -R listener.":"Remote host and port that receives traffic from local -L listener.",ds=nr(a.localHost||"localhost",a.localPort),ws=nr(a.remoteHost||"localhost",a.remotePort),ss=a.type==="local"&&typeof a.localPort=="number"&&a.localPort>0,Xa=ss?`http://${Vo(a.localHost)}:${a.localPort}`:"",na=!!ce[a.id],Za=a.type==="local"?"Local (-L)":a.type==="remote"?"Remote (-R)":"Dynamic (-D)";return e.jsxs($r,{open:na,onOpenChange:Pe=>{ie(Ke=>({...Ke,[a.id]:Pe}))},className:`${m>0?"border-t border-[var(--surface-subtle)]":""} py-2`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"min-w-0 flex items-center gap-2",children:e.jsxs(Kr,{className:"flex items-center gap-2 group",children:[e.jsx(f,{name:"arrow-down-s",className:`h-4 w-4 text-muted-foreground transition-transform ${na?"rotate-180":""}`}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Fo(a)}),e.jsx("span",{className:"typography-micro text-muted-foreground/70 shrink-0",children:Za})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xn,{checked:a.enabled,onCheckedChange:Pe=>$(Ke=>({...Ke,enabled:Pe})),"aria-label":"Enable forward"}),e.jsx(h,{type:"button",variant:"ghost",size:"xs",className:"!font-normal h-6 w-6 px-0 text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>Ze(Pe=>({...Pe,portForwards:Pe.portForwards.filter(Ke=>Ke.id!==a.id)})),children:e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})]}),e.jsx(Wr,{className:"pt-2",children:e.jsxs("div",{className:"space-y-0 pb-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:"Forward type",hint:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{children:"Choose what kind of port access this SSH connection should provide."}),e.jsx("p",{children:Ho(a.type)})]})})}),e.jsxs(Qe,{value:a.type,onValueChange:Pe=>$(Ke=>({...Ke,type:Pe==="dynamic"||Pe==="remote"?Pe:"local"})),children:[e.jsx(Ye,{size:tt,className:"w-fit min-w-[140px]",children:e.jsx(Je,{placeholder:"Type"})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"local",children:"Local (-L)"}),e.jsx(Me,{value:"remote",children:"Remote (-R)"}),e.jsx(Me,{value:"dynamic",children:"Dynamic (-D)"})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:Y,hint:Le})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ne,{className:"h-7 w-32",value:a.localHost||"127.0.0.1",onChange:Pe=>$(Ke=>({...Ke,localHost:Pe.target.value})),placeholder:"127.0.0.1"}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsx(At,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:a.localPort,onValueChange:Pe=>{$(Ke=>({...Ke,localPort:Number.isFinite(Pe)&&Pe>0?Pe:void 0}))},onClear:()=>{$(Pe=>({...Pe,localPort:void 0}))},emptyLabel:"Auto"})]})]}),a.type!=="dynamic"?e.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[e.jsx("div",{className:"w-56 shrink-0",children:e.jsx(as,{label:Ht,hint:Ge})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ne,{className:"h-7 w-32",value:a.remoteHost||"",onChange:Pe=>$(Ke=>({...Ke,remoteHost:Pe.target.value})),placeholder:"127.0.0.1"}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsx(At,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:a.remotePort,onValueChange:Pe=>{$(Ke=>({...Ke,remotePort:Number.isFinite(Pe)&&Pe>0?Pe:void 0}))},onClear:()=>{$(Pe=>({...Pe,remotePort:void 0}))},emptyLabel:"Auto"})]})]}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2 rounded-md bg-[var(--surface-subtle)] p-2",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 typography-micro text-muted-foreground/80",children:a.type==="dynamic"?e.jsxs(e.Fragment,{children:[e.jsx(f,{name:"computer",className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono text-foreground",children:ds}),e.jsx("span",{children:"(local SOCKS5)"})]}):a.type==="remote"?e.jsxs(e.Fragment,{children:[e.jsx(f,{name:"server",className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono text-foreground",children:ws}),e.jsx("span",{children:"(remote)"}),e.jsx(f,{name:"arrow-right",className:"h-3.5 w-3.5"}),e.jsx(f,{name:"computer",className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono text-foreground",children:ds}),e.jsx("span",{children:"(local)"})]}):e.jsxs(e.Fragment,{children:[e.jsx(f,{name:"computer",className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono text-foreground",children:ds}),e.jsx("span",{children:"(local)"}),e.jsx(f,{name:"arrow-right",className:"h-3.5 w-3.5"}),e.jsx(f,{name:"server",className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-mono text-foreground",children:ws}),e.jsx("span",{children:"(remote)"})]})}),ss?e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Nn(Xa).then(Pe=>{Pe||R.error("Failed to open local address")})},children:[e.jsx(f,{name:"external-link",className:"h-3.5 w-3.5"}),"Open local"]}):null]})]})})]},a.id)}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal mt-1",onClick:()=>{const a=Uo();Ze(m=>({...m,portForwards:[...m.portForwards,a]})),ie(m=>({...m,[a.id]:!0}))},children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Add forward"]})]}),e.jsx("div",{className:"mt-8 border-t border-[var(--interactive-border)] pt-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(h,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{Wa()},disabled:!Ka||L,children:"Save Changes"}),bt?.localUrl?e.jsxs(e.Fragment,{children:[e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{en(bt.localUrl||"").then(a=>{a.ok&&R.success("Local URL copied")})},children:[e.jsx(f,{name:"file-copy",className:"h-3.5 w-3.5"}),"Copy local URL"]}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Qa()},children:[e.jsx(f,{name:"external-link",className:"h-3.5 w-3.5"}),"Open"]})]}):null,p?e.jsx("div",{className:"ml-auto typography-meta text-[var(--status-error)]",children:p}):null]})}),e.jsx(wt,{open:l,onOpenChange:y,children:e.jsxs(jt,{className:"sm:max-w-2xl",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"SSH Logs"}),e.jsx(It,{children:S?.nickname?.trim()||S?.sshParsed?.destination||S?.id||"Selected instance"})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Ga,disabled:U||!Bt.trim(),children:[e.jsx(f,{name:"file-copy",className:"h-3.5 w-3.5"}),"Copy all"]}),e.jsxs(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{qa()},disabled:U,children:[e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"}),"Clear"]})]}),U?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Loading logs..."}):G?e.jsx("div",{className:"typography-meta text-[var(--status-error)]",children:G}):e.jsx("pre",{className:"max-h-[55vh] overflow-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3 typography-micro text-foreground whitespace-pre-wrap break-words",children:ge.length>0?ge.join(`
4
+ `):"No SSH logs yet."})]})}),e.jsx(wt,{open:!!re,onOpenChange:a=>{a||Us()},children:e.jsxs(jt,{className:"sm:max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Choose an SSH destination"}),e.jsx(It,{children:re?`${re} requires a concrete destination.`:"Enter destination."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:a=>{a.preventDefault(),Na()},children:[e.jsx(ne,{value:we,onChange:a=>ke(a.target.value),placeholder:"user@host",autoFocus:!0}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Us,disabled:D,children:"Cancel"}),e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:D,children:"Create"})]})]})]})})]})})},Yo="@ai-sdk/openai-compatible",Jo=/^[a-z0-9][a-z0-9-_]*$/,Xo=/^https?:\/\//,Zo=/^\{env:([^}]+)\}$/;let el=0;const za=()=>`row-${el++}`,Tn=()=>({row:za(),id:"",name:""}),In=()=>({row:za(),key:"",value:""}),tl=()=>({providerID:"",name:"",baseURL:"",apiKey:"",models:[Tn()],headers:[In()]});function sl(t){const r=t.trim();if(!r)return{};const o=r.match(Zo)?.[1]?.trim();return o?{env:o}:{key:r}}function al(t){const r=t.options&&typeof t.options=="object"?t.options:{},i=typeof r.baseURL=="string"?r.baseURL:"",o=r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)?r.headers:{},c=Object.entries(o).filter(g=>typeof g[0]=="string"&&typeof g[1]=="string").map(([g,L])=>({row:za(),key:g,value:L})),w=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([g,L])=>({id:g,name:L&&typeof L=="object"&&"name"in L&&typeof L.name=="string"?L.name:g})):[],v=w.length>0?w.map(g=>({row:za(),id:typeof g?.id=="string"?g.id:"",name:typeof g?.name=="string"?g.name:typeof g?.id=="string"?g.id:""})):[Tn()],x=Array.isArray(t.env)?t.env.find(g=>typeof g=="string"&&g.trim().length>0)?.trim():void 0;return{providerID:t.id,name:typeof t.name=="string"&&t.name.trim()?t.name:t.id,baseURL:i,apiKey:x?`{env:${x}}`:"",models:v,headers:c.length>0?c:[In()]}}function nl(t){const r=t.form.providerID.trim(),i=t.form.name.trim(),o=t.form.baseURL.trim(),{env:c,key:w}=sl(t.form.apiKey),v=t.disabledProviders??[],x=t.editingProviderID?.trim(),g=r?Jo.test(r)?void 0:"Use lowercase letters, numbers, hyphens, or underscores":"Provider ID is required",L=i?void 0:"Display name is required",p=o?Xo.test(o)?void 0:"Base URL must start with http:// or https://":"Base URL is required",u=!!(c||w||x&&t.allowExistingAuth&&x===r)?void 0:"API key or {env:VAR_NAME} is required",P=v.includes(r),F=g||!!(x&&x===r)?void 0:t.existingProviderIDs.has(r)&&!P?"A provider with this ID is already connected":void 0,H=new Set,_=t.form.models.map(y=>{const U=y.id.trim(),K=U?H.has(U)?"Duplicate":void H.add(U):"Required",G=y.name.trim()?void 0:"Required";return{id:K,name:G}}),W=_.every(y=>!y.id&&!y.name),Q=Object.fromEntries(t.form.models.map(y=>[y.id.trim(),{name:y.name.trim()}])),M=new Set,C=t.form.headers.map(y=>{const U=y.key.trim(),K=y.value.trim();return!U&&!K?{}:{key:U?M.has(U.toLowerCase())?"Duplicate":void M.add(U.toLowerCase()):"Required",value:K?void 0:"Required"}}),b=C.every(y=>!y.key&&!y.value),S=Object.fromEntries(t.form.headers.map(y=>({key:y.key.trim(),value:y.value.trim()})).filter(y=>y.key&&y.value).map(y=>[y.key,y.value])),k={providerID:g??F,name:L,baseURL:p,apiKey:u};return!g&&!F&&!L&&!p&&!u&&W&&b?{err:k,models:_,headers:C,result:{providerID:r,name:i,apiKey:w,config:{npm:Yo,name:i,...c?{env:[c]}:{},options:{baseURL:o,...Object.keys(S).length>0?{headers:S}:{}},models:Q}}}:{err:k,models:_,headers:C}}const rl=({existingProviderIDs:t,disabledProviders:r=[],busy:i=!1,mode:o="create",initialValues:c,allowExistingAuth:w=!1,authFailureHint:v=null,onSubmit:x,onCancel:g,onDisconnect:L})=>{const p=o==="edit",[j,u]=s.useState(()=>c??tl()),[P,A]=s.useState({}),[F,H]=s.useState([]),[_,W]=s.useState([]),Q=s.useRef(null);s.useEffect(()=>{c&&(p&&Q.current===c.providerID||(Q.current=p?c.providerID:null,u(c),A({}),H([]),W([])))},[c,p]);const M=(k,l)=>{u(y=>({...y,[k]:l})),A(y=>({...y,[k]:void 0}))},C=(k,l,y)=>{u(U=>({...U,models:U.models.map((K,G)=>G===k?{...K,[l]:y}:K)})),H(U=>{const K=[...U];return K[k]={...K[k]??{},[l]:void 0},K})},b=(k,l,y)=>{u(U=>({...U,headers:U.headers.map((K,G)=>G===k?{...K,[l]:y}:K)})),W(U=>{const K=[...U];return K[k]={...K[k]??{},[l]:void 0},K})},S=async k=>{if(k.preventDefault(),i)return;const l=nl({form:j,existingProviderIDs:t,disabledProviders:r,editingProviderID:p?j.providerID:void 0,allowExistingAuth:p&&w});A(l.err),H(l.models),W(l.headers),l.result&&await x(l.result)};return e.jsxs("form",{onSubmit:S,className:"space-y-0",children:[e.jsxs(te,{title:p?"Edit custom provider":"Custom provider",divider:!1,settingsItem:"providers.custom",contentClassName:rs,children:[e.jsx("p",{className:qn,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."}),v?e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:v}):null,e.jsxs(qe,{label:"Provider ID",info:"Lowercase letters, numbers, hyphens, and underscores. Used as the Pi provider id.",children:[e.jsx(ne,{value:j.providerID,onChange:k=>M("providerID",k.target.value),placeholder:"my-provider",className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:!p,disabled:p||i,"aria-invalid":!!P.providerID,"aria-label":"Provider ID"}),P.providerID?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.providerID}):null]}),e.jsxs(qe,{label:"Display name",info:"Shown in the provider and model pickers.",children:[e.jsx(ne,{value:j.name,onChange:k=>M("name",k.target.value),placeholder:"My Provider",className:"h-8 rounded-md px-3","aria-invalid":!!P.name,"aria-label":"Display name"}),P.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.name}):null]}),e.jsxs(qe,{label:"Base URL",info:"OpenAI-compatible API base URL. Must start with http:// or https://.",children:[e.jsx(ne,{value:j.baseURL,onChange:k=>M("baseURL",k.target.value),placeholder:"https://api.example.com/v1",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!P.baseURL,"aria-label":"Base URL"}),P.baseURL?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.baseURL}):null]}),e.jsxs(qe,{label:"API key",info:p&&w?"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(ne,{type:"password",value:j.apiKey,onChange:k=>M("apiKey",k.target.value),placeholder:p&&w?"Leave blank to keep existing key":"sk-... or {env:VAR_NAME}",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!P.apiKey,"aria-label":"API key"}),P.apiKey?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.apiKey}):null]})]}),e.jsxs(te,{title:"Models",contentClassName:rs,children:[j.models.map((k,l)=>e.jsx("div",{className:`${Gs} 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:st,children:"Model ID"}),e.jsx(ne,{value:k.id,onChange:y=>C(l,"id",y.target.value),placeholder:"gpt-4o",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Model ID"}),F[l]?.id?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:F[l]?.id}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:st,children:"Model name"}),e.jsx(ne,{value:k.name,onChange:y=>C(l,"name",y.target.value),placeholder:"GPT-4o",className:"mt-1 h-8 rounded-md px-3","aria-label":"Model name"}),F[l]?.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:F[l]?.name}):null]})]}),e.jsx(h,{type:"button",variant:"ghost",size:"icon",className:yt,disabled:j.models.length<=1,onClick:()=>{j.models.length<=1||(u(y=>({...y,models:y.models.filter((U,K)=>K!==l)})),H(y=>y.filter((U,K)=>K!==l)))},"aria-label":"Remove model",children:e.jsx(f,{name:"delete-bin",className:"size-4"})})]})},k.row)),e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u(k=>({...k,models:[...k.models,Tn()]})),H(k=>[...k,{}])},children:"Add model"})]}),e.jsxs(te,{title:"Headers",contentClassName:rs,children:[e.jsx("p",{className:qn,children:"Optional request headers sent with every call."}),j.headers.map((k,l)=>e.jsx("div",{className:`${Gs} 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:st,children:"Header name"}),e.jsx(ne,{value:k.key,onChange:y=>b(l,"key",y.target.value),placeholder:"X-Custom-Header",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header name"}),_[l]?.key?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:_[l]?.key}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:st,children:"Header value"}),e.jsx(ne,{value:k.value,onChange:y=>b(l,"value",y.target.value),placeholder:"value",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header value"}),_[l]?.value?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:_[l]?.value}):null]})]}),e.jsx(h,{type:"button",variant:"ghost",size:"icon",className:yt,disabled:j.headers.length<=1,onClick:()=>{j.headers.length<=1||(u(y=>({...y,headers:y.headers.filter((U,K)=>K!==l)})),W(y=>y.filter((U,K)=>K!==l)))},"aria-label":"Remove header",children:e.jsx(f,{name:"delete-bin",className:"size-4"})})]})},k.row)),e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u(k=>({...k,headers:[...k.headers,In()]})),W(k=>[...k,{}])},children:"Add header"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4",children:[g?e.jsx(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:g,disabled:i,children:"Back"}):null,L?e.jsx(h,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{L()},disabled:i,children:"Disconnect"}):null,e.jsx(h,{type:"submit",size:"xs",className:"!font-normal",disabled:i,children:i?"Saving...":p?"Update provider":"Save provider"})]})]})},il=({provider:t,onSelect:r})=>{const i=t.models.length,o=i===1?"1 model":`${i} models`,{hasLogo:c}=mi(t.id);return e.jsxs("button",{type:"button",onClick:()=>r(t.id),"aria-label":`${t.label} provider, ${o}${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:[c?e.jsx(Er,{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(f,{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(f,{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(f,{name:"stack",className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"tabular-nums",children:o})]})]})},ol=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((r,i)=>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"})]},i))}),la="__pi_custom_provider__",yn=qr(t=>({selectedProviderId:null,setSelectedProviderId:r=>t(i=>i.selectedProviderId===r?i:{selectedProviderId:r})})),ll=(t,r,i)=>t.some(o=>o.providerID===r&&o.modelID===i),_t=()=>({runtimeKey:Zt()}),Pa="__pi_fallback__",cl=(t,r)=>{const i=[...t];return r&&!i.includes(r)&&i.push(r),i},dl=t=>[...t].sort((r,i)=>r.authenticated!==i.authenticated?r.authenticated?-1:1:r.label.localeCompare(i.label,void 0,{sensitivity:"base"})),Xr=s.memo(({providerId:t,model:r,storedLevel:i,isBusy:o,isHidden:c,isConnected:w,onThinkingChange:v,onToggleHidden:x})=>{const g=s.useMemo(()=>Ar(r),[r]),p=s.useMemo(()=>Mr(g),[g])||i!==void 0,j=s.useMemo(()=>cl(g,i),[g,i]),u=i??Pa;return e.jsxs("div",{className:J("flex min-w-0 items-center gap-2 py-2",c&&"opacity-60"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",children:r.label||r.id}),p?e.jsxs(Qe,{value:u,onValueChange:P=>v(t,r.id,P===Pa?null:P),disabled:o,children:[e.jsx(Ye,{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 ${r.label||r.id}`,children:e.jsx(Je,{children:P=>P===Pa?"Default":P&&Lr(P)?Da[P]:P??""})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:Pa,children:"Default"}),j.map(P=>e.jsx(Me,{value:P,children:Da[P]},P))]})]}):null,r.supportsThinking?e.jsx(f,{name:"brain-ai-3",className:"size-4 shrink-0 text-muted-foreground","aria-label":"Reasoning"}):null,typeof r.contextWindow=="number"?e.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:r.contextWindow}):null,w?e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>x(t,r.id),"aria-label":c?"Show model in pickers":"Hide model from pickers",title:c?"Show model in pickers":"Hide model from pickers",children:e.jsx(f,{name:c?"eye":"eye-off",className:"size-4"})}):null]})});Xr.displayName="ProviderModelRow";const ul=()=>{const{isMobile:t}=Mt(),r=yn(N=>N.selectedProviderId),i=yn(N=>N.setSelectedProviderId),o=T(N=>N.hiddenModels),c=T(N=>N.toggleHiddenModel),w=T(N=>N.hideAllModels),v=T(N=>N.showAllModels),x=We(N=>N.settingsDefaultThinkingByModel),g=We(N=>N.setSettingsDefaultThinkingByModel),L=We(N=>N.setSettingsDefaultThinking),[p,j]=s.useState(null),[u,P]=s.useState(""),[A,F]=s.useState(""),[H,_]=s.useState(null),[W,Q]=s.useState(!1),[M,C]=s.useState(null),[b,S]=s.useState(!1),[k,l]=s.useState(!1),[y,U]=s.useState(!1),[K,G]=s.useState(!1),[ae,ge]=s.useState(null),[le,re]=s.useState(new Set),[de,we]=s.useState(""),[ke,D]=s.useState(80),q=s.useCallback(async()=>{const{providers:N}=await et.listProviders(_t());j(N),l(!1),We.getState().loadProviders({source:"providersPage:refresh"})},[]),ce=s.useCallback(async()=>{if(!y){U(!0);try{const{providers:N}=await et.refreshProviders(_t());j(N),l(!1);const me=We.getState();me.invalidateProviderCache(),me.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:N}))}catch{l(!0)}finally{U(!1)}}},[y]),ie=s.useCallback(async()=>{if(!K){G(!0),ge(null);try{const{providers:N}=await et.refreshProviders(_t());j(N),l(!1),ge("success");const me=We.getState();me.invalidateProviderCache(),me.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:N})),R.success("Model catalog refreshed")}catch{l(!0),ge("error"),R.error("Could not refresh model catalog")}finally{G(!1)}}},[K]);s.useEffect(()=>{let N=!0;return q().catch(()=>{N&&l(!0)}),()=>{N=!1}},[q]),s.useEffect(()=>{let N=!0;const me=_t();return et.getSettings(me).then(z=>{if(!N||me.runtimeKey!==Zt())return;const ee=z.pichamber.defaultThinkingByModel??{},xe=z.pichamber.defaultThinking,Ue=We.getState().settingsDefaultThinkingByModel;(()=>{const O=Object.keys(Ue),X=Object.keys(ee);if(O.length!==X.length)return!1;for(const pe of O)if(Ue[pe]!==ee[pe])return!1;return!0})()||g(ee),xe!==We.getState().settingsDefaultThinking&&L(xe)}).catch(()=>{}),()=>{N=!1}},[L,g]),s.useEffect(()=>{if(!H||H.state!=="pending")return;let N=!0;const me=window.setInterval(()=>{et.getProviderLogin(H.providerId,H.id,_t()).then(z=>{N&&(_(z.login),z.login.state==="complete"&&q().catch(()=>l(!0)))}).catch(()=>{N&&_(z=>z&&{...z,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})})},1e3);return()=>{N=!1,window.clearInterval(me)}},[H,q]),s.useEffect(()=>{if(!H||H.state!=="complete"||!p)return;p.find(me=>me.id===H.providerId)?.authenticated===!0&&_(null)},[H,p]),s.useEffect(()=>{const N=me=>{const z=me.detail;Array.isArray(z)&&(j(z),l(!1))};return window.addEventListener("pichamber:providers-refreshed",N),()=>window.removeEventListener("pichamber:providers-refreshed",N)},[]);const I=p?.find(N=>N.id===r)??null,fe=I?.id;s.useEffect(()=>{if(!fe){C(null);return}let N=!0;return et.getProviderConfig(fe,_t()).then(me=>{N&&C(me.config)}).catch(()=>{N&&C(null)}),()=>{N=!1}},[fe]);const Se=s.useCallback(async(N,me,z)=>{const ee=Ra({providerId:N,modelId:me});if(!ee)return;const xe=_t(),Ue=We.getState().settingsDefaultThinkingByModel,He={...Ue};z===null?delete He[ee]:He[ee]=z,g(He),re(O=>new Set(O).add(ee)),Ws("saving");try{const O=await et.setPiChamberDefaults({defaultThinkingByModel:{[ee]:z}},xe);if(xe.runtimeKey!==Zt()){g(Ue);return}const X=O.pichamber.defaultThinkingByModel??{};g(X),O.pichamber.defaultThinking!==void 0&&L(O.pichamber.defaultThinking),Ws("saved")}catch{xe.runtimeKey===Zt()&&g(Ue),Ws("error")}finally{re(O=>{const X=new Set(O);return X.delete(ee),X})}},[L,g]),V=s.useCallback((N,me,z)=>{Se(N,me,z)},[Se]),ye=s.useCallback((N,me)=>{c(N,me)},[c]);s.useEffect(()=>{D(80)},[fe]);const Te=s.useMemo(()=>I?I.models.slice(0,ke):[],[I,ke]),ue=I?I.models.length>Te.length:!1,Fe=s.useMemo(()=>p?dl(p):[],[p]),Ve=s.useMemo(()=>{const N=de.trim().toLowerCase();return N?Fe.filter(me=>{const z=me.label.toLowerCase(),ee=me.id.toLowerCase();return z.includes(N)||ee.includes(N)}):Fe},[Fe,de]),kt=async N=>{S(!0);try{await et.setProviderModels({providerId:N.providerID,label:N.name,baseUrl:N.config.options.baseURL,api:"openai-completions",models:Object.entries(N.config.models).map(([me,z])=>({id:me,providerId:N.providerID,label:z.name})),...N.config.options.headers?{headers:N.config.options.headers}:{},...N.config.env?.[0]?{apiKeyReference:`{env:${N.config.env[0]}}`}:{}},_t()),N.apiKey&&_((await et.loginProvider({providerId:N.providerID,type:"api_key",apiKey:N.apiKey},_t())).login),i(N.providerID),Q(!1),await q()}catch{l(!0)}finally{S(!1)}},Re=async N=>{if(!(!I||b||N==="api_key"&&u.trim().length===0)){S(!0);try{const me=await et.loginProvider({providerId:I.id,type:N,...N==="api_key"?{apiKey:u.trim()}:{}},_t());P(""),F(""),_(me.login),me.login.state==="complete"&&await q()}catch{_({id:"",providerId:I.id,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{S(!1)}}},rt=async()=>{if(!(!H||!H.prompt||A.length===0||b)){S(!0);try{const N=await et.respondProviderLogin(H.providerId,H.id,A,_t());F(""),_(N.login),N.login.state==="complete"&&await q()}catch{_(N=>N&&{...N,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{S(!1)}}},Lt=async()=>{if(!(!I||b)){S(!0);try{await et.logoutProvider({providerId:I.id},_t()),_(null),await q()}catch{l(!0)}finally{S(!1)}}};if(k&&!p)return e.jsx(Be,{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(h,{variant:"outline",size:"sm",onClick:()=>{ce()},disabled:y,children:[e.jsx(f,{name:"refresh",className:J("size-4",y&&"animate-spin")}),y?"Retrying…":"Retry"]})]})});if(W||r===la){const N=M?.providerId===I?.id?M:null,me=N?al({id:N.providerId,name:N.label,options:{baseURL:N.baseUrl},models:N.models}):void 0;return e.jsx(Be,{title:N?"Edit custom provider":"Custom provider",children:e.jsx(rl,{existingProviderIDs:new Set(p?.map(z=>z.id)??[]),mode:N?"edit":"create",initialValues:me,allowExistingAuth:I?.authenticated===!0,busy:b,onSubmit:z=>{kt(z)},onCancel:()=>{Q(!1),i(I?.id??null)}})})}if(I){const N=H?.providerId===I.id?H:null,me=I.authenticated||N?.state==="complete";return e.jsxs(Be,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>i(null),"aria-label":"Back to providers",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(f,{name:"arrow-left-s",className:"size-4"})}),e.jsx(Er,{providerId:I.id,className:"size-5 shrink-0"}),e.jsx("span",{className:"truncate",children:I.label})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:I.id}),children:[k?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,e.jsxs(te,{title:"Authentication",divider:!1,settingsItem:"providers.auth",headerAction:me?e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>{Lt()},disabled:b,children:b?"Disconnecting...":"Disconnect"}):null,children:[me?e.jsxs("div",{className:"flex items-center gap-1.5 py-1.5 typography-ui-label",children:[e.jsx(f,{name:"check",className:"size-4 text-[var(--status-success)]"}),"Connected"]}):e.jsxs("div",{className:"space-y-4 py-1.5",children:[e.jsx(ct,{label:"API Key",children:e.jsxs("div",{className:"flex w-full max-w-[24rem] gap-2",children:[e.jsx(ne,{type:"password",value:u,onChange:z=>P(z.target.value),placeholder:"sk-...",autoComplete:"off"}),e.jsx(h,{size:"sm",onClick:()=>{Re("api_key")},disabled:b||u.trim().length===0,children:b?"Saving...":"Save Key"})]})}),e.jsx(h,{variant:"outline",size:"sm",onClick:()=>{Re("oauth")},disabled:b,children:"Reconnect"})]}),N?.state==="pending"?e.jsx(ml,{login:N,promptValue:A,onPromptValueChange:F,onSubmit:()=>{rt()},busy:b}):null,N?.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(h,{variant:"ghost",size:"icon",onClick:()=>{ie()},disabled:K||b,"aria-label":"Refresh model catalog",title:"Refresh model catalog",children:e.jsx(f,{name:"refresh",className:J("size-4",K&&"animate-spin")})}),me?e.jsxs(e.Fragment,{children:[e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>v(I.id),children:"Show all"}),e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>w(I.id,I.models.map(z=>z.id)),children:"Hide all"})]}):null,M?e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>Q(!0),children:"Update provider"}):null]}),children:[e.jsx("div",{"aria-live":"polite",className:"sr-only",children:K?"Refreshing model catalog":ae==="success"?"Model catalog refreshed":ae==="error"?"Could not refresh model catalog":""}),e.jsxs("div",{className:"divide-y divide-[var(--surface-subtle)]",children:[I.models.length===0?e.jsx("p",{className:"py-3 typography-meta text-muted-foreground",children:"No models available."}):Te.map(z=>{const ee=ll(o,I.id,z.id),xe=Ra({providerId:I.id,modelId:z.id})??`${I.id}/${z.id}`,Ue=x[xe],He=Lr(Ue)?Ue:void 0,O=le.has(xe);return e.jsx(Xr,{providerId:I.id,model:z,storedLevel:He,isBusy:O,isHidden:ee,isConnected:me,onThinkingChange:V,onToggleHidden:ye},z.id)}),ue?e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(h,{variant:"ghost",size:"xs",onClick:()=>D(z=>z+80),children:["Show ",Math.min(80,I.models.length-Te.length)," more (",Te.length," of"," ",I.models.length,")"]})}):null]})]})]})}return p===null?e.jsx(Be,{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(h,{variant:"ghost",size:"icon",onClick:()=>{ce()},disabled:y,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(f,{name:"refresh",className:J("size-4",y&&"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(ol,{count:6})})})}):Ve.length===0&&de.trim()===""&&p.length===0?e.jsx(Be,{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(f,{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(ne,{value:de,onChange:N=>we(N.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-[24rem] pl-8"})]}),e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{ce()},disabled:y,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(f,{name:"refresh",className:J("size-4",y&&"animate-spin")})}),e.jsxs(h,{variant:"outline",size:"sm",onClick:()=>i(la),children:[e.jsx(f,{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(f,{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(h,{variant:"outline",size:"sm",onClick:()=>i(la),children:"Add custom provider"})]})}):e.jsxs(Be,{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(f,{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(ne,{value:de,onChange:N=>we(N.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),de?e.jsx("button",{type:"button",onClick:()=>we(""),"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(f,{name:"close",className:"size-4"})}):null]}),e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{ce()},disabled:y,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(f,{name:"refresh",className:J("size-4",y&&"animate-spin")})}),e.jsxs(h,{variant:"outline",size:"sm",onClick:()=>i(la),children:[e.jsx(f,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:[k?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:Ve.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 “",de,"”."]}),e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>we(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[Ve.map(N=>e.jsx(il,{provider:N,onSelect:i},N.id)),e.jsxs("button",{type:"button",onClick:()=>i(la),"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(f,{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"})]})]})})]})},ml=({login:t,promptValue:r,onPromptValueChange:i,onSubmit:o,busy:c})=>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(ct,{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(Qe,{value:r,onValueChange:i,children:[e.jsx(Ye,{size:tt,className:Br,children:e.jsx(Je,{})}),e.jsx(Xe,{children:t.prompt.options.map(w=>e.jsx(Me,{value:w.id,children:w.label},w.id))})]}):e.jsx(ne,{type:t.prompt.type==="secret"?"password":"text",value:r,onChange:w=>i(w.target.value),placeholder:t.prompt.placeholder,autoComplete:"off"}),e.jsx(h,{size:"sm",onClick:o,disabled:c||r.length===0,children:"Continue"})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Waiting for authorization…"})]}),pl="git.commit.generate",wn=qr(t=>({selectedPromptId:pl,setSelectedPromptId:r=>{t(i=>i.selectedPromptId===r?i:{selectedPromptId:r})}})),hl=({onItemSelect:t})=>{const r=wn(c=>c.selectedPromptId),i=wn(c=>c.setSelectedPromptId),o=s.useMemo(()=>[{groupLabel:"Git",items:[{id:"git.commit.generate",title:"Commit Generation"},{id:"git.pr.generate",title:"PR Generation"},{id:"git.conflict.resolve",title:"Merge/Rebase Conflict Resolution"},{id:"git.integrate.cherrypick.resolve",title:"Cherry-pick Conflict Resolution"}]},{groupLabel:"GitHub",items:[{id:"github.pr.review",title:"PR Review"},{id:"github.issue.review",title:"Issue Review"},{id:"github.pr.checks.review",title:"PR Failed Checks Review"},{id:"github.pr.comments.review",title:"PR Comments Review"},{id:"github.pr.comment.single",title:"Single PR Comment Review"}]},{groupLabel:"Planning",items:[{id:"plan.todo",title:"Todo Planning"},{id:"plan.improve",title:"Improve Plan"},{id:"plan.implement",title:"Implement Plan"}]},{groupLabel:"Session",items:[{id:"session.explore",title:"Codebase Tour"},{id:"session.summary",title:"Session Summary"},{id:"session.plan",title:"Feature Planning"},{id:"session.catchup",title:"Catch Up"},{id:"session.debug",title:"Debugging"},{id:"session.weigh",title:"Weigh Options"},{id:"session.fusion",title:"Fusion"}]}],[]);return e.jsxs("div",{className:"flex h-full flex-col bg-background",children:[e.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[e.jsx("h2",{className:Ur,children:"PiChamber Utility Prompts"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Select a prompt template to edit."})]}),e.jsx(Sn,{outerClassName:"flex-1 min-h-0",className:"space-y-3 px-3 py-2 overflow-x-hidden",children:o.map(c=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro px-1 text-muted-foreground",children:c.groupLabel}),c.items.map(w=>{const v=r===w.id;return e.jsx("button",{type:"button",onClick:()=>{i(w.id),t?.()},className:J("flex w-full items-center rounded-md px-2 py-1.5 text-left transition-colors",v?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:e.jsx("span",{className:"typography-ui-label truncate font-normal",children:w.title})},w.id)})]},c.groupLabel))})]})},ir={"git.commit.generate":{title:"Commit Generation",description:"Prompts used for commit message generation: visible user message + hidden instructions.",blocks:[{id:"git.commit.generate.visible",title:"Visible Prompt"},{id:"git.commit.generate.instructions",title:"Instructions"}]},"git.pr.generate":{title:"PR Generation",description:"Prompts used for PR title/body generation: visible user message + hidden instructions.",blocks:[{id:"git.pr.generate.visible",title:"Visible Prompt"},{id:"git.pr.generate.instructions",title:"Instructions"}]},"github.pr.review":{title:"PR Review",description:"Prompts used for PR review flow: visible user message + hidden instruction payload.",blocks:[{id:"github.pr.review.visible",title:"Visible Prompt"},{id:"github.pr.review.instructions",title:"Instructions"}]},"github.issue.review":{title:"Issue Review",description:"Prompts used for issue review flow: visible user message + hidden instruction payload.",blocks:[{id:"github.issue.review.visible",title:"Visible Prompt"},{id:"github.issue.review.instructions",title:"Instructions"}]},"github.pr.checks.review":{title:"PR Failed Checks Review",description:"Prompts used for PR failed checks analysis.",blocks:[{id:"github.pr.checks.review.visible",title:"Visible Prompt"},{id:"github.pr.checks.review.instructions",title:"Instructions"}]},"github.pr.comments.review":{title:"PR Comments Review",description:"Prompts used for PR comments analysis.",blocks:[{id:"github.pr.comments.review.visible",title:"Visible Prompt"},{id:"github.pr.comments.review.instructions",title:"Instructions"}]},"github.pr.comment.single":{title:"Single PR Comment Review",description:"Prompts used for single PR comment analysis.",blocks:[{id:"github.pr.comment.single.visible",title:"Visible Prompt"},{id:"github.pr.comment.single.instructions",title:"Instructions"}]},"git.conflict.resolve":{title:"Merge/Rebase Conflict Resolution",description:"Prompts used when resolving merge/rebase conflicts with AI.",blocks:[{id:"git.conflict.resolve.visible",title:"Visible Prompt"},{id:"git.conflict.resolve.instructions",title:"Instructions"}]},"git.integrate.cherrypick.resolve":{title:"Cherry-pick Conflict Resolution",description:"Prompts used when resolving cherry-pick conflicts in integrate flow.",blocks:[{id:"git.integrate.cherrypick.resolve.visible",title:"Visible Prompt"},{id:"git.integrate.cherrypick.resolve.instructions",title:"Instructions"}]},"plan.improve":{title:"Improve Plan",description:"Hidden prompt used when sending a saved plan into an improve flow.",blocks:[{id:"plan.improve.visible",title:"Visible Prompt"},{id:"plan.improve.instructions",title:"Instructions"}]},"plan.todo":{title:"Todo Planning",description:"Hidden prompt used when sending a todo into a new planning session.",blocks:[{id:"plan.todo.visible",title:"Visible Prompt"},{id:"plan.todo.instructions",title:"Instructions"}]},"plan.implement":{title:"Implement Plan",description:"Hidden prompt used when sending a saved plan into an implement flow.",blocks:[{id:"plan.implement.visible",title:"Visible Prompt"},{id:"plan.implement.instructions",title:"Instructions"}]},"session.summary":{title:"Session Summary",description:"Prompts used by the /summary slash command: visible user message + hidden instructions. Non-destructive - does not compact session history.",blocks:[{id:"session.summary.visible",title:"Visible Prompt"},{id:"session.summary.instructions",title:"Instructions"}]},"session.plan":{title:"Feature Planning",description:"Prompts used by the /plan-feature slash command: visible user message + hidden instructions. Runs a guided dialogue that researches the code and asks clarifying questions in small batches before producing an implementation plan.",blocks:[{id:"session.plan.visible",title:"Visible Prompt"},{id:"session.plan.instructions",title:"Instructions"}]},"session.catchup":{title:"Catch Up",description:"Prompts used by the /catch-up slash command: visible user message + hidden instructions. Builds branch-aware context — the branch's commits, its PR, and uncommitted work together — to understand what you were doing, then gives a digestible summary and a product-focused next step.",blocks:[{id:"session.catchup.visible",title:"Visible Prompt"},{id:"session.catchup.instructions",title:"Instructions"}]},"session.debug":{title:"Debugging",description:"Prompts used by the /debug slash command: visible user message + hidden instructions. Runs a guided root-cause investigation — captures the symptom, forms hypotheses, checks them against the code, and confirms the cause before proposing a fix.",blocks:[{id:"session.debug.visible",title:"Visible Prompt"},{id:"session.debug.instructions",title:"Instructions"}]},"session.weigh":{title:"Weigh Options",description:"Prompts used by the /weigh slash command: visible user message + hidden instructions. Investigates the code, then lays out 2-3 distinct approaches with trade-offs and a recommendation — without writing a plan or code.",blocks:[{id:"session.weigh.visible",title:"Visible Prompt"},{id:"session.weigh.instructions",title:"Instructions"}]},"session.explore":{title:"Codebase Tour",description:"Prompts used by the /explore slash command: visible user message + hidden instructions. Investigates the repository and gives a structured orientation — the big picture, main modules, how they connect, and where to start — rather than a file-by-file dump.",blocks:[{id:"session.explore.visible",title:"Visible Prompt"},{id:"session.explore.instructions",title:"Instructions"}]},"session.fusion":{title:"Fusion",description:"Prompts used when combining multi-run outputs into one final answer: visible user message + hidden instructions before source results.",blocks:[{id:"session.fusion.visible",title:"Visible Prompt"},{id:"session.fusion.instructions",title:"Instructions"}]}},or=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),ln=t=>t.endsWith(".visible"),gl=()=>{const t=wn(M=>M.selectedPromptId),[r,i]=s.useState(!0),[o,c]=s.useState({}),[w,v]=s.useState({}),[x,g]=s.useState({}),[L,p]=s.useState({}),[j,u]=s.useState(!1);s.useEffect(()=>{let M=!0;return(async()=>{i(!0);try{const b=await fi();if(!M)return;c(b)}catch(b){console.warn("Failed to load magic prompts:",b),R.error("Failed to load PiChamber Utility Prompts")}finally{M&&i(!1)}})(),()=>{M=!1}},[]);const P=ir[t]??ir["git.commit.generate"],A=s.useCallback(M=>or(o,M)?o[M]:tn(M),[o]),F=s.useCallback(M=>w[M]??A(M),[w,A]),H=s.useCallback((M,C)=>{v(b=>b[M]===C?b:{...b,[M]:C})},[]),_=s.useCallback(async M=>{const C=F(M);if(ln(M)&&C.trim().length===0){R.error("Visible prompt cannot be empty");return}g(b=>({...b,[M]:!0}));try{const b=C===tn(M)?await Ln(M):await pi(M,C);c(b.overrides),R.success("Utility prompt saved")}catch(b){const S=b instanceof Error?b.message:String(b);R.error("Failed to save utility prompt",{description:S})}finally{g(b=>({...b,[M]:!1}))}},[F]),W=s.useCallback(async M=>{p(C=>({...C,[M]:!0}));try{const C=await Ln(M);c(C.overrides),v(b=>({...b,[M]:tn(M)})),R.success("Prompt reset to default")}catch(C){const b=C instanceof Error?C.message:String(C);R.error("Failed to reset utility prompt",{description:b})}finally{p(C=>({...C,[M]:!1}))}},[]),Q=s.useCallback(async()=>{u(!0);try{const M=await hi();c(M.overrides),v({}),R.success("All prompt overrides reset")}catch(M){const C=M instanceof Error?M.message:String(M);R.error("Failed to reset all prompts",{description:C})}finally{u(!1)}},[]);return r?e.jsxs("div",{className:"py-6 px-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-current animate-busy-pulse","aria-label":"Loading"}),e.jsx("span",{className:"typography-ui",children:"Loading PiChamber Utility Prompts..."})]}):e.jsx(Be,{title:P.title,titleAccessory:e.jsx(Xt,{contentClassName:"max-w-xs",children:P.description}),headerEnd:e.jsx(h,{"data-settings-item":"magic-prompts.reset-overrides",variant:"outline",size:"sm",onClick:()=>{Q()},disabled:j||Object.keys(o).length===0,children:j?"Resetting...":"Reset All Overrides"}),children:P.blocks.map((M,C)=>{const b=gi(M.id),S=A(M.id),k=F(M.id),l=or(o,M.id),y=k!==S,U=ln(M.id)&&k.trim().length===0,K=x[M.id]===!0,G=L[M.id]===!0;return e.jsxs(te,{title:M.title,info:b.description,description:b.placeholders&&b.placeholders.length>0?`Placeholders: ${b.placeholders.map(ae=>`{{${ae.key}}}`).join(", ")}`:void 0,divider:C>0,settingsItem:ln(M.id)?"magic-prompts.visible-prompt":"magic-prompts.instructions",contentClassName:"space-y-3",children:[e.jsx(Fr,{value:k,onChange:ae=>H(M.id,ae.target.value),className:"min-h-[220px] font-mono text-sm"}),U&&e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:"Visible prompt cannot be empty."}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:y?"Unsaved changes":l?"Using saved override":"Using built-in default"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"outline",size:"sm",onClick:()=>{W(M.id)},disabled:!l||K||G,children:G?"Resetting...":"Reset to Default"}),e.jsx(h,{size:"sm",onClick:()=>{_(M.id)},disabled:!y||K||G||U,children:K?"Saving...":"Save"})]})]})]},M.id)})})},fl=({snippet:t,onSelect:r,showSourcePill:i=!0})=>{const o=t.source==="project"?"Project":t.source==="global"?"Global":t.source,c=t.description?.trim()||t.content.replace(/\s+/g," ").trim().slice(0,140)||"No description",w=c.length>=140||(t.description?.trim()?.length??0)===0&&t.content.length>140;return e.jsxs("button",{type:"button",onClick:()=>r(t.name),"aria-label":`${t.name} snippet, ${o}`,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:[i?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:o})}):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:[c,w?"…":null]})]}),t.editable?null:e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/70",children:[e.jsx("span",{className:"inline-flex size-1.5 rounded-full bg-muted-foreground/40","aria-hidden":!0}),"Read-only"]})]})},xl=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((r,i)=>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"})]})]},i))}),bl=()=>{const{isMobile:t}=Mt(),r=Ot(V=>V.selectedSnippetName),i=Ot(V=>V.snippetDraft),o=Ot(V=>V.snippets),c=Ot(V=>V.isLoading),w=Ot(V=>V.setSelectedSnippet),v=Ot(V=>V.setSnippetDraft),x=Ot(V=>V.createSnippet),g=Ot(V=>V.updateSnippet),L=Ot(V=>V.deleteSnippet),p=Ot(V=>V.loadSnippets),j=s.useMemo(()=>r?o.find(V=>V.name===r)??null:null,[r,o]),u=!!(i&&!j&&r!==null),[P,A]=s.useState(""),[F,H]=s.useState("global"),[_,W]=s.useState(""),[Q,M]=s.useState(""),[C,b]=s.useState(!1),[S,k]=s.useState(!1),[l,y]=s.useState(!1),U=s.useRef(""),K=s.useRef("");s.useEffect(()=>{u&&i?(A(i.name),H(i.scope),W(i.description??""),M(i.content??""),U.current=i.content??"",K.current=i.name):j&&(A(j.name),H(j.source),W(j.description??""),M(j.content),U.current=j.content,K.current=j.name)},[i,u,j]);const G=s.useCallback(()=>{u&&v(null),w(null)},[u,w,v]),ae=s.useCallback(async()=>{const V=P.trim().replace(/\s+/g,"-");if(!V){R.error("Template name is required");return}if(!/^[a-z0-9_-]+$/i.test(V)){R.error("Template name may only contain letters, numbers, dashes and underscores");return}if(!Q.trim()){R.error("Snippet content is required");return}b(!0);const ye=u?await x(V,Q,{description:_,scope:F}):await g(j?.name??V,{content:Q});b(!1),ye?(u||v(null),R.success(u?"Template created":"Template updated")):R.error(u?"Failed to create template":"Failed to update template")},[Q,x,_,u,P,F,j?.name,v,g]),ge=s.useCallback(async()=>{if(!j)return;k(!0);const V=await L(j.name);k(!1),V?(R.success("Snippet deleted"),y(!1)):R.error("Failed to delete snippet")},[L,j]),[le,re]=s.useState(""),[de,we]=s.useState("all"),[ke,D]=s.useState(!1),q=s.useCallback(async()=>{if(!ke){D(!0);try{const{invalidateSnippetsLoadCache:V}=await pa(async()=>{const{invalidateSnippetsLoadCache:ye}=await import("./SessionSwitcherDropdown-DROjbyIu.js").then(Te=>Te.f0);return{invalidateSnippetsLoadCache:ye}},__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]));V(),await p()}finally{D(!1)}}},[p,ke]);s.useEffect(()=>{p()},[p]);const ce=s.useMemo(()=>[...o].sort((V,ye)=>V.name.localeCompare(ye.name)),[o]),ie=s.useMemo(()=>{let V=ce;de!=="all"&&(V=V.filter(Te=>Te.source===de));const ye=le.trim().toLowerCase();return ye?V.filter(Te=>{const ue=Te.name.toLowerCase().includes(ye),Fe=(Te.description??"").toLowerCase().includes(ye),Ve=Te.content.toLowerCase().includes(ye);return ue||Fe||Ve}):V},[ce,de,le]),I=s.useMemo(()=>{let V=0,ye=0;for(const Te of o)Te.source==="project"?ye+=1:V+=1;return{all:o.length,global:V,project:ye}},[o]),fe=s.useCallback(async()=>{const V=new Set(o.map(ue=>ue.name));let ye="new-snippet",Te=1;for(;V.has(ye);)ye=`new-snippet-${Te++}`;v({name:ye,scope:"global",content:"",description:""}),w(ye)},[w,v,o]);if(r!==null){if(!j&&!u)return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{p()}}),e.jsx(Be,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"ghost",size:"xs",onClick:G,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(f,{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(f,{name:"file-text",className:"size-8 text-muted-foreground/60","aria-hidden":!0}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Snippet “",r,"” was not found."]}),e.jsx(h,{variant:"outline",size:"sm",onClick:G,children:"Back to snippets"})]})})]});const V=u||j?.editable===!0,ye=u?P.trim()!==K.current||_!==(i?.description??"")||Q!==U.current||F!==(i?.scope??"global"):Q!==U.current,Te=V&&ye&&!C&&Q.trim().length>0&&P.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{p()}}),e.jsxs(Be,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"ghost",size:"xs",onClick:G,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(f,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:u?"New snippet":`#${j?.name??P}`})]}),description:u?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a new prompt template"}):j?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:j.description}):void 0,headerEnd:!u&&j?.editable===!0?e.jsxs(h,{variant:"ghost",size:"xs",onClick:()=>y(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(f,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[u?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(ne,{value:P,onChange:ue=>A(ue.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:["#",P.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(Qe,{value:F,onValueChange:ue=>H(ue),children:[e.jsx(Ye,{size:tt,className:"w-full",children:e.jsx(Je,{})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"global",children:"Global"}),e.jsx(Me,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:F==="project"?"Available only in this 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(ne,{value:_,onChange:ue=>W(ue.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(te,{title:"Details",divider:!1,settingsItem:"snippets.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",j?.source==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:j?.source==="project"?"Project":"Global"}),j?.editable!==!0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 text-muted-foreground",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-muted-foreground/60","aria-hidden":!0}),"Read-only"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-[var(--status-success)]/10 px-2.5 py-1 text-[var(--status-success)]",children:[e.jsx(f,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]})]}),V?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"This template is provided by Pi and cannot be edited. Create a new snippet to customize it."})]}),e.jsxs(te,{title:"Content",divider:!!u||!!j,settingsItem:"snippets.content",info:"Markdown is rendered in Pi chat when the template is used. Use headings, lists, and code blocks to structure your prompt.",headerAction:V?e.jsx("span",{className:"typography-micro text-muted-foreground",children:ye?"Unsaved changes":"No changes"}):null,children:[e.jsx(Pn,{value:Q,onChange:M,readOnly:!V,initialMode:u?"write":"preview"},u?"new-snippet-editor":`snippet-editor:${j?.name??""}`),V?e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(h,{variant:"ghost",size:"sm",onClick:G,children:"Cancel"}),e.jsx(h,{size:"sm",onClick:()=>{ae()},disabled:!Te,children:C?"Saving…":u?"Create snippet":"Save changes"})]}):null]}),!u&&j?.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 snippet"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Permanently remove #",j.name,"."]})]}),e.jsxs(h,{variant:"destructive",size:"sm",onClick:()=>y(!0),disabled:S,children:[e.jsx(f,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(wt,{open:l,onOpenChange:ue=>!ue&&y(!1),children:e.jsxs(jt,{className:"max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Delete snippet?"}),e.jsxs(It,{children:["This will permanently delete #",j?.name??"",". This cannot be undone."]})]}),e.jsxs(ga,{children:[e.jsx(h,{variant:"ghost",size:"sm",onClick:()=>y(!1),disabled:S,children:"Cancel"}),e.jsx(h,{variant:"destructive",size:"sm",onClick:()=>{ge()},disabled:S,children:S?"Deleting…":"Delete"})]})]})})]})}if(c&&o.length===0)return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{p()}}),e.jsx(Be,{title:t?void 0:"Snippets",description:t?void 0:"Prompt templates that expand as #name in the composer. Create your own to reuse long prompts.",headerEnd:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{q()},disabled:ke,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(f,{name:"refresh",className:J("size-4",ke&&"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(xl,{count:6})})})})]});const Se=ie.length===0&&o.length===0;return e.jsxs(e.Fragment,{children:[e.jsx(is,{onResolved:()=>{p()}}),e.jsx(Be,{title:t?void 0:"Snippets",description:t?void 0:"Prompt templates that expand as #name in the composer. Create your own to reuse long prompts.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(f,{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(ne,{value:le,onChange:V=>re(V.target.value),placeholder:"Search snippets","aria-label":"Search snippets",className:"h-9 w-[18rem] max-w-[24rem] pl-8"}),le?e.jsx("button",{type:"button",onClick:()=>re(""),"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(f,{name:"close",className:"size-4"})}):null]}),e.jsx(h,{variant:"ghost",size:"icon",onClick:()=>{q()},disabled:ke,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(f,{name:"refresh",className:J("size-4",ke&&"animate-spin")})}),e.jsxs(h,{variant:"outline",size:"sm",onClick:()=>{fe()},children:[e.jsx(f,{name:"add",className:"size-4"}),"New snippet"]})]}),children:Se?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(f,{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 markdown prompt templates. 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(h,{variant:"outline",size:"sm",onClick:()=>{fe()},children:[e.jsx(f,{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(h,{variant:"chip",size:"xs","aria-pressed":de==="all",onClick:()=>we("all"),children:["All ",I.all]}),e.jsxs(h,{variant:"chip",size:"xs","aria-pressed":de==="project",onClick:()=>we("project"),children:["Project ",I.project]}),e.jsxs(h,{variant:"chip",size:"xs","aria-pressed":de==="global",onClick:()=>we("global"),children:["Global ",I.global]})]}),ie.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:le.trim()?`No snippets match “${le}”.`:`No ${de} snippets.`}),e.jsx(h,{variant:"ghost",size:"xs",onClick:()=>{re(""),we("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[ie.map(V=>e.jsx(fl,{snippet:V,onSelect:w,showSourcePill:de==="all"},`${V.source}:${V.filePath}`)),e.jsxs("button",{type:"button",onClick:()=>{fe()},"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(f,{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:"Markdown prompt template"})]})]})]})})]})},En=()=>{const t=We(p=>p.settingsGitmojiEnabled),r=We(p=>p.setSettingsGitmojiEnabled),i=Vi(),o=T(p=>p.gitChangesViewMode),c=T(p=>p.setGitChangesViewMode),[w,v]=s.useState(!0),x=s.useMemo(()=>[{id:"flat",label:"Flat List"},{id:"tree",label:"Tree View"}],[]);s.useEffect(()=>{(async()=>{try{let j=null;if(!j){const u=ha()?.settings;if(u)try{const A=(await u.load())?.settings;A&&(j={gitmojiEnabled:typeof A.gitmojiEnabled=="boolean"?A.gitmojiEnabled:void 0,gitChangesViewMode:A.gitChangesViewMode==="flat"||A.gitChangesViewMode==="tree"?A.gitChangesViewMode:void 0})}catch{}}if(!j){const u=await ht("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(j=await u.json())}j&&(typeof j.gitmojiEnabled=="boolean"&&r(j.gitmojiEnabled),(j.gitChangesViewMode==="flat"||j.gitChangesViewMode==="tree")&&c(j.gitChangesViewMode))}catch(j){console.warn("Failed to load git settings:",j)}finally{v(!1)}})()},[c,r]);const g=s.useCallback(async p=>{r(p);try{await Ie({gitmojiEnabled:p})}catch(j){console.warn("Failed to save gitmoji setting:",j)}},[r]),L=s.useCallback(p=>{p!==o&&(c(p),Ie({gitChangesViewMode:p}))},[o,c]);return w?null:e.jsx(te,{title:"Git Preferences",children:e.jsxs("div",{className:Et,children:[e.jsx(Vs,{settingsItem:"git.changes-view",title:"Changes View",children:e.jsx(Ss,{"aria-label":"Git changes view mode",children:x.map(p=>e.jsx(Cs,{selected:o===p.id,onSelect:()=>{L(p.id)},label:p.label,ariaLabel:`Git changes view mode: ${p.label}`},p.id))})}),e.jsx(ve,{settingsItem:"git.gitmoji",checked:t,onChange:p=>{g(p)},label:"Enable Gitmoji Picker",ariaLabel:"Enable Gitmoji picker"}),e.jsx(ve,{settingsItem:"git.gitignored-files",checked:i,onChange:$i,label:"Display Gitignored Files",ariaLabel:"Display gitignored files"})]})})},lr=[{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)"}],vl=[{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"}],yl=({open:t,onOpenChange:r,profileId:i,importData:o})=>{const c=ua(I=>I.getProfileById),w=ua(I=>I.createProfile),v=ua(I=>I.updateProfile),x=ua(I=>I.deleteProfile),g=s.useMemo(()=>i&&i!=="new"&&!o?c(i):null,[i,c,o]),L=i==="new"||o!=null,p=i==="global",[j,u]=s.useState(""),[P,A]=s.useState(""),[F,H]=s.useState(""),[_,W]=s.useState("ssh"),[Q,M]=s.useState(""),[C,b]=s.useState(!1),[S,k]=s.useState(""),[l,y]=s.useState(""),[U,K]=s.useState("keyword"),[G,ae]=s.useState("branch"),[ge,le]=s.useState(!1),[re,de]=s.useState(!1),[we,ke]=s.useState(!1);s.useEffect(()=>{if(t){if(o){const I=o.host.split("/"),fe=I.length>=3?I[I.length-1]:o.host;u(fe),A(o.username),H(""),W("token"),M(""),b(!1),k(""),y(o.host),K("string"),ae("code")}else if(L)u(""),A(""),H(""),W("ssh"),M(""),b(!1),k(""),y(""),K("keyword"),ae("branch");else if(g)u(g.name),A(g.userName),H(g.userEmail),W(g.authType||"ssh"),M(g.sshKey||""),b(g.signCommits===!0),k(g.signingKey||""),y(g.host||""),K(g.color||"keyword"),ae(g.icon||"branch");else if(p){const I=c("global");I&&(u(I.name),A(I.userName),H(I.userEmail),W(I.authType||"ssh"),M(I.sshKey||""),b(!1),k(""),y(I.host||""),K(I.color||"keyword"),ae(I.icon||"branch"))}}},[t,i,g,L,o,p,c]);const D=async()=>{if(!P.trim()||!F.trim()){R.error("User name and email are required");return}if(_==="token"&&!l.trim()){R.error("Host is required for token-based authentication");return}if(C&&!S.trim()){R.error("Signing key is required when commit signing is enabled");return}le(!0);try{const I={name:j.trim()||P.trim(),userName:P.trim(),userEmail:F.trim(),authType:_,sshKey:_==="ssh"&&Q.trim()||null,signCommits:C,signingKey:S.trim()||null,host:_==="token"&&l.trim()||null,color:U,icon:G};let fe;if(L)fe=await w(I);else if(i)fe=await v(i,I);else return;fe?(R.success(L?"Profile created":"Profile updated"),r(!1)):R.error(L?"Failed to create profile":"Failed to update profile")}catch(I){console.error("Error saving profile:",I),R.error("An error occurred while saving")}finally{le(!1)}},q=async()=>{if(!(!i||L)){ke(!0);try{await x(i)?(R.success("Profile deleted"),de(!1),r(!1)):R.error("Failed to delete profile")}catch(I){console.error("Error deleting profile:",I),R.error("An error occurred while deleting")}finally{ke(!1)}}},ce=s.useMemo(()=>lr.find(fe=>fe.key===U)?.cssVar||"var(--syntax-keyword)",[U]),ie=o?"Import Credential":L?"New Identity":p?"Global Identity":g?.name||"Edit Identity";return e.jsxs(e.Fragment,{children:[e.jsx(wt,{open:t,onOpenChange:r,children:e.jsxs(jt,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:ie}),e.jsx(It,{children:p?"System-wide Git identity (read-only)":L?"Create a new Git identity profile":"Edit identity profile settings"})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[!p&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:`${st} block mb-1.5`,children:"Profile Name"}),e.jsx(ne,{value:j,onChange:I=>u(I.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:lr.map(I=>e.jsx("button",{type:"button",onClick:()=>K(I.key),className:J("w-6 h-6 rounded-md border-2 transition-all cursor-pointer",U===I.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:I.cssVar},title:I.label},I.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:vl.map(I=>{const fe=I.Icon;return e.jsx("button",{type:"button",onClick:()=>ae(I.key),className:J("w-7 h-7 rounded-md border-2 transition-all flex items-center justify-center cursor-pointer",G===I.key?"border-[var(--interactive-border)] bg-[var(--surface-muted)]":"border-transparent hover:border-[var(--interactive-border)] hover:bg-[var(--surface-muted)]/50"),title:I.label,children:e.jsx(f,{name:fe,className:"w-3.5 h-3.5",style:{color:G===I.key?ce:"var(--surface-muted-foreground)"}})},I.key)})})]})]}),!p&&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:st,children:"User Name"}),!p&&e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(Xt,{contentClassName:"max-w-xs",children:"The name that will appear in Git commit messages."})]}),e.jsx(ne,{value:P,onChange:I=>A(I.target.value),placeholder:"John Doe",required:!p,readOnly:p,disabled:p,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:st,children:"Email Address"}),!p&&e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(Xt,{contentClassName:"max-w-xs",children:"Should match your email in GitHub/GitLab for proper attribution."})]}),e.jsx(ne,{type:"email",value:F,onChange:I=>H(I.target.value),placeholder:"john@example.com",required:!p,readOnly:p,disabled:p,className:"h-8"})]})]}),!p&&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(h,{size:"sm",type:"button",variant:"chip","aria-pressed":_==="ssh",onClick:()=>W("ssh"),children:[e.jsx(f,{name:"lock-2",className:"w-3.5 h-3.5 mr-1"})," SSH"]}),e.jsxs(h,{size:"sm",type:"button",variant:"chip","aria-pressed":_==="token",onClick:()=>W("token"),children:[e.jsx(f,{name:"key",className:"w-3.5 h-3.5 mr-1"})," ","Token"]})]})]}),_==="ssh"&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:st,children:"SSH Key Path"}),e.jsx(Xt,{contentClassName:"max-w-xs",children:"Optional path to private key. e.g. ~/.ssh/id_ed25519"})]}),e.jsx(ne,{value:Q,onChange:I=>M(I.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:C,onChange:b,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:st,children:"Signing key"})}),e.jsx(ne,{value:S,onChange:I=>k(I.target.value),placeholder:"~/.ssh/id_ed25519.pub",disabled:!C,className:"h-8 font-mono text-xs"})]})]}),_==="token"&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx("label",{className:st,children:"Host"}),e.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),e.jsx(Xt,{contentClassName:"max-w-xs",children:"Token will be read from ~/.git-credentials for this host."})]}),e.jsx(ne,{value:l,onChange:I=>y(I.target.value),placeholder:"github.com",required:!0,className:"h-8 font-mono text-xs"})]})]})]})]}),e.jsxs(ga,{className:"gap-2",children:[!p&&!L&&e.jsxs(h,{variant:"outline",size:"sm",onClick:()=>de(!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(f,{name:"delete-bin",className:"w-3.5 h-3.5 mr-1"})," ","Delete"]}),e.jsx(h,{variant:"ghost",size:"sm",onClick:()=>r(!1),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:p?"Close":"Cancel"}),!p&&e.jsx(h,{size:"sm",onClick:D,disabled:ge,children:ge?"Saving...":L?"Create":"Save"})]})]})}),e.jsx(wt,{open:re,onOpenChange:I=>{we||de(I)},children:e.jsxs(jt,{className:"max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Delete Profile"}),e.jsx(It,{children:`Are you sure you want to delete \\"${g?.name||j}\\"?`})]}),e.jsxs(ga,{children:[e.jsx(h,{variant:"ghost",onClick:()=>de(!1),disabled:we,children:"Cancel"}),e.jsx(h,{size:"sm",variant:"destructive",onClick:()=>{q()},disabled:we,children:"Delete"})]})]})})]})},wl={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart"},jl={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},kl=()=>{const{isMobile:t}=Mt(),{profiles:r,globalIdentity:i,defaultGitIdentityId:o,deleteProfile:c,loadProfiles:w,loadGlobalIdentity:v,loadDiscoveredCredentials:x,loadDefaultGitIdentityId:g,setDefaultGitIdentityId:L,getUnimportedCredentials:p}=ua(Gr(l=>({profiles:l.profiles,globalIdentity:l.globalIdentity,defaultGitIdentityId:l.defaultGitIdentityId,deleteProfile:l.deleteProfile,loadProfiles:l.loadProfiles,loadGlobalIdentity:l.loadGlobalIdentity,loadDiscoveredCredentials:l.loadDiscoveredCredentials,loadDefaultGitIdentityId:l.loadDefaultGitIdentityId,setDefaultGitIdentityId:l.setDefaultGitIdentityId,getUnimportedCredentials:l.getUnimportedCredentials}))),[j,u]=s.useState(!1),[P,A]=s.useState(null),[F,H]=s.useState(null),[_,W]=s.useState(null),[Q,M]=s.useState(!1);s.useEffect(()=>{w(),v(),x(),g()},[w,v,x,g]);const C=p(),b=(l,y)=>{A(l),H(y??null),u(!0)},S=async l=>{const y=o===l?null:l;if(!await L(y)){R.error("Failed to update default identity");return}R.success(y?"Default identity updated":"Default identity unset")},k=async()=>{if(!_)return;M(!0),await c(_.id)?(R.success(`Profile \\"${_.name}\\" deleted`),W(null)):R.error("Failed to delete profile"),M(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(Be,{title:t?void 0:"Git",children:[e.jsx(te,{title:"Identities",headerAction:e.jsxs(h,{size:"sm",variant:"outline",onClick:()=>b("new"),children:[e.jsx(f,{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:[i&&e.jsx(cr,{profile:i,isDefault:o==="global",onEdit:()=>b("global"),onToggleDefault:()=>S("global"),isReadOnly:!0,hasBorder:r.length>0||C.length>0}),r.map((l,y)=>e.jsx(cr,{profile:l,isDefault:o===l.id,onEdit:()=>b(l.id),onToggleDefault:()=>S(l.id),onDelete:()=>W(l),hasBorder:y<r.length-1||C.length>0},l.id)),!i&&r.length===0&&C.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground",children:[e.jsx(f,{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"})]}),C.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"})}),C.map((l,y)=>e.jsx(Nl,{credential:l,onImport:()=>b("new",{host:l.host,username:l.username}),hasBorder:y<C.length-1},`${l.host}-${l.username}`))]})]})}),e.jsx(En,{})]}),e.jsx(yl,{open:j,onOpenChange:u,profileId:P,importData:F}),e.jsx(wt,{open:_!==null,onOpenChange:l=>{Q||l||W(null)},children:e.jsxs(jt,{className:"max-w-md",children:[e.jsxs(Pt,{children:[e.jsx(Tt,{children:"Delete Profile"}),e.jsx(It,{children:`Are you sure you want to delete \\"${_?.name??""}\\"?`})]}),e.jsxs(ga,{children:[e.jsx(h,{variant:"ghost",onClick:()=>W(null),disabled:Q,children:"Cancel"}),e.jsx(h,{size:"sm",variant:"destructive",onClick:()=>{k()},disabled:Q,children:"Delete"})]})]})})]})},cr=({profile:t,isDefault:r,onEdit:i,onToggleDefault:o,onDelete:c,isReadOnly:w,hasBorder:v})=>{const[x,g]=s.useState(!1),L=wl[t.icon||"branch"]||"git-branch",p=jl[t.color||""],j=t.authType||"ssh",u=A=>{A.currentTarget===A.target&&(A.key!=="Enter"&&A.key!==" "||(A.preventDefault(),i()))},P=A=>e.jsxs(e.Fragment,{children:[e.jsx(A,{onClick:F=>{F.stopPropagation(),o()},children:r?"Unset default":"Set as default"}),!w&&c&&e.jsxs(A,{onClick:F=>{F.stopPropagation(),c()},className:"text-destructive focus:text-destructive",children:[e.jsx(f,{name:"delete-bin",className:"h-4 w-4 mr-px"}),"Delete"]})]});return e.jsxs(go,{open:x,onOpenChange:g,children:[e.jsxs(fo,{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",v&&"border-b border-[var(--surface-subtle)]"),onClick:i,role:"button",tabIndex:0,onKeyDown:u,onContextMenu:A=>{A.preventDefault(),g(!0)}}),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(f,{name:L,className:"w-4 h-4 shrink-0",style:{color:p}}),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:j}),r&&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"}),w&&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:j==="token"&&t.host?t.host:t.userEmail})]})]}),e.jsxs(Sr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(h,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",onClick:A=>A.stopPropagation(),children:e.jsx(f,{name:"more-2",className:"h-3.5 w-3.5"})})}),e.jsx(Pr,{align:"end",className:"w-fit min-w-28",children:P(Tr)})]})]}),e.jsx(xo,{className:"w-fit min-w-28",children:P(bo)})]})},Nl=({credential:t,onImport:r,hasBorder:i})=>{const o=t.host.split("/"),c=o.length>=3?o[o.length-1]:t.host,w=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",i&&"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:c}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 truncate block leading-tight",children:w?t.host:t.username})]}),e.jsxs(h,{size:"sm",variant:"ghost",onClick:r,className:"gap-1 shrink-0",children:[e.jsx(f,{name:"download",className:"h-3 w-3"}),"Import"]})]})},Sl=["standalone","minimal-ui","fullscreen","window-controls-overlay"],Cl=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Pl=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":Sl.find(i=>Cl(i))??"browser",dr=()=>{const t=Pl();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},Tl=()=>{const[t,r]=s.useState(()=>dr());return s.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=[window.matchMedia("(display-mode: standalone)"),window.matchMedia("(display-mode: minimal-ui)"),window.matchMedia("(display-mode: fullscreen)"),window.matchMedia("(display-mode: window-controls-overlay)")],o=()=>{r(dr())};o();for(const c of i)typeof c.addEventListener=="function"?c.addEventListener("change",o):typeof c.addListener=="function"&&c.addListener(o);return window.addEventListener("appinstalled",o),window.addEventListener("focus",o),()=>{for(const c of i)typeof c.removeEventListener=="function"?c.removeEventListener("change",o):typeof c.removeListener=="function"&&c.removeListener(o);window.removeEventListener("appinstalled",o),window.removeEventListener("focus",o)}},[]),t},Il=[{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"}],El=[{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."}],Al=[{id:"svg",label:"SVG",description:"Render diagrams as scalable graphics."},{id:"ascii",label:"ASCII",description:"Render diagrams as text blocks."}],ca="PiChamber - AI Coding Assistant",ur=[{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."}],mr=[{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."}],Ml=[{value:"default",label:"Old"},{value:"new",label:"New"}],cn=t=>t==="portrait"||t==="landscape"?t:"system",Ll=[{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."}],pr=[{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."}],hr=[{id:"auto",label:"Auto",description:"Use locale week start."},{id:"monday",label:"Monday"},{id:"sunday",label:"Sunday"}],Rl=[{id:"steer",label:"Steer"},{id:"queue",label:"Queue"}],Dl=t=>t==="markdown"?"markdown":"plain",_l=[{id:"left",label:"Left"},{id:"right",label:"Right"}],Ol=[{id:"classic",label:"Classic"},{id:"traffic-lights",label:"Traffic lights"}],Fa=({visibleSettings:t})=>{const{isMobile:r}=Mt(),{terminal:i}=Ir(),{browserTab:o}=Tl(),c=Ki(),w=T(n=>n.showReasoningTraces),v=T(n=>n.setShowReasoningTraces),x=T(n=>n.collapsibleThinkingBlocks),g=T(n=>n.setCollapsibleThinkingBlocks),L=T(n=>n.collapseThinkingByDefault),p=T(n=>n.setCollapseThinkingByDefault),j=T(n=>n.mermaidRenderingMode),u=T(n=>n.setMermaidRenderingMode),P=T(n=>n.userMessageRenderingMode),A=T(n=>n.setUserMessageRenderingMode),F=T(n=>n.collapsibleUserMessages),H=T(n=>n.setCollapsibleUserMessages),_=T(n=>n.stickyUserHeader),W=T(n=>n.promptNavigatorEnabled),Q=T(n=>n.setStickyUserHeader),M=T(n=>n.setPromptNavigatorEnabled),C=T(n=>n.expandedEditorToolbar),b=T(n=>n.setExpandedEditorToolbar),S=T(n=>n.autoSaveEnabled),k=T(n=>n.setAutoSaveEnabled),l=T(n=>n.wideChatLayoutEnabled),y=T(n=>n.setWideChatLayoutEnabled),U=T(n=>n.codeBlockLineWrap),K=T(n=>n.setCodeBlockLineWrap),G=T(n=>n.fontSize),ae=T(n=>n.setFontSize),ge=T(n=>n.terminalFontSize),le=T(n=>n.setTerminalFontSize),re=T(n=>n.terminalShell),de=T(n=>n.setTerminalShell),we=T(n=>n.terminalLoginShells),ke=T(n=>n.setTerminalLoginShells),D=T(n=>n.editorFontSize),q=T(n=>n.setEditorFontSize),ce=T(n=>n.uiFont),ie=T(n=>n.setUiFont),I=T(n=>n.monoFont),fe=T(n=>n.setMonoFont),Se=T(n=>n.padding),V=T(n=>n.setPadding),ye=T(n=>n.inputBarOffset),Te=T(n=>n.setInputBarOffset),ue=T(n=>n.mobileKeyboardMode),Fe=T(n=>n.setMobileKeyboardMode),Ve=T(n=>n.diffLayoutPreference),kt=T(n=>n.setDiffLayoutPreference),Re=T(n=>n.showTerminalQuickKeysOnDesktop),rt=T(n=>n.setShowTerminalQuickKeysOnDesktop),Lt=T(n=>n.fileEditorKeymap),gt=T(n=>n.setFileEditorKeymap),N=Bn(n=>n.followUpBehavior),me=Bn(n=>n.setFollowUpBehavior),z=T(n=>n.persistChatDraft),ee=T(n=>n.setPersistChatDraft),xe=T(n=>n.inputSpellcheckEnabled),Ue=T(n=>n.setInputSpellcheckEnabled),He=T(n=>n.showToolFileIcons),O=T(n=>n.setShowToolFileIcons),X=T(n=>n.showTurnChangedFiles),pe=T(n=>n.setShowTurnChangedFiles),Ee=T(n=>n.showExpandedBashTools),Ce=T(n=>n.setShowExpandedBashTools),$e=T(n=>n.showExpandedEditTools),De=T(n=>n.setShowExpandedEditTools),Oe=T(n=>n.timeFormatPreference),nt=T(n=>n.setTimeFormatPreference),dt=T(n=>n.weekStartPreference),ut=T(n=>n.setWeekStartPreference),mt=T(n=>n.showSplitAssistantMessageActions),pt=T(n=>n.setShowSplitAssistantMessageActions),ze=T(n=>n.allowPromptingSubagentSessions),zt=T(n=>n.setAllowPromptingSubagentSessions),Vt=T(n=>n.draftStartersVisible),hs=T(n=>n.setDraftStartersVisible),gs=We(n=>n.settingsDefaultFileViewerPreview),fs=We(n=>n.setSettingsDefaultFileViewerPreview),{themeMode:xs,setThemeMode:es,availableThemes:it,customThemesLoading:Ps,reloadCustomThemes:ts,lightThemeId:bs,darkThemeId:Ts,setLightThemePreference:Is,setDarkThemePreference:os}=xi(),[ls,$t]=s.useState(!1),ft=s.useMemo(()=>at()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),Kt=T(n=>n.dockBadgeEnabled),d=T(n=>n.setDockBadgeEnabled),B=Wi(),se=T(n=>n.desktopWindowControlsPosition),Z=T(n=>n.setDesktopWindowControlsPosition),je=T(n=>n.desktopWindowControlsStyle),Ne=T(n=>n.setDesktopWindowControlsStyle),oe=s.useSyncExternalStore(Gi,qi,()=>!1),_e=s.useCallback(n=>{Z(n),Ie({desktopWindowControlsPosition:n})},[Z]),Wt=s.useCallback(n=>{Ne(n),Ie({desktopWindowControlsStyle:n})},[Ne]),Gt=s.useCallback(n=>{A(n),Ie({userMessageRenderingMode:n})},[A]),Es=s.useCallback(n=>{Q(n),Ie({stickyUserHeader:n})},[Q]),As=s.useCallback(n=>{M(n),Ie({promptNavigatorEnabled:n})},[M]),vs=s.useCallback(n=>{hs(n),Ie({draftStartersVisible:n})},[hs]),qt=s.useCallback(n=>{b(n),Ie({expandedEditorToolbar:n})},[b]),ys=s.useCallback(n=>{H(n),Ie({collapsibleUserMessages:n})},[H]),Qt=s.useCallback(n=>{v(n),Ie({showReasoningTraces:n})},[v]),Yt=s.useCallback(n=>{g(n),Ie({collapsibleThinkingBlocks:n})},[g]),ot=s.useCallback(n=>{p(n),Ie({collapseThinkingByDefault:n})},[p]),Qs=s.useCallback(n=>{y(n),Ie({wideChatLayoutEnabled:n})},[y]),Ua=s.useCallback(n=>{pt(n),Ie({showSplitAssistantMessageActions:n})},[pt]),Ba=s.useCallback(n=>{Ue(n),Ie({inputSpellcheckEnabled:n})},[Ue]),Ms=s.useCallback(n=>{u(n),Ie({mermaidRenderingMode:n})},[u]),Ls=s.useCallback(n=>{O(n),Ie({showToolFileIcons:n})},[O]),xa=s.useCallback(n=>{pe(n),Ie({showTurnChangedFiles:n})},[pe]),Ys=s.useCallback(n=>{fs(n),Ie({defaultFileViewerPreview:n}),window.dispatchEvent(new CustomEvent("pichamber:file-viewer-preview-mode-changed",{detail:{enabled:n}}))},[fs]),ba=s.useCallback(n=>{Ce(n),Ie({showExpandedBashTools:n})},[Ce]),va=s.useCallback(n=>{De(n),Ie({showExpandedEditTools:n})},[De]),Nt=s.useCallback(n=>{nt(n),Ie({timeFormatPreference:n})},[nt]),Ha=s.useCallback(n=>{ut(n),Ie({weekStartPreference:n})},[ut]),Rs=s.useMemo(()=>it.filter(n=>n.metadata.variant==="light").sort((n,be)=>n.metadata.name.localeCompare(be.metadata.name)),[it]),Ds=s.useMemo(()=>it.filter(n=>n.metadata.variant==="dark").sort((n,be)=>n.metadata.name.localeCompare(be.metadata.name)),[it]),Js=s.useMemo(()=>Rs.find(n=>n.metadata.id===bs)??Rs[0],[Rs,bs]),Xs=s.useMemo(()=>Ds.find(n=>n.metadata.id===Ts)??Ds[0],[Ds,Ts]),_s=s.useCallback((n,be)=>{const Dt=be==="dark"?" Dark":" Light";return n.endsWith(Dt)?n.slice(0,-Dt.length):n},[]),E=n=>t?t.includes(n):!0,xt=E("theme"),Os=E("windowControlsPosition")&&B,Va=E("theme")||E("timeFormat")||E("weekStart"),Zs=r&&ps()&&!at(),ya=E("theme")||Os||Zs||E("pwaInstallName")||E("pwaOrientation")||E("timeFormat")||E("weekStart"),wa=E("fontSize")||E("terminalFontSize")||E("editorFontSize")||E("spacing")||E("inputBarOffset")&&r,ja=E("terminalQuickKeys")||E("terminalShell")||E("terminalLoginShell")||E("fileEditorKeymap")||E("autoSaveEnabled")||E("expandedEditorToolbar"),$a=E("mermaidRendering")||E("userMessageRendering")||E("collapsibleUserMessages")||E("stickyUserHeader")||E("promptNavigatorEnabled")||E("wideChatLayout")||E("codeBlockLineWrap")||E("splitAssistantMessageActions")||E("subagentReadOnlyBanner")||E("diffLayout")||E("dotfiles")||E("fileViewerPreview")||E("reasoning")||E("followUpBehavior")||E("persistDraft")||E("showToolFileIcons")||E("expandedTools")||E("inputSpellcheck"),ka=E("userMessageRendering")||E("mermaidRendering")||E("diffLayout")||E("followUpBehavior"),bt=E("subagentReadOnlyBanner")||E("collapsibleUserMessages")||E("stickyUserHeader")||E("promptNavigatorEnabled")||E("wideChatLayout")||E("codeBlockLineWrap")||E("splitAssistantMessageActions")||E("dotfiles")||E("fileViewerPreview")||E("persistDraft")||E("showToolFileIcons")||E("showTurnChangedFiles")||E("inputSpellcheck")||E("reasoning")||E("expandedTools"),Ft=ya||wa||ja,Ut=E("pwaInstallName")&&ps()&&o&&!at(),vt=E("pwaOrientation")&&ps()&&!at(),St=E("mobileKeyboardMode")&&ps()&&!at()&&Qi(),ea=E("terminalShell")||E("terminalLoginShell"),[Jt,ta]=s.useState([]),[zs,Ka]=s.useState(0);s.useEffect(()=>Cn(()=>{ta([]),Ka(n=>n+1)}),[]),s.useEffect(()=>{let n=!1;if(!(!ea||!i.listShells))return i.listShells().then(be=>{n||ta(be)}).catch(()=>{n||ta([])}),()=>{n=!0}},[ea,i,zs]);const Ze=s.useMemo(()=>{const n=Jt.filter(be=>be.id!=="auto");return re==="auto"||n.some(be=>be.id===re)?n:[{id:re,name:re,supportsLogin:!1},...n]},[Jt,re]),Wa=Jt.find(n=>n.id===re)?.supportsLogin===!0,Fs=we.includes(re),Us=n=>{ke(n?[...we.filter(be=>be!==re),re]:we.filter(be=>be!==re))},[sa,Na]=s.useState(()=>No()),[cs,Rt]=s.useState(""),[Bs,Bt]=s.useState("system"),Ga=s.useMemo(()=>pr.find(be=>be.id===Oe)?.label??"Auto",[Oe]),qa=s.useMemo(()=>hr.find(be=>be.id===dt)?.label??"Auto",[dt]),Qa=s.useMemo(()=>{const n=ur.find(be=>be.id===Bs);return n?n.label:void 0},[Bs]),Ya=s.useMemo(()=>{const n=mr.find(be=>be.id===ue);return n?n.label:void 0},[ue]),Ja=s.useCallback(n=>{n!==sa&&(Na(n),So(n),window.location.reload())},[sa]),aa=s.useCallback(async n=>{if(typeof window>"u")return;const be=window,a=n.trim().replace(/\s+/g," ").slice(0,64);if(await Ie({pwaAppName:a}),typeof be.__PICHAMBER_SET_PWA_INSTALL_NAME__=="function"){const m=be.__PICHAMBER_SET_PWA_INSTALL_NAME__(a);Rt(m);return}Rt(a||ca),be.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Sa=s.useCallback(async n=>{if(typeof window>"u")return;const be=window,Dt=cn(n);if(await Ie({pwaOrientation:Dt}),typeof be.__PICHAMBER_SET_PWA_ORIENTATION__=="function"){const a=be.__PICHAMBER_SET_PWA_ORIENTATION__(Dt);Bt(a);return}Bt(Dt),be.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return s.useEffect(()=>{if(typeof window>"u"||!Ut&&!vt&&!St)return;let n=!1;return(async()=>{try{const Dt=await ht("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Dt.ok){n||Rt(ca);return}const a=await Dt.json().catch(()=>({})),$=(typeof a?.pwaAppName=="string"?a.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),Y=cn(a?.pwaOrientation),Le=Wn(a?.mobileKeyboardMode);n||(Ut&&Rt($||ca),vt&&Bt(Y),St&&Fe(Le))}catch{n||(Ut&&Rt(ca),vt&&Bt("system"),St&&Fe("native"))}})(),()=>{n=!0}},[Fe,St,Ut,vt]),e.jsxs(e.Fragment,{children:[ya&&e.jsxs(e.Fragment,{children:[xt&&e.jsxs(te,{title:"Color mode & Theme",divider:!1,children:[e.jsxs(ms,{children:[e.jsxs("div",{className:rs,children:[e.jsx(Ss,{"aria-label":"Color Mode",children:Il.map(n=>e.jsx(Cs,{selected:xs===n.value,onSelect:()=>es(n.value),label:n.label,ariaLabel:n.label},n.value))}),Zs&&e.jsx(Oa,{children:e.jsx(qe,{label:"Mobile Layout",children:e.jsx(Aa,{value:sa,options:Ml.map(n=>({value:n.value,label:n.label})),onChange:Ja,"aria-label":"Mobile Layout"})})})]}),e.jsxs("div",{className:rs,children:[e.jsx(qe,{label:"Light Theme",settingsItem:"appearance.light-theme",children:e.jsxs(Qe,{value:Js?.metadata.id??"",onValueChange:Is,children:[e.jsx(Ye,{"aria-label":"Select light theme",size:tt,className:js,children:e.jsx(Je,{placeholder:"Select theme",children:Js?_s(Js.metadata.name,"light"):void 0})}),e.jsx(Xe,{children:Rs.map(n=>e.jsx(Me,{value:n.metadata.id,children:_s(n.metadata.name,"light")},n.metadata.id))})]})}),e.jsx(qe,{label:"Dark Theme",settingsItem:"appearance.dark-theme",children:e.jsxs(Qe,{value:Xs?.metadata.id??"",onValueChange:os,children:[e.jsx(Ye,{"aria-label":"Select dark theme",size:tt,className:js,children:e.jsx(Je,{placeholder:"Select theme",children:Xs?_s(Xs.metadata.name,"dark"):void 0})}),e.jsx(Xe,{children:Ds.map(n=>e.jsx(Me,{value:n.metadata.id,children:_s(n.metadata.name,"dark")},n.metadata.id))})]})}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{type:"button",disabled:Ps||ls,onClick:()=>{const n=Date.now();$t(!0),ts().finally(()=>{const be=Date.now()-n;if(be<500){window.setTimeout(()=>{$t(!1)},500-be);return}$t(!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(f,{name:"restart",className:J("h-3.5 w-3.5",ls&&"animate-spin")}),ls?"Reloading themes...":"Reload themes"]}),e.jsx(Xt,{children:"Import custom themes from ~/.config/pichamber/themes/"})]})]})]}),ft&&e.jsx(Oa,{settingsItem:"appearance.dock-badge",children:e.jsx(ve,{checked:Kt,onChange:d,label:"Dock badge",info:"Show a count of chats with unseen activity on the macOS dock icon.",ariaLabel:"Dock badge"})})]}),Os&&e.jsx(te,{title:"Window controls",info:"Choose where minimize, maximize, and close buttons appear. Defaults to the right.",divider:xt,children:e.jsxs(ms,{children:[e.jsx(qe,{label:"Window controls position",settingsItem:"sessions.desktop-window-controls-position",children:e.jsx(Aa,{value:se,options:_l.map(n=>({value:n.id,label:n.label})),onChange:_e,"aria-label":"Window controls position"})}),e.jsx(qe,{label:"Style",settingsItem:"sessions.desktop-window-controls-style",children:e.jsx(Aa,{value:je,options:Ol.map(n=>({value:n.id,label:n.label})),onChange:Wt,"aria-label":"Window controls style"})})]})}),Va&&e.jsx(te,{title:"Localization",children:e.jsx(ms,{children:(E("timeFormat")||E("weekStart"))&&e.jsxs("div",{className:rs,children:[E("timeFormat")&&e.jsx(qe,{label:"Time Format",settingsItem:"appearance.time-format",children:e.jsxs(Qe,{value:Oe,onValueChange:n=>Nt(n),children:[e.jsx(Ye,{"aria-label":"Select time format",size:tt,className:js,children:e.jsx(Je,{children:Ga})}),e.jsx(Xe,{children:pr.map(n=>e.jsx(Me,{value:n.id,children:n.label},n.id))})]})}),E("weekStart")&&e.jsx(qe,{label:"Week Starts On",settingsItem:"appearance.week-start",children:e.jsxs(Qe,{value:dt,onValueChange:n=>Ha(n),children:[e.jsx(Ye,{"aria-label":"Select week start",size:tt,className:js,children:e.jsx(Je,{children:qa})}),e.jsx(Xe,{children:hr.map(n=>e.jsx(Me,{value:n.id,children:n.label},n.id))})]})})]})})}),(Ut||vt||St)&&e.jsxs(te,{title:"App install",contentClassName:rs,children:[Ut&&e.jsxs(ct,{label:"Install App Name",info:"Used by PWA installation process.",settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:Gs,children:[e.jsx(ne,{value:cs,onChange:n=>{Rt(n.target.value)},onBlur:()=>{aa(cs)},onKeyDown:n=>{n.key==="Enter"&&(n.preventDefault(),aa(cs))},className:"min-w-0 flex-1",maxLength:64,"aria-label":"PWA install app name"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Rt(ca),aa("")},className:yt,"aria-label":"Reset install app name",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]}),vt&&e.jsxs(ct,{label:"Install Orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:Gs,children:[e.jsxs(Qe,{value:Bs,onValueChange:n=>{const be=cn(n);Bt(be),Sa(be)},children:[e.jsx(Ye,{"aria-label":"PWA install orientation",size:tt,className:Qn,children:e.jsx(Je,{placeholder:"Select orientation",children:Qa})}),e.jsx(Xe,{children:ur.map(n=>e.jsx(Me,{value:n.id,children:n.label},n.id))})]}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Bt("system"),Sa("system")},disabled:Bs==="system",className:yt,"aria-label":"Reset install orientation",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]}),St&&e.jsxs(ct,{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:Gs,children:[e.jsxs(Qe,{value:ue,onValueChange:n=>{const be=Wn(n);Fe(be),Ie({mobileKeyboardMode:be})},children:[e.jsx(Ye,{"aria-label":"Mobile keyboard behavior",size:tt,className:Qn,children:e.jsx(Je,{placeholder:"Select keyboard behavior",children:Ya})}),e.jsx(Xe,{children:mr.map(n=>e.jsx(Me,{value:n.id,children:n.label},n.id))})]}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Fe("native"),Ie({mobileKeyboardMode:"native"})},disabled:ue==="native",className:yt,"aria-label":"Reset mobile keyboard behavior",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})]})]}),wa&&e.jsxs(te,{title:"Density & type",contentClassName:rs,children:[E("fontSize")||E("terminalFontSize")?e.jsxs(ms,{children:[E("fontSize")&&e.jsxs(qe,{label:"Interface Font",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[e.jsxs(Qe,{value:ce,onValueChange:n=>ie(n),children:[e.jsx(Ye,{"aria-label":"Select interface font",size:tt,className:js,children:e.jsx(Je,{children:Hn.find(n=>n.id===ce)?.label})}),e.jsx(Xe,{children:Hn.map(n=>e.jsx(Me,{value:n.id,children:e.jsx("span",{style:{fontFamily:n.stack},children:n.label})},n.id))})]}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>ie(Vn),disabled:ce===Vn,className:yt,"aria-label":"Reset interface font",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]}),E("terminalFontSize")&&e.jsxs(qe,{label:"Code Font",controlClassName:"w-full",children:[e.jsxs(Qe,{value:I,onValueChange:n=>fe(n),children:[e.jsx(Ye,{"aria-label":"Select code font",size:tt,className:js,children:e.jsx(Je,{children:$n.find(n=>n.id===I)?.label})}),e.jsx(Xe,{children:$n.map(n=>e.jsx(Me,{value:n.id,children:e.jsx("span",{style:{fontFamily:n.stack},children:n.label})},n.id))})]}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>fe(Kn),disabled:I===Kn,className:yt,"aria-label":"Reset code font",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,E("fontSize")||E("terminalFontSize")||E("editorFontSize")?e.jsxs(ms,{children:[E("fontSize")&&e.jsx(qe,{label:"Interface Font Size",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:$s,children:[e.jsx(At,{value:G,onValueChange:ae,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx("span",{className:Ks,children:"%"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>ae(100),disabled:G===100,className:yt,"aria-label":"Reset font size",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})}),E("terminalFontSize")&&e.jsx(qe,{label:"Terminal Font Size",settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:$s,children:[e.jsx(At,{value:ge,onValueChange:le,min:9,max:52,step:1}),e.jsx("span",{className:Ks,children:"px"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>le(13),disabled:ge===13,className:yt,"aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})}),E("editorFontSize")&&e.jsx(qe,{label:"Editor Font Size",settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:$s,children:[e.jsx(At,{value:D,onValueChange:q,min:9,max:32,step:1}),e.jsx("span",{className:Ks,children:"px"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>q(13),disabled:D===13,className:yt,"aria-label":"Reset editor font size",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,E("spacing")||E("inputBarOffset")&&r?e.jsxs(ms,{children:[E("spacing")&&e.jsx(qe,{label:"Spacing Density",settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:e.jsxs("div",{className:$s,children:[e.jsx(At,{value:Se,onValueChange:V,min:50,max:200,step:5}),e.jsx("span",{className:Ks,children:"%"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>V(100),disabled:Se===100,className:yt,"aria-label":"Reset spacing",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})}),E("inputBarOffset")&&r&&e.jsx(qe,{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:$s,children:[e.jsx(At,{value:ye,onValueChange:Te,min:0,max:100,step:5}),e.jsx("span",{className:Ks,children:"px"}),e.jsx(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>Te(0),disabled:ye===0,className:yt,"aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),ja&&e.jsxs(te,{title:"Navigation",contentClassName:"space-y-4",children:[E("fileEditorKeymap")&&e.jsx(Vs,{title:"File editor keymap",settingsItem:"appearance.file-editor-keymap",children:e.jsx(Ss,{"aria-label":"File editor keymap",children:["default","vim"].map(n=>e.jsx(Cs,{selected:Lt===n,onSelect:()=>gt(n),label:n==="default"?"Default":"Vim",ariaLabel:n==="default"?"Default":"Vim"},n))})}),e.jsxs("div",{className:Et,children:[E("autoSaveEnabled")&&e.jsx(ve,{checked:S,onChange:k,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"}),E("expandedEditorToolbar")&&e.jsx(ve,{checked:C,onChange:qt,label:"Always show editor toolbar (docked under the file tabs)",ariaLabel:"Always show editor toolbar",settingsItem:"appearance.expanded-editor-toolbar"}),E("terminalQuickKeys")&&e.jsx(ve,{checked:Re,onChange:rt,label:"Terminal Quick Keys",ariaLabel:"Terminal quick keys",settingsItem:"appearance.terminal-quick-keys",info:"Show Esc, Ctrl, Arrows in terminal view"}),ea&&e.jsx(qe,{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(Qe,{value:re,onValueChange:n=>{Yi(n)&&de(n)},children:[e.jsx(Ye,{"aria-label":"Select terminal shell",size:tt,className:js,children:e.jsx(Je,{})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:"auto",children:"Auto"}),Ze.map(n=>e.jsx(Me,{value:n.id,children:n.name},n.id))]})]})}),ea&&Wa&&e.jsx(ve,{checked:Fs,onChange:Us,label:"Start as login shell",ariaLabel:"Start as login shell",settingsItem:"appearance.terminal-login-shell"})]})]}),$a&&e.jsxs(e.Fragment,{children:[ka&&e.jsx(te,{title:"Message options",divider:Ft,children:e.jsxs(ms,{className:"lg:gap-y-6",children:[E("userMessageRendering")&&e.jsx(Vs,{title:"User Message Rendering",children:e.jsx(Ss,{"aria-label":"User message rendering mode",children:Ll.map(n=>e.jsx(Cs,{selected:Dl(P)===n.id,onSelect:()=>Gt(n.id),label:n.label,ariaLabel:`User message rendering: ${n.label}`},n.id))})}),E("mermaidRendering")&&e.jsx(Vs,{title:"Mermaid Rendering",children:e.jsx(Ss,{"aria-label":"Mermaid rendering mode",children:Al.map(n=>e.jsx(Cs,{selected:j===n.id,onSelect:()=>Ms(n.id),label:n.label,ariaLabel:`Mermaid rendering: ${n.label}`},n.id))})}),E("diffLayout")&&e.jsx(Vs,{title:"Diff Layout",children:e.jsx(Ss,{"aria-label":"Diff layout",children:El.map(n=>e.jsx(Cs,{selected:Ve===n.id,onSelect:()=>kt(n.id),label:n.label,ariaLabel:`Diff layout: ${n.label}`},n.id))})}),E("followUpBehavior")&&e.jsx(Vs,{title:"Follow-up behavior",settingsItem:"chat.follow-up-behavior",children:e.jsx(Ss,{"aria-label":"Follow-up behavior",children:Rl.map(n=>e.jsx(Cs,{selected:N===n.id,onSelect:()=>me(n.id),label:n.label,ariaLabel:`Follow-up behavior: ${n.label}`},n.id))})})]})}),bt&&e.jsxs(e.Fragment,{children:[E("expandedTools")&&e.jsxs(te,{title:"Show tools opened by default",divider:ka||Ft,contentClassName:Et,children:[e.jsx(ve,{checked:Ee,onChange:ba,label:"Bash",ariaLabel:"Show expanded bash tools"}),e.jsx(ve,{checked:$e,onChange:va,label:"Edit tools",ariaLabel:"Show expanded edit tools"})]}),e.jsxs(te,{title:"Features",contentClassName:Et,children:[e.jsx(ve,{checked:Vt,onChange:vs,label:"Show Starters on New Session Screen",ariaLabel:"Show starters on the new session screen",settingsItem:"chat.draft-starters-visible"}),E("subagentReadOnlyBanner")&&e.jsx(ve,{checked:ze,onChange:zt,label:"Allow Prompting Subagent Sessions",ariaLabel:"Allow prompting subagent sessions",settingsItem:"chat.subagent-read-only-banner"})]}),E("reasoning")&&e.jsxs(te,{title:"Reasoning",settingsItem:"chat.reasoning",contentClassName:Et,children:[e.jsx(ve,{checked:w,onChange:Qt,label:"Show Reasoning Traces",ariaLabel:"Show reasoning traces",settingsItem:"chat.reasoning-traces"}),w&&e.jsx(ve,{checked:x,onChange:Yt,label:"Enable Collapsible Reasoning Blocks",ariaLabel:"Enable collapsible reasoning blocks",settingsItem:"chat.collapsible-reasoning"}),w&&x&&e.jsx(ve,{checked:L,onChange:ot,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"})]}),(E("collapsibleUserMessages")||E("stickyUserHeader")||E("promptNavigatorEnabled")||E("wideChatLayout")||E("splitAssistantMessageActions")||E("codeBlockLineWrap"))&&e.jsxs(te,{title:"Message Appearance",settingsItem:"chat.message-appearance",contentClassName:Et,children:[E("collapsibleUserMessages")&&e.jsx(ve,{checked:F,onChange:ys,label:"Collapse Long User Messages",ariaLabel:"Collapse long user messages",settingsItem:"chat.collapsible-user-messages"}),E("stickyUserHeader")&&e.jsx(ve,{checked:_,onChange:Es,label:"Sticky User Header",ariaLabel:"Sticky user header",settingsItem:"chat.sticky-user-header"}),E("promptNavigatorEnabled")&&e.jsx(ve,{checked:W,onChange:As,label:"Prompt Navigator",ariaLabel:"Prompt navigator",settingsItem:"chat.prompt-navigator"}),E("wideChatLayout")&&e.jsx(ve,{checked:l,onChange:Qs,label:"Wide Chat Layout",ariaLabel:"Wide chat layout",settingsItem:"chat.wide-layout"}),E("splitAssistantMessageActions")&&e.jsx(ve,{checked:mt,onChange:Ua,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."}),E("codeBlockLineWrap")&&e.jsx(ve,{checked:U,onChange:K,label:"Wrap Code Block Lines",ariaLabel:"Wrap code block lines",settingsItem:"chat.code-block-line-wrap"})]}),(E("showToolFileIcons")||E("showTurnChangedFiles")||E("dotfiles")||E("fileViewerPreview"))&&e.jsxs(te,{title:"Tools & Files",settingsItem:"chat.tools-and-files",contentClassName:Et,children:[E("showToolFileIcons")&&e.jsx(ve,{checked:He,onChange:Ls,label:"Show Tool File Icons",ariaLabel:"Show tool file icons",settingsItem:"chat.tool-file-icons"}),E("showTurnChangedFiles")&&e.jsx(ve,{checked:X,onChange:xa,label:"Show Changed Files for Completed Turns",ariaLabel:"Show changed files for completed turns",settingsItem:"chat.changed-files"}),E("dotfiles")&&e.jsx(ve,{checked:c,onChange:Ji,label:"Show Dotfiles",ariaLabel:"Show dotfiles",settingsItem:"chat.dotfiles"}),E("fileViewerPreview")&&e.jsx(ve,{checked:gs,onChange:Ys,label:"Open previewable files in preview mode",ariaLabel:"Open previewable files in preview mode"})]}),(E("persistDraft")||E("inputSpellcheck"))&&e.jsxs(te,{title:"Composer",settingsItem:"chat.composer",contentClassName:Et,children:[E("persistDraft")&&e.jsx(ve,{checked:z,onChange:ee,label:"Persist Draft Messages",ariaLabel:"Persist draft messages",settingsItem:"chat.persist-drafts"}),E("inputSpellcheck")&&e.jsx(ve,{checked:xe,onChange:Ba,label:"Enable Spellcheck in Text Inputs",ariaLabel:"Enable spellcheck in text inputs",settingsItem:"chat.spellcheck"})]})]})]}),E("perfHud")&&e.jsx(te,{title:"Diagnostics",children:e.jsx(ve,{checked:oe,onChange:Xi,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"})})]})},zl=1,Fl=365,gr=30,Ul=[{value:"archive",label:"Archive"},{value:"delete",label:"Delete"}],Zr=()=>{const t=T(u=>u.autoDeleteEnabled),r=T(u=>u.autoDeleteAfterDays),i=T(u=>u.sessionRetentionAction),o=T(u=>u.setAutoDeleteEnabled),c=T(u=>u.setAutoDeleteAfterDays),w=T(u=>u.setSessionRetentionAction),{candidates:v,isRunning:x,runCleanup:g,action:L}=bi({autoRun:!1}),p=v.length,j=s.useCallback(async()=>{const u=await g({force:!0});if(u.completedIds.length===0&&u.failedIds.length===0){R.message(u.action==="archive"?"No sessions eligible for archiving":"No sessions eligible for deletion");return}u.completedIds.length>0&&R.success(u.action==="archive"?`Archived ${u.completedIds.length} session(s)`:`Deleted ${u.completedIds.length} session(s)`),u.failedIds.length>0&&R.error(u.action==="archive"?`Failed to archive ${u.failedIds.length} session(s)`:`Failed to delete ${u.failedIds.length} session(s)`)},[g]);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:o,label:"Enable Auto-Cleanup",ariaLabel:"Enable auto-cleanup"}),e.jsxs(Oa,{className:"space-y-0",children:[e.jsxs(ct,{settingsItem:"sessions.retention-period",label:"Retention Period",children:[e.jsx(At,{value:r,onValueChange:c,min:zl,max:Fl,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(h,{size:"sm",type:"button",variant:"ghost",onClick:()=>c(gr),disabled:r===gr,className:yt,"aria-label":"Reset retention period",title:"Reset",children:e.jsx(f,{name:"restart",className:"h-3.5 w-3.5"})})]}),e.jsx(ct,{settingsItem:"sessions.retention-action",label:"When sessions expire",children:e.jsx(Aa,{value:i,onChange:w,options:Ul.map(u=>({value:u.value,label:u.label}))})})]}),e.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[e.jsx(ct,{label:"Manual Cleanup",children:e.jsx(h,{type:"button",variant:"outline",size:"xs",onClick:j,disabled:x,className:"!font-normal",children:x?"Cleaning up...":"Run cleanup now"})}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:L==="archive"?`Eligible for archiving right now: ${p}`:`Eligible for deletion right now: ${p}`})]})]})},fr=(t,r,i)=>!t||!Number.isFinite(t)?r:new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short",hour12:i==="auto"?void 0:i==="12h"}).format(t),ei=()=>{const t=T(b=>b.timeFormatPreference),[r,i]=s.useState(!1),[o,c]=s.useState(!0),[w,v]=s.useState(!1),[x,g]=s.useState(null),[L,p]=s.useState(!1),[j,u]=s.useState([]),[P,A]=s.useState(vi),[F,H]=s.useState(""),_=s.useMemo(()=>yi(),[]),W=s.useCallback(async()=>{c(!0),H("");try{const b=await wi();u(b)}catch(b){const S=b instanceof Error?b.message:"Could not load passkeys.";H(S)}finally{c(!1)}},[]);s.useEffect(()=>{let b=!1;return(async()=>{try{if(!_.supported){b||(i(!1),c(!1));return}b||i(!0)}catch{b||i(!1)}if(!b){const S=await sn();if(A(S),!S.enabled){u([]),c(!1);return}await W()}})(),()=>{b=!0,Rn()}},[W,_.supported]);const Q=s.useCallback(async()=>{if(!P.enabled){const b="Enable the UI password lock before adding passkeys.";H(b),R.message(b);return}if(!r){H(_.reason),R.message(_.reason);return}if(w){Rn(),v(!1);return}H(""),v(!0);try{await ji(),A(await sn()),await W(),R.success("Passkey added")}catch(b){if(ki(b)){R.message("Passkey setup canceled");return}const S=b instanceof Error?b.message:"Could not add passkey.";H(S),R.error(S)}finally{v(!1)}},[w,W,P.enabled,_.reason,r]),M=s.useCallback(async b=>{g(b),H("");try{await Ni(b),A(await sn()),await W(),R.success("Passkey removed")}catch(S){const k=S instanceof Error?S.message:"Could not remove passkey.";H(k),R.error(k)}finally{g(null)}},[W]),C=s.useCallback(async()=>{p(!0),H("");try{await Si(),window.location.reload()}catch(b){const S=b instanceof Error?b.message:"Could not clear saved authentication.";H(S),R.error(S),p(!1)}},[]);return e.jsxs(te,{title:"Passkeys",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{label:"Current device",children:[e.jsx(h,{type:"button",variant:w?"secondary":"outline",size:"xs",onClick:()=>{Q()},disabled:o||L,className:"!font-normal",children:w?"Cancel passkey setup":"Add passkey"}),e.jsx(h,{type:"button",variant:"ghost",size:"xs",onClick:()=>{C()},disabled:o||w||L,className:"!font-normal text-muted-foreground hover:text-foreground",children:L?"Signing out…":"Sign out everywhere"})]}),!P.enabled&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Passkeys are available only when the UI password lock is enabled."}),P.enabled&&!r&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:_.reason}),o?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading passkeys…"}):j.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:j.map(b=>e.jsxs(ct,{label:e.jsx("span",{className:"truncate",children:b.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:b.lastUsedAt?`Last used ${fr(b.lastUsedAt,"Never used",t)}`:`Added ${fr(b.createdAt,"Never used",t)}`}),e.jsx(h,{type:"button",variant:"ghost",size:"xs",onClick:()=>{M(b.id)},disabled:x===b.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:x===b.id?"Removing…":"Delete"})]},b.id))})]}),F&&e.jsx("div",{className:"mt-1 py-1.5",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:F})})]})},Bl=t=>{if(!t)return;const r=t.providerId.trim(),i=t.modelId.trim();if(!(!r||!i))return`${r}/${i}`},dn=t=>{const r=Ci(t??void 0);return r?{providerId:r.providerId,modelId:r.modelId}:null},Hl=(t,r={})=>{if(!t)return{};const i={};if(!r.defaultModel){const o=dn(typeof t.defaultModel=="string"?t.defaultModel:void 0);o&&(i.defaultModel=o)}if(!r.smallModel&&t.smallModelUseDefault===!1){const o=dn(typeof t.smallModelOverride=="string"?t.smallModelOverride:void 0);o&&(i.smallModel=o)}if(!r.walkthroughModel){const o=dn(typeof t.walkthroughModelOverride=="string"?t.walkthroughModelOverride:void 0);o&&(i.walkthroughModel=o)}return i},Vl=t=>!!(t.defaultModel||t.smallModel||t.walkthroughModel),un=()=>({runtimeKey:Zt()}),Ta="__pi_fallback__",$l=(t,r)=>{const i=[...t];return r&&!i.includes(r)&&i.push(r),i},ti=()=>{const t=We(l=>l.providers),r=We(l=>l.modelsMetadata),i=We(l=>l.loadProviders),o=We(l=>l.setProvider),c=We(l=>l.setModel),w=We(l=>l.setSettingsDefaultModel),v=We(l=>l.setSettingsDefaultThinking),x=We(l=>l.setSettingsDefaultThinkingByModel),g=T(l=>l.showDeletionDialog),L=T(l=>l.setShowDeletionDialog),[p,j]=s.useState(null),[u,P]=s.useState("loading"),A=s.useCallback(l=>{j(l),w(Bl(l.defaultModel)),v(l.defaultThinking),x(l.defaultThinkingByModel??{})},[w,v,x]);s.useEffect(()=>{i({source:"sessionsDefaults"})},[i]),s.useEffect(()=>{let l=!0;return(async()=>{try{const U=await et.getSettings(un());if(!l)return;let K=U.pichamber;if(!K.defaultModel&&!K.smallModel&&!K.walkthroughModel){const G=ha()?.settings;if(G)try{const ae=await G.load(),ge=Hl(ae?.settings,K);if(Vl(ge)){const le=await et.setPiChamberDefaults(ge,un());if(!l)return;K=le.pichamber,await Ie({defaultModel:"",smallModelOverride:"",walkthroughModelOverride:""})}}catch{}}if(!l)return;A(K),P("ready")}catch{l&&P("failed")}})(),()=>{l=!1}},[A]);const F=s.useCallback(async l=>{Ws("saving");try{const y=await et.setPiChamberDefaults(l,un());A(y.pichamber),Ws("saved")}catch{Ws("error")}},[A]),H=s.useCallback((l,y)=>{const U=t.find(G=>G.id===l);return(Array.isArray(U?.models)?U.models:[]).find(G=>G.id===y)},[t]),_=s.useCallback(l=>{l&&t.find(U=>U.id===l.providerId)&&(o(l.providerId),c(l.modelId)),F({defaultModel:l})},[F,t,c,o]),W=s.useCallback((l,y)=>{const U=Ra(l);U&&F({defaultThinkingByModel:{[U]:y}})},[F]),Q=s.useCallback((l,y)=>r.get(`${l}/${y}`)?.structured_output!==!1,[r]);if(u==="loading")return null;if(u==="failed"&&!p)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 M=Ra(p?.defaultModel),C=p?.defaultModel?H(p.defaultModel.providerId,p.defaultModel.modelId):void 0,b=Ar(C),S=!!(p?.defaultModel&&Mr(b)),k=M?p?.defaultThinkingByModel?.[M]: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:rs,children:[e.jsx(ct,{settingsItem:"sessions.default-model",label:"Default Model",info:"The model new sessions start with. Unset keeps Pi's default.",children:e.jsx(nn,{value:p?.defaultModel??null,noneLabel:"Default",ariaLabel:"Default model",onChange:_})}),S&&p?.defaultModel?e.jsx(ct,{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(Qe,{value:k??Ta,onValueChange:l=>{W(p.defaultModel,l===Ta?null:l)},children:[e.jsx(Ye,{size:tt,className:Br,"aria-label":"Default thinking",children:e.jsx(Je,{children:l=>l===Ta?"Default":l?Da[l]??l:""})}),e.jsxs(Xe,{children:[e.jsx(Me,{value:Ta,children:"Default"}),$l(b,k).map(l=>e.jsx(Me,{value:l,children:Da[l]},l))]})]})}):null,e.jsx(ct,{settingsItem:"sessions.small-model",label:"Small Model",info:"A cheap model for quick utility tasks like short recaps and summaries.",children:e.jsx(nn,{value:p?.smallModel??null,noneLabel:"Use default small model",ariaLabel:"Small model",onChange:l=>{F({smallModel:l})}})}),e.jsx(ct,{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(nn,{value:p?.walkthroughModel??null,noneLabel:"Small model",ariaLabel:"Changes walkthrough model",isModelAllowed:Q,onChange:l=>{F({walkthroughModel:l})}})}),e.jsx(ct,{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:Gs,children:e.jsxs("div",{className:$s,children:[e.jsx(At,{value:p?.defaultRetryLimit??3,min:0,max:10,step:1,"aria-label":"Default retry limit",onValueChange:l=>{if(!Number.isFinite(l))return;const y=Math.max(0,Math.min(10,Math.round(l)));F({defaultRetryLimit:y})}}),e.jsx("span",{className:Ks,children:"retries"})]})})}),e.jsx(Oa,{className:Et,children:e.jsx(ve,{settingsItem:"sessions.deletion-dialog",checked:g,onChange:L,label:"Show Deletion Dialog",ariaLabel:"Show deletion dialog"})})]})})},xr={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"}},Kl={completion:"completion",subtask:"Subagent Completion",error:"error",question:"question"},Wl=()=>{const t=s.useMemo(()=>at(),[]),r=s.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),i=!t&&!r,o=T(D=>D.nativeNotificationsEnabled),c=T(D=>D.setNativeNotificationsEnabled),w=T(D=>D.notificationMode),v=T(D=>D.setNotificationMode),x=T(D=>D.notifyOnSubtasks),g=T(D=>D.setNotifyOnSubtasks),L=T(D=>D.notifyOnCompletion),p=T(D=>D.setNotifyOnCompletion),j=T(D=>D.notifyOnError),u=T(D=>D.setNotifyOnError),P=T(D=>D.notifyOnQuestion),A=T(D=>D.setNotifyOnQuestion),F=T(D=>D.notificationTemplates),H=T(D=>D.setNotificationTemplates),[_,W]=s.useState("default"),[Q,M]=s.useState(!1),[C,b]=s.useState(!1),[S,k]=s.useState(!1);s.useEffect(()=>{if(!i){M(!1),b(!1);return}typeof Notification<"u"&&W(Notification.permission);const D=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;M(D),(async()=>{if(!D){b(!1);return}try{const ce=await navigator.serviceWorker.getRegistration();if(!ce){b(!1);return}const ie=await ce.pushManager.getSubscription();b(!!ie)}catch{b(!1)}})()},[i]);const l=async D=>{if(t){c(D);return}if(!i){c(D);return}if(D&&typeof Notification<"u"&&Notification.permission==="default")try{const q=await Notification.requestPermission();W(q),q==="granted"?c(!0):R.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(q){console.error("Failed to request notification permission:",q),R.error("Failed to request notification permission")}else c(!!(D&&_==="granted"))},y=t||r||i&&typeof Notification<"u"&&Notification.permission==="granted",U=(D,q,ce)=>{H(ie=>({...ie,[D]:{...ie[D],[q]:ce}}))},K=D=>{const q="=".repeat((4-D.length%4)%4),ce=(D+q).replace(/-/g,"+").replace(/_/g,"/"),ie=atob(ce),I=new Uint8Array(ie.length);for(let fe=0;fe<ie.length;fe+=1)I[fe]=ie.charCodeAt(fe);return I},G=async(D,q,ce)=>{let ie=null;const I=new Promise((fe,Se)=>{ie=setTimeout(()=>{Se(new Error(ce))},q)});try{return await Promise.race([D,I])}finally{ie&&clearTimeout(ie)}},ae=async D=>{if(D.active)return;const q=D.installing||D.waiting;q&&q.state!=="activated"&&await G(new Promise(ce=>{const ie=()=>{q.state==="activated"&&(q.removeEventListener("statechange",ie),ce())};q.addEventListener("statechange",ie),ie()}),15e3,"Service worker activation timed out")},ge=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const D=[{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 q=null;for(const ce of D)try{const ie=ce.opts?navigator.serviceWorker.register("/sw.js",ce.opts):navigator.serviceWorker.register("/sw.js");return await G(ie,1e4,`Service worker registration timed out (${ce.label})`)}catch(ie){q=ie}throw q instanceof Error?q:new Error("Service worker registration failed")},le=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const D=await navigator.serviceWorker.getRegistration();if(D)return D;const q=await ge();try{await q.update()}catch{}return await ae(q),q},re=D=>{const q=D,ce=[`type=${typeof D}`,`toString=${String(D)}`,`name=${String(q?.name??"")}`,`message=${String(q?.message??"")}`];let ie="";try{ie=JSON.stringify(D)}catch{}return{summary:ce.filter(Boolean).join(" | "),json:ie,stack:typeof q?.stack=="string"?q.stack:""}},de=async()=>{const D=ha();if(!D?.notifications){R.error("Notifications API not available");return}try{await D.notifications.notifyAgentCompletion({title:"Test Notification",body:"This is a test notification from PiChamber.",tag:"pichamber-test"})?R.success("Test notification sent successfully"):R.error("Failed to send test notification")}catch(q){console.error("Test notification failed:",q),R.error("Failed to send test notification")}},we=async()=>{if(!Q){R.error("Push notifications not supported");return}const D=ha();if(!D?.push){R.error("Push API not available");return}k(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const ye=await Notification.requestPermission();if(W(ye),ye!=="granted"){R.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){R.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const q=await D.push.getVapidPublicKey();if(!q?.publicKey){R.error("Failed to load push key");return}const ce=await le();await ae(ce);const ie=await ce.pushManager.getSubscription();if(!("pushManager"in ce)||!ce.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const fe=(ie??await G(ce.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:K(q.publicKey)}),15e3,"Push subscription timed out")).toJSON(),Se=fe.keys;if(!fe.endpoint||!Se?.p256dh||!Se.auth)throw new Error("Push subscription missing keys");if(!(await G(D.push.subscribe({endpoint:fe.endpoint,keys:{p256dh:Se.p256dh,auth:Se.auth},origin:typeof window<"u"?window.location.origin:void 0,platform:Zi()}),15e3,"Push subscribe request timed out"))?.ok){R.error("Failed to enable background notifications");return}b(!0),R.success("Background notifications enabled")}catch(q){console.error("[Push] Enable failed:",q);const ce=re(q);R.error("Failed to enable background notifications",{description:ce.summary})}finally{k(!1)}},ke=async()=>{if(!Q){b(!1);return}const D=ha();if(!D?.push){R.error("Push API not available");return}k(!0);try{const ce=await(await le()).pushManager.getSubscription();if(!ce){b(!1);return}const ie=ce.endpoint;await ce.unsubscribe(),await D.push.unsubscribe({endpoint:ie}),b(!1),R.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:Et,children:[e.jsx(ve,{checked:o&&y,onChange:D=>{l(D)},label:"Enable Notifications",info:i?"Your browser may ask for permission the first time.":void 0,ariaLabel:"Enable notifications"}),o&&y&&!r&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{checked:w==="always",onChange:D=>v(D?"always":"hidden-only"),label:"Notify While App is Focused",ariaLabel:"Notify while app is focused"}),e.jsx("div",{className:"py-2",children:e.jsx(h,{type:"button",variant:"outline",size:"sm",onClick:()=>{de()},children:"Send test notification"})})]})]}),i&&e.jsxs("div",{className:"mt-1",children:[_==="denied"&&e.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:"Notification permission denied. Enable it in your browser settings."}),_==="granted"&&!o&&e.jsx("p",{className:"typography-meta text-muted-foreground/70 mt-1",children:"Permission granted, but notifications are disabled."})]})]}),o&&y&&e.jsxs(e.Fragment,{children:[e.jsx(te,{settingsItem:"notifications.events",title:"Notification Events",children:e.jsxs("div",{className:Et,children:[e.jsx(ve,{checked:L,onChange:p,label:"Agent Completion",ariaLabel:"Agent completion"}),e.jsx(ve,{checked:x,onChange:g,label:"Subagent Completion",ariaLabel:"Subagent completion"}),e.jsx(ve,{checked:j,onChange:u,label:"Agent Errors",ariaLabel:"Agent errors"}),e.jsx(ve,{checked:P,onChange:A,label:"Agent Questions",ariaLabel:"Agent questions"})]})}),!r&&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(ms,{className:"gap-2 md:grid-cols-2 md:gap-3 lg:gap-3",children:["completion","subtask","error","question"].map(D=>e.jsxs("section",{className:"p-2",children:[e.jsx(_a,{className:"capitalize",children:Kl[D]}),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(ne,{value:F[D].title,onChange:q=>U(D,"title",q.target.value),className:"h-7",placeholder:xr[D].titleKey})]}),e.jsxs("div",{children:[e.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:"Message"}),e.jsx(ne,{value:F[D].message,onChange:q=>U(D,"message",q.target.value),className:"h-7",placeholder:xr[D].messageKey})]})]})]},D))})})]}),i&&e.jsx(te,{settingsItem:"notifications.push",title:"Background Push Notifications",children:e.jsx(ve,{checked:Q?C:!1,disabled:!Q||S,onChange:D=>{D?we():ke()},label:"Enable push notifications",description:Q?void 0:"Push not supported. Desktop Chrome/Edge and Android support push. iOS requires an installed PWA.",info:Q?"Receive alerts via your operating system background service":void 0,ariaLabel:"Enable push notifications",labelAccessory:S?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})})]})},Ia=[{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}],Ea=[{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}],Gl="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",ql="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",mn=[{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."}],Ql=[".yml",".yaml",".json"],Yl="Config file must use .yml, .yaml, or .json extension.",da=t=>{const r=t.trim().toLowerCase();return Ql.some(i=>r.endsWith(i))},Jl=()=>"cloudflared",si=()=>{if(typeof window<"u"&&typeof window.__PICHAMBER_PLATFORM__=="string"){const r=window.__PICHAMBER_PLATFORM__;if(r==="win32"||r==="darwin"||r==="linux")return r}const t=typeof navigator<"u"?`${navigator.platform||""} ${navigator.userAgent||""}`.toLowerCase():"";return t.includes("win")?"win32":t.includes("mac")?"darwin":"linux"},Xl=(t=si())=>t==="win32"?"winget install --id Cloudflare.cloudflared":t==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",pn=(t,r)=>{const i=typeof r?.provider=="string"&&r.provider.trim().length>0?r.provider.trim().toLowerCase():t,o=typeof r?.dependency=="string"&&r.dependency.trim().length>0?r.dependency.trim():Jl(),c=typeof r?.platform=="string"&&r.platform.trim().length>0?r.platform.trim():si(),w=typeof r?.installCommand=="string"&&r.installCommand.trim().length>0?r.installCommand.trim():Xl(c);return{provider:i,dependency:o,installCommand:w}},Zl=t=>t==="cloudflare"?"Cloudflare":t,ec=({provider:t})=>{const r=Zl(t),i=t==="cloudflare";return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(f,{name:"cloud",className:J("size-4 shrink-0",i?"text-[var(--status-warning)]":"text-muted-foreground")}),e.jsx("span",{children:r})]})},ks=t=>t==="quick"?"quick":t==="managed-remote"?"managed-remote":t==="managed-local"?"managed-local":"quick",jn=(t,r,i)=>t.find(c=>c.ms===r)?.value||i,br=(t,r,i)=>{const o=jn(t,r,i);return t.find(c=>c.value===o)?.label||o},vr=t=>{const r=Math.max(0,t),i=Math.floor(r/1e3),o=Math.floor(i/3600),c=Math.floor(i%3600/60),w=i%60;return o>0?`${o}h ${c}m`:c>0?`${c}m ${w}s`:`${w}s`},tc=(t,r)=>Ti(t,r,{hour:"2-digit",precision:"second"}),Ma=t=>{const r=t.trim();if(!r)return"";try{return(r.includes("://")?new URL(r):new URL(`https://${r}`)).hostname.trim().toLowerCase()}catch{return r.toLowerCase()}},sc=t=>{if(!Array.isArray(t))return[];const r=new Set,i=new Set,o=[];for(const c of t){if(!c||typeof c!="object")continue;const w=c,v=typeof w.id=="string"?w.id.trim():"",x=typeof w.name=="string"?w.name.trim():"",g=Ma(typeof w.hostname=="string"?w.hostname:"");!v||!x||!g||r.has(v)||i.has(g)||(r.add(v),i.add(g),o.push({id:v,name:x,hostname:g}))}return o},ac=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,nc=()=>{const t=T(d=>d.timeFormatPreference),[r,i]=s.useState("checking"),[o,c]=s.useState(null),[w,v]=s.useState(null),[x,g]=s.useState(null),[L,p]=s.useState(null),[j,u]=s.useState(null),[P,A]=s.useState(!1),[F,H]=s.useState(!1),[_,W]=s.useState(!1),[Q,M]=s.useState("cloudflare"),[C,b]=s.useState(()=>pn("cloudflare")),[S,k]=s.useState([]),[l,y]=s.useState("quick"),[U,K]=s.useState(null),[G,ae]=s.useState([]),[ge,le]=s.useState({}),[re,de]=s.useState(""),[we,ke]=s.useState({}),[D,q]=s.useState(new Set),[ce,ie]=s.useState(!1),[I,fe]=s.useState(""),[Se,V]=s.useState(""),[ye,Te]=s.useState(""),[ue,Fe]=s.useState(1800*1e3),[Ve,kt]=s.useState(480*60*1e3),[Re,rt]=s.useState(""),[Lt,gt]=s.useState([]),[N,me]=s.useState(()=>Date.now()),[z,ee]=s.useState(null),xe=Yl,Ue=s.useRef(null),He=s.useMemo(()=>U?!da(U):!1,[U]),O=s.useMemo(()=>G.find(d=>d.id===re)||G[0]||null,[G,re]),X=s.useMemo(()=>Lt.map(d=>{const B=d.expiresAt<=N,se=d.status==="active"&&!B,Z=se?vr(d.expiresAt-N):d.inactiveReason==="expired"||B?"expired":"inactive",je=Z==="expired"?"Expired":d.inactiveReason==="tunnel-revoked"?"Revoked":"Inactive",Ne=ks(d.mode);return{...d,isActive:se,mode:Ne,remainingTextForSession:Z,inactiveLabel:je}}),[N,Lt]),pe=s.useMemo(()=>o?.connectUrl?o.bootstrapExpiresAt===null?!0:o.bootstrapExpiresAt>N:!1,[N,o?.bootstrapExpiresAt,o?.connectUrl]),Ee=s.useMemo(()=>!o||r!=="active"&&r!=="stopping"?!1:w===l,[w,r,o,l]),Ce=s.useMemo(()=>!o||r!=="active"||!w?!1:w!==l,[w,r,o,l]),$e=s.useMemo(()=>{if(typeof z=="number"&&Number.isFinite(z)&&z>0)return z;if(typeof window>"u")return null;const B=qs()||window.location.href;let se=0;try{se=Number(new URL(B).port)}catch{se=Number(window.location.port)}return Number.isFinite(se)&&se>0?se:null},[z]),De=s.useMemo(()=>S.find(d=>d.provider===Q)??null,[S,Q]),Oe=s.useMemo(()=>{const d=new Set(De?.modes?.map(B=>B.key).filter(B=>B==="quick"||B==="managed-remote"||B==="managed-local"));return d.size===0?mn:mn.filter(B=>d.has(B.value))},[De]),nt=s.useMemo(()=>Oe.some(d=>d.value==="managed-remote"||d.value==="managed-local"),[Oe]),dt=s.useMemo(()=>C.provider===Q?C:pn(Q),[C,Q]),ut=s.useCallback(async d=>{await Nn(d)},[]),mt=s.useCallback((d,B)=>(b(pn(B,d)),d.available===!0),[]),pt=s.useCallback(async d=>{try{const[B,se,Z,je]=await Promise.all([ht("/api/pichamber/tunnel/check",{signal:d}),ht("/api/pichamber/tunnel/status",{signal:d}),ht("/api/pi/ui-settings",{signal:d,headers:{Accept:"application/json"}}),ht("/api/pichamber/tunnel/providers",{signal:d})]),Ne=await B.json(),oe=await se.json(),_e=Z.ok?await Z.json():{},Wt=je.ok?await je.json():{},Gt=oe.ttlConfig?.bootstrapTtlMs??(_e?.tunnelBootstrapTtlMs===null?null:typeof _e?.tunnelBootstrapTtlMs=="number"?_e.tunnelBootstrapTtlMs:1800*1e3),Es=typeof oe.ttlConfig?.sessionTtlMs=="number"?oe.ttlConfig.sessionTtlMs:typeof _e?.tunnelSessionTtlMs=="number"?_e.tunnelSessionTtlMs:480*60*1e3,As=ks(oe.mode??_e?.tunnelMode),vs="cloudflare",qt=typeof _e?.managedLocalTunnelConfigPath=="string"&&_e.managedLocalTunnelConfigPath.trim()||null,ys=mt(Ne,vs),Qt=sc(oe?.managedRemoteTunnelPresets),Yt=typeof oe.managedRemoteTunnelHostname=="string"?oe.managedRemoteTunnelHostname:"",ot=Qt.length>0?Qt:Yt?[{id:`legacy-${Ma(Yt)}`,name:Yt,hostname:Ma(Yt)}]:[],Qs=ot[0]?.id||"";if(Fe(Gt),kt(Es),M(vs),k(Array.isArray(Wt?.providers)?Wt.providers:[]),y(As),K(qt),ae(ot),de(Qs),gt(Array.isArray(oe.activeSessions)?oe.activeSessions:[]),v(oe.activeTunnelMode?ks(oe.activeTunnelMode):oe.active&&oe.mode?ks(oe.mode):null),q(new Set(Array.isArray(oe.managedRemoteTunnelTokenPresetIds)?oe.managedRemoteTunnelTokenPresetIds:[])),ee(typeof oe.localPort=="number"?oe.localPort:null),oe.active&&oe.url){c({url:oe.url,connectUrl:null,bootstrapExpiresAt:typeof oe.bootstrapExpiresAt=="number"?oe.bootstrapExpiresAt:null}),i("active");return}i(ys?"idle":"not-available")}catch{d.aborted||(i("error"),p("Failed to check tunnel availability"))}},[mt]);s.useEffect(()=>{const d=new AbortController;return pt(d.signal),()=>d.abort()},[pt]),s.useEffect(()=>{if(!o?.connectUrl){g(null);return}let d=!1;return Vr.toDataURL(o.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(B=>{d||g(B)}).catch(()=>{d||g(null)}),()=>{d=!0}},[o?.connectUrl]),s.useEffect(()=>{if(!o?.bootstrapExpiresAt){rt("No expiry");return}let d=null,B=Date.now();const se=()=>{const Ne=o.bootstrapExpiresAt?o.bootstrapExpiresAt-Date.now():0;Ne<=0?rt("Expired"):rt(vr(Ne))},Z=()=>{const Ne=Date.now();Ne-B>=1e3&&(se(),B=Ne),d=requestAnimationFrame(Z)};se(),(typeof document>"u"||document.visibilityState==="visible")&&(d=requestAnimationFrame(Z));const je=()=>{document.visibilityState==="visible"&&d===null?d=requestAnimationFrame(Z):document.visibilityState!=="visible"&&d!==null&&(cancelAnimationFrame(d),d=null)};return document.addEventListener("visibilitychange",je),()=>{document.removeEventListener("visibilitychange",je),d!==null&&cancelAnimationFrame(d)}},[o?.bootstrapExpiresAt]),s.useEffect(()=>{let d=null,B=Date.now();const se=()=>{const je=Date.now();je-B>=1e3&&(me(je),B=je),d=requestAnimationFrame(se)};(typeof document>"u"||document.visibilityState==="visible")&&(d=requestAnimationFrame(se));const Z=()=>{document.visibilityState==="visible"&&d===null?d=requestAnimationFrame(se):document.visibilityState!=="visible"&&d!==null&&(cancelAnimationFrame(d),d=null)};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z),d!==null&&cancelAnimationFrame(d)}},[]),s.useEffect(()=>{if(r==="starting"||r==="stopping"||r==="checking")return;let d=!1;const B=async()=>{try{const Z=await ht("/api/pichamber/tunnel/status");if(!Z.ok||d)return;const je=await Z.json();if(d)return;gt(Array.isArray(je.activeSessions)?je.activeSessions:[]),q(new Set(Array.isArray(je.managedRemoteTunnelTokenPresetIds)?je.managedRemoteTunnelTokenPresetIds:[])),ee(typeof je.localPort=="number"?je.localPort:null)}catch{}},se=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||B()},5e3);return()=>{d=!0,window.clearInterval(se)}},[r]);const ze=s.useCallback(async d=>{W(!0);try{await Ie(d),Object.prototype.hasOwnProperty.call(d,"tunnelMode")&&d.tunnelMode&&y(d.tunnelMode),Object.prototype.hasOwnProperty.call(d,"tunnelProvider")&&typeof d.tunnelProvider=="string"&&M(d.tunnelProvider),Object.prototype.hasOwnProperty.call(d,"managedLocalTunnelConfigPath")&&K(d.managedLocalTunnelConfigPath??null),Object.prototype.hasOwnProperty.call(d,"managedRemoteTunnelPresets")&&d.managedRemoteTunnelPresets&&ae(d.managedRemoteTunnelPresets)}catch{R.error("Failed to save tunnel settings")}finally{W(!1)}},[]),zt=s.useCallback(async(d,B)=>{H(!0);try{await Ie({tunnelBootstrapTtlMs:d,tunnelSessionTtlMs:B})}catch{R.error("Failed to save tunnel TTL settings")}finally{H(!1)}},[]),Vt=s.useCallback(async d=>{const B=d.token.trim();if(B)try{const se={...we,[d.presetId]:B};await Ie({managedRemoteTunnelPresetTokens:se}),q(Z=>{const je=new Set(Z);return je.add(d.presetId),je})}catch{R.error("Failed to save managed remote tunnel token")}},[we]),hs=s.useCallback(async()=>{const d=await eo({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(d.success&&typeof d.path=="string"&&d.path.trim().length>0){const B=d.path.trim();if(!da(B)){R.error(xe);return}K(B),await ze({managedLocalTunnelConfigPath:B});return}Ue.current?.click()},[xe,ze]),gs=s.useCallback(d=>{const B=d.trim();K(B.length>0?B:null)},[]),fs=s.useCallback(async()=>{if(U&&!da(U)){R.error(xe);return}await ze({managedLocalTunnelConfigPath:U})},[xe,U,ze]),xs=s.useCallback(async()=>{K(null),await ze({managedLocalTunnelConfigPath:null})},[ze]),es=s.useCallback(async d=>{const B=d.target.files?.[0];if(!B)return;const se=B.name.trim();if(se.length!==0){if(!da(se)){R.error(xe);return}K(se),await ze({managedLocalTunnelConfigPath:se}),d.target.value=""}},[xe,ze]),it=s.useCallback(async()=>{if(p(null),u(null),l==="managed-local"&&U&&!da(U)){p(xe),R.error(xe);return}i("starting");try{let d="",B="";if(l==="managed-remote"){if(!O){i("idle"),u("Select or add a managed remote tunnel first"),R.error("Select or add a managed remote tunnel first");return}d=O.hostname,B=(we[O.id]||"").trim(),await ze({tunnelMode:"managed-remote",managedRemoteTunnelPresets:G})}const se=await ht("/api/pichamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:Q,mode:l,...l==="managed-remote"&&O?{managedRemoteTunnelPresetId:O.id,managedRemoteTunnelPresetName:O.name}:{},...l==="managed-remote"&&d?{managedRemoteTunnelHostname:d}:{},...l==="managed-remote"&&B?{managedRemoteTunnelToken:B}:{},...l==="managed-local"&&U?{configPath:U}:{}})}),Z=await se.json();if(!se.ok||!Z.ok){if(l==="managed-remote"&&typeof Z.error=="string"&&Z.error.includes("Managed remote tunnel token is required")){i("idle"),u("Managed remote tunnel token is required before starting"),R.error("Add a managed remote tunnel token before starting");return}i("error"),p(Z.error||"Failed to start tunnel"),R.error(Z.error||"Failed to start tunnel");return}const je=typeof Z.url=="string"?Z.url:"";if(!je){i("error"),p("Tunnel started but no public URL was returned"),R.error("Tunnel started but no public URL was returned");return}if(c({url:je,connectUrl:typeof Z.connectUrl=="string"?Z.connectUrl:null,bootstrapExpiresAt:typeof Z.bootstrapExpiresAt=="number"?Z.bootstrapExpiresAt:null}),v(Z.activeTunnelMode?ks(Z.activeTunnelMode):Z.mode?ks(Z.mode):l),gt(Array.isArray(Z.activeSessions)?Z.activeSessions:[]),Array.isArray(Z.managedRemoteTunnelTokenPresetIds)&&q(new Set(Z.managedRemoteTunnelTokenPresetIds)),typeof Z.localPort=="number"&&ee(Z.localPort),typeof Z.mode=="string"&&y(ks(Z.mode)),i("active"),Z.replacedTunnel){const Ne=typeof Z.revokedBootstrapCount=="number"?Z.revokedBootstrapCount:0,oe=typeof Z.invalidatedSessionCount=="number"?Z.invalidatedSessionCount:0;Ne===1&&oe===1?R.warning("Replaced previous tunnel: revoked 1 link, invalidated 1 session."):Ne===1?R.warning(`Replaced previous tunnel: revoked 1 link, invalidated ${oe} sessions.`):oe===1?R.warning(`Replaced previous tunnel: revoked ${Ne} links, invalidated 1 session.`):R.warning(`Replaced previous tunnel: revoked ${Ne} links, invalidated ${oe} sessions.`)}else R.success("Tunnel link ready")}catch{i("error"),p("Failed to start tunnel"),R.error("Failed to start tunnel")}},[xe,G,ze,O,we,Q,l,U]),Ps=s.useCallback(async()=>{i("stopping");try{await ht("/api/pichamber/tunnel/stop",{method:"POST"});const d=await ht("/api/pichamber/tunnel/status");if(d.ok){const B=await d.json();gt(Array.isArray(B.activeSessions)?B.activeSessions:[]),q(new Set(Array.isArray(B.managedRemoteTunnelTokenPresetIds)?B.managedRemoteTunnelTokenPresetIds:[])),ee(typeof B.localPort=="number"?B.localPort:null)}c(null),v(null),g(null),i("idle"),R.success("Tunnel stopped")}catch{i("error"),p("Failed to stop tunnel"),R.error("Failed to stop tunnel")}},[]),ts=s.useCallback(async()=>{if(o?.connectUrl)try{await navigator.clipboard.writeText(o.connectUrl),A(!0),R.success("Connect link copied"),setTimeout(()=>A(!1),2e3)}catch{R.error("Failed to copy URL")}},[o?.connectUrl]),bs=s.useCallback(async d=>{const B=Ia.find(se=>se.value===d);B&&(Fe(B.ms),await zt(B.ms,Ve))},[zt,Ve]),Ts=s.useCallback(async d=>{const B=Ea.find(se=>se.value===d);!B||B.ms===null||(kt(B.ms),await zt(ue,B.ms))},[ue,zt]),Is=s.useCallback(async d=>{u(null),p(null),r!=="active"&&r!=="stopping"&&r!=="starting"&&i("idle"),await ze({tunnelMode:d,managedRemoteTunnelPresets:G})},[G,ze,r]),os=s.useCallback(async(d,B)=>{try{await Ie({managedRemoteTunnelPresets:B})}catch{R.error("Failed to save selected managed remote tunnel")}},[]),ls=s.useCallback(d=>{const B=G.find(se=>se.id===d);B&&(de(B.id),u(null),os(B,G))},[G,os]),$t=s.useCallback(async()=>{const d=I.trim(),B=Ma(Se),se=ye.trim();if(!d){R.error("Tunnel name is required");return}if(!B){R.error("Managed remote tunnel hostname is required");return}if(!se){R.error("Managed remote tunnel token is required");return}if(G.some(Ne=>Ne.hostname===B)){R.error("This hostname already exists");return}const Z={id:ac(),name:d,hostname:B},je=[...G,Z];ae(je),de(Z.id),le(Ne=>({...Ne,[Z.id]:!0})),ke(Ne=>({...Ne,[Z.id]:se})),u(null),ie(!1),fe(""),V(""),Te(""),await ze({tunnelMode:"managed-remote",managedRemoteTunnelPresets:je,managedRemoteTunnelPresetTokens:{...we,[Z.id]:se}}),await Vt({presetId:Z.id,presetName:Z.name,hostname:Z.hostname,token:se}),R.success("Managed remote tunnel saved")},[G,Se,I,ye,Vt,ze,we]),ft=s.useCallback(async d=>{const B=G.find(oe=>oe.id===d);if(!B)return;const se=G.filter(oe=>oe.id!==B.id),Z=se[0]?.id||"",je=re===B.id?Z:re,Ne=Object.fromEntries(Object.entries(we).filter(([oe,_e])=>oe!==B.id&&_e.trim().length>0));ae(se),de(je),le(oe=>{const _e={...oe};return delete _e[B.id],_e}),ke(oe=>{const _e={...oe};return delete _e[B.id],_e}),q(oe=>{const _e=new Set(oe);return _e.delete(B.id),_e}),u(null),await ze({managedRemoteTunnelPresets:se,managedRemoteTunnelPresetTokens:Ne}),R.success("Managed remote tunnel removed")},[G,ze,re,we]),Kt="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 r==="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:[X.length>0&&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(f,{name:"information",className:"size-4 text-[var(--status-info)]"}),e.jsx("p",{className:Yn,children:"Redeemed access links"})]}),e.jsx("div",{className:"space-y-1",children:X.map(d=>{const B=d.mode==="quick",se=d.mode==="managed-remote",Z=B?"border-[var(--status-warning-border)] bg-[var(--status-warning-background)] text-[var(--status-warning)]":se?"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)]",je=d.isActive?B?"text-[var(--status-warning)]":se?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",Ne=B?"QUICK":se?"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(f,{name:"checkbox-blank-circle-fill",className:J("size-2.5 shrink-0",je)}),e.jsx("span",{className:J("typography-micro rounded border px-1.5 py-0.5 uppercase",Z),children:Ne}),e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:`Redeemed ${tc(d.createdAt,t)}`}),e.jsx("span",{className:"typography-meta text-foreground",children:d.isActive?`Expires in ${d.remainingTextForSession}`:d.inactiveLabel==="Inactive"?"Inactive":`Inactive (${d.inactiveLabel})`})]},d.sessionId)})})]})}),r==="not-available"&&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(f,{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:Yn,children:`${dt.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:dt.installCommand})]})]})}),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:st,children:"Provider"}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-foreground",children:e.jsx(ec,{provider:"cloudflare"})})]}),e.jsxs("div",{"data-settings-item":"tunnel.type",className:"space-y-1.5",children:[e.jsx("p",{className:st,children:"Tunnel type"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1",children:Oe.map(d=>e.jsxs(Rr,{children:[e.jsx(Dr,{asChild:!0,children:e.jsx(h,{variant:"chip",size:"xs","aria-pressed":l===d.value,className:"!font-normal",onClick:()=>{Is(d.value)},disabled:_||r==="starting"||r==="stopping",children:d.label})}),e.jsx(Pi,{sideOffset:8,className:"max-w-xs",children:d.tooltip})]},d.value))})]})]}),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(st,"shrink-0"),children:"Connect link TTL"}),e.jsxs(Qe,{value:jn(Ia,ue,"1800000"),onValueChange:d=>{bs(d)},disabled:F||_||r==="starting"||r==="stopping",children:[e.jsx(Ye,{size:tt,className:"max-w-[11rem] min-w-0",children:e.jsx(Je,{className:"truncate",children:br(Ia,ue,"1800000")})}),e.jsx(Xe,{children:Ia.map(d=>e.jsx(Me,{value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:J(st,"shrink-0"),children:"Tunnel session TTL"}),e.jsxs(Qe,{value:jn(Ea,Ve,"28800000"),onValueChange:d=>{Ts(d)},disabled:F||_||r==="starting"||r==="stopping",children:[e.jsx(Ye,{size:tt,className:"max-w-[11rem] min-w-0",children:e.jsx(Je,{className:"truncate",children:br(Ea,Ve,"28800000")})}),e.jsx(Xe,{children:Ea.map(d=>e.jsx(Me,{value:d.value,children:d.label},d.value))})]})]})]}),l==="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(f,{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."}),nt&&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."})]})]})}),l==="managed-remote"&&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 $e=="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:",$e]})]})}),e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[e.jsx(_a,{children:"Saved managed remote tunnels"}),e.jsxs(h,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>ie(d=>!d),disabled:r==="starting"||r==="stopping"||_,children:[e.jsx(f,{name:"add",className:"h-3.5 w-3.5"}),"Create"]})]}),G.length>0?e.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:G.map((d,B)=>{const se=we[d.id]||"",Z=D.has(d.id),je=ge[d.id]??!1;return e.jsx("div",{className:J(B<G.length-1&&"border-b border-[var(--surface-subtle)]"),children:e.jsxs($r,{open:je,onOpenChange:Ne=>{le(oe=>({...oe,[d.id]:Ne})),Ne&&ls(d.id)},className:"py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3",children:[e.jsxs(Kr,{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:r==="starting"||r==="stopping"||_,children:[je?e.jsx(f,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):e.jsx(f,{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:d.name})]}),e.jsx(h,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":`Remove ${d.name}`,onClick:()=>{ft(d.id)},disabled:r==="starting"||r==="stopping"||_,children:e.jsx(f,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsx(Wr,{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:d.hostname})]}),e.jsx(ne,{type:"password",value:se,onChange:Ne=>{const oe=Ne.target.value;u(null),ke(_e=>({..._e,[d.id]:oe}))},onBlur:Ne=>{const oe=Ne.currentTarget.value.trim();oe&&Vt({presetId:d.id,presetName:d.name,hostname:d.hostname,token:oe})},placeholder:Z?"Saved token available (optional to replace)":"Paste token for this tunnel",className:"h-7",disabled:r==="starting"||r==="stopping"}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(h,{variant:"ghost",size:"xs",className:"!font-normal",disabled:r==="starting"||r==="stopping"||se.trim().length===0,onClick:()=>{Vt({presetId:d.id,presetName:d.name,hostname:d.hostname,token:se})},children:"Save token"})})]})})]})},d.id)})}):e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"No managed remote tunnels saved yet."}),ce&&e.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[e.jsx(ne,{value:I,onChange:d=>fe(d.target.value),placeholder:"Tunnel name (e.g. Production)",className:"h-7",disabled:_||r==="starting"||r==="stopping"}),e.jsx(ne,{value:Se,onChange:d=>V(d.target.value),placeholder:"Hostname (e.g. oc.example.com)",className:"h-7",disabled:_||r==="starting"||r==="stopping"}),e.jsx(ne,{type:"password",value:ye,onChange:d=>Te(d.target.value),placeholder:"Token",className:"h-7",disabled:_||r==="starting"||r==="stopping"}),typeof $e=="number"&&e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["For Cloudflare connector target, use"," ",e.jsxs("code",{children:["http://localhost:",$e]}),"."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(h,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{$t()},disabled:_||r==="starting"||r==="stopping",children:"Save Changes"}),e.jsx(h,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{ie(!1),fe(""),V(""),Te("")},disabled:_||r==="starting"||r==="stopping",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(Xt,{children:"Tokens are saved in ~/.config/pichamber/cloudflare-managed-remote-tunnels.json."})]}),!O&&j&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:j})]}),l==="managed-local"&&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:st,children:"Configuration file"}),e.jsx("input",{ref:Ue,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:d=>{es(d)}}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{value:U||"",onChange:d=>{gs(d.target.value)},onBlur:()=>{fs()},placeholder:"Using default cloudflared config",className:"h-7",disabled:r==="starting"||r==="stopping"||_}),e.jsx(h,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":"Browse config file",onClick:()=>{hs()},disabled:r==="starting"||r==="stopping"||_,children:e.jsx(f,{name:"folder",className:"size-3.5"})}),U&&e.jsx(h,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":"Clear config file",onClick:()=>{xs()},disabled:r==="starting"||r==="stopping"||_,children:e.jsx(f,{name:"close",className:"size-3.5"})})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:U?"Custom config file will be used when starting the tunnel.":"When empty, cloudflared uses its default config (~/.cloudflared/config.yml)."}),He&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:xe})]})}),!Ee&&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(f,{name:"information",className:"mt-0.5 size-4 shrink-0 text-[var(--status-info)]"}),e.jsxs("div",{className:"space-y-1",children:[l==="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:()=>{ut(Gl)},children:["Check documentation on how to configure a managed remote tunnel",e.jsx(f,{name:"external-link",className:"size-3.5"})]})]}),l==="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:()=>{ut(ql)},children:["Check documentation on managed local tunnel configuration",e.jsx(f,{name:"external-link",className:"size-3.5"})]})]}),e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:`Start a ${mn.find(d=>d.value===l)?.label??"Quick"} tunnel and generate a one-time connect link. Do not close the app while this tunnel is in use.`})]})]})}),l==="managed-remote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:st,children:"Managed remote tunnel to connect"}),e.jsxs(Qe,{value:re||(G[0]?.id??""),onValueChange:d=>{ls(d)},disabled:_||r==="starting"||r==="stopping"||G.length<=1,children:[e.jsx(Ye,{size:tt,children:e.jsx(Je,{placeholder:"Select saved tunnel",children:O?.name})}),e.jsx(Xe,{fitContent:!0,children:G.map(d=>e.jsx(Me,{value:d.id,children:d.name},d.id))})]})]}),Ce&&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(f,{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(h,{size:"sm",variant:"outline",onClick:it,disabled:r==="starting"||_||l==="managed-remote"&&!O||l==="managed-local"&&He,className:J(Kt,r==="starting"&&"opacity-70"),children:r==="starting"?e.jsxs(e.Fragment,{children:[e.jsx(f,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Starting tunnel..."]}):"Start Tunnel"})]})]}),Ee&&o&&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:o.url})]}),pe&&o.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:o.connectUrl}),e.jsxs(h,{size:"sm",variant:"ghost",onClick:ts,className:"shrink-0 gap-1.5",children:[P?e.jsx(f,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):e.jsx(f,{name:"file-copy",className:"size-3.5"}),P?"Copied":"Copy all"]})]}),e.jsxs("p",{className:"typography-meta mt-1 text-muted-foreground/70",children:["Expires",": ",o.bootstrapExpiresAt?Re:"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:[x?e.jsx("img",{src:x,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(h,{size:"sm",variant:"outline",onClick:it,disabled:r==="stopping"||_||l==="managed-local"&&He,className:Kt,children:[e.jsx(f,{name:"restart",className:"size-3.5"}),"New connect link"]}),e.jsx(h,{size:"sm",variant:"ghost",onClick:Ps,disabled:r==="stopping"||_,className:"gap-2 text-[var(--status-error)]",children:r==="stopping"?e.jsxs(e.Fragment,{children:[e.jsx(f,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Stopping..."]}):"Stop Tunnel"})]})})]}),r==="error"&&L&&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:L}),e.jsx(h,{size:"sm",variant:"ghost",onClick:it,children:"Retry"})]})]})})},ai=()=>{const t=at()&&fa(),r=t&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[i,o]=he.useState(!1),[c,w]=he.useState(!1),[v,x]=he.useState(""),[g,L]=he.useState(""),[p,j]=he.useState(!1),[u,P]=he.useState(!1),[A,F]=he.useState(null),[H,_]=he.useState(!0),[W,Q]=he.useState(!1),[M,C]=he.useState(!1),[b,S]=he.useState(!1),[k,l]=he.useState(!1),[y,U]=he.useState(!1),[K,G]=he.useState(!1),[ae,ge]=he.useState(!1),[le,re]=he.useState(!0),[de,we]=he.useState(!0),[ke,D]=he.useState(!1),[q,ce]=he.useState(!1),[ie,I]=he.useState(!1),[fe,Se]=he.useState(null),[V,ye]=he.useState(null);he.useEffect(()=>{if(!t){_(!1);return}let z=!1;return(async()=>{try{const ee=await ht("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!ee.ok)throw new Error("Failed to load desktop settings");const xe=await ee.json().catch(()=>null);if(z)return;const Ue=xe?.desktopLanAccessEnabled===!0,He=typeof xe?.desktopUiPassword=="string"?xe.desktopUiPassword:"";o(Ue),w(Ue),x(He),L(He),P(xe?.desktopLanAccessActive===!0),F(typeof xe?.desktopLanAccessBlockedReason=="string"?xe.desktopLanAccessBlockedReason:null);const O=xe?.desktopMacMenuBarEnabled!==!1;re(O),we(O),Se(null)}catch(ee){z||Se(ee instanceof Error?ee.message:"Failed to load desktop settings")}finally{z||_(!1)}})(),()=>{z=!0}},[t]),he.useEffect(()=>{if(!t){C(!1);return}let z=!1;return(async()=>{const ee=await to();z||(C(ee?.supported===!0),S(ee?.enabled===!0))})(),()=>{z=!0}},[t]),he.useEffect(()=>{if(!t){U(!1);return}let z=!1;return(async()=>{const ee=await so();z||(U(ee?.supported===!0),G(ee?.enabled===!0))})(),()=>{z=!0}},[t]),he.useEffect(()=>{if(!t){D(!1);return}let z=!1;return(async()=>{const ee=await ao();z||(D(ee?.supported===!0),ce(ee?.enabled===!0))})(),()=>{z=!0}},[t]),he.useEffect(()=>{if(!t||!c){ye(null);return}let z=!1;return(async()=>{const ee=await Or();z||ye(ee)})(),()=>{z=!0}},[c,t]);const Te=c!==i||g!==v||de!==le,ue=he.useMemo(()=>{if(typeof window>"u")return null;const ee=qs()||window.location.href;let xe=0;try{xe=Number(new URL(ee).port)}catch{xe=Number(window.location.port)}return Number.isFinite(xe)&&xe>0?xe:null},[]),Fe=c&&u&&V&&ue?`http://${V}:${ue}`:null,Ve=c&&!g.trim(),kt=i&&!u&&A==="missing-password",Re=H||W||!Te||Ve,rt=he.useCallback(z=>{L(z),z.trim()||w(!1)},[]),Lt=he.useCallback(async()=>{if(!M||k)return;const z=!b;S(z),l(!0),Se(null);try{const ee=await no(z);if(!ee?.supported)throw new Error("Launch at login is not supported on this system");S(ee.enabled)}catch(ee){S(!z),Se(ee instanceof Error?ee.message:"Failed to update launch at login setting")}finally{l(!1)}},[k,b,M]),gt=he.useCallback(async()=>{if(!y||ae)return;const z=!K;G(z),ge(!0),Se(null);try{const ee=await ro(z);if(!ee)throw new Error("Failed to update system tray setting");if(!ee.supported)throw new Error("System tray background mode is not supported on this system");G(ee.enabled)}catch(ee){G(!z),Se(ee instanceof Error?ee.message:"Failed to update system tray setting")}finally{ge(!1)}},[ae,K,y]),N=he.useCallback(async()=>{if(!ke||ie)return;const z=!q;ce(z),I(!0),Se(null);try{const ee=await io(z);if(!ee?.supported)throw new Error("Preventing sleep is not supported on this system");ce(ee.enabled)}catch(ee){ce(!z),Se(ee instanceof Error?ee.message:"Failed to update keep awake setting")}finally{I(!1)}},[ie,q,ke]),me=he.useCallback(async()=>{if(Te){Q(!0),Se(null);try{if(!(await ht("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:c,desktopUiPassword:g,desktopMacMenuBarEnabled:de})})).ok)throw new Error("Failed to save desktop settings");if(o(c),x(g),re(de),!await oo())throw new Error("Saved, but failed to restart app")}catch(z){Se(z instanceof Error?z.message:"Failed to save desktop settings"),Q(!1)}}},[de,g,c,Te]);return t?e.jsx(te,{title:"Desktop Network Access",children:e.jsxs("div",{className:"space-y-3",children:[M||r||y||ke?e.jsxs("div",{className:Et,children:[M?e.jsx(ve,{settingsItem:"sessions.desktop-launch-at-login",checked:b,onChange:z=>{z!==b&&Lt()},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,r?e.jsx(ve,{settingsItem:"sessions.desktop-mac-menu-bar",checked:de,onChange:we,disabled:H||W,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,y?e.jsx(ve,{settingsItem:"sessions.desktop-minimize-to-tray",checked:K,onChange:z=>{z!==K&&gt()},disabled:ae,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,ke?e.jsx(ve,{settingsItem:"sessions.desktop-keep-awake",checked:q,onChange:z=>{z!==q&&N()},disabled:ie,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(qe,{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(ne,{id:"desktop-ui-password",type:p?"text":"password",className:"h-8 min-w-0 flex-1",value:g,onChange:z=>rt(z.target.value),placeholder:"No password required",disabled:H||W,required:c,"aria-invalid":Ve}),e.jsx(h,{type:"button",variant:"ghost",size:"xs",onClick:()=>j(z=>!z),className:yt,"aria-label":p?"Hide password":"Show password","aria-pressed":p,children:e.jsx(f,{name:p?"eye-off":"eye",className:"h-4 w-4"})})]}),e.jsx("div",{className:Et,children:e.jsx(ve,{settingsItem:"sessions.desktop-lan-access",checked:c,onChange:w,disabled:H||W,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."}),Ve||kt?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"})}),fe?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:fe}):null,Fe?e.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[Te&&!i?"After restart, open from another device: ":"Open from another device: ",e.jsx("span",{className:"font-mono text-foreground",children:Fe})]}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(h,{type:"button",size:"xs",onClick:me,disabled:Re,className:"shrink-0 !font-normal",children:W?"Saving...":"Save + Restart"})})]})}):null},ni=new Set(["shift","control","alt","meta"]),rc=t=>{if(ni.has(t.key.toLowerCase()))return null;const r=[];(t.metaKey||t.ctrlKey)&&r.push("mod"),t.shiftKey&&r.push("shift"),t.altKey&&r.push("alt");const i=_r(t.key);return i?(r.push(i),ns(r.join("+"))):null},ic=t=>{const r=[];if((t.metaKey||t.ctrlKey)&&r.push("mod"),t.shiftKey&&r.push("shift"),t.altKey&&r.push("alt"),ni.has(t.key.toLowerCase()))return r.length>0?ns(r.join("+")):null;const i=_r(t.key);return i?(r.push(i),r.length>0?ns(r.join("+")):null):null},oc={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"},lc=()=>{const t=T(C=>C.shortcutOverrides),r=T(C=>C.setShortcutOverride),i=T(C=>C.clearShortcutOverride),o=T(C=>C.resetAllShortcutOverrides),c=s.useMemo(()=>Ii(),[]),w=s.useCallback((C,b)=>oc[C]??b,[]),[v,x]=s.useState(null),[g,L]=s.useState({}),[p,j]=s.useState(""),[u,P]=s.useState(""),[A,F]=s.useState(null),H=s.useCallback(C=>{Ie({shortcutOverrides:C})},[]),_=s.useCallback((C,b)=>{const S=ns(b);for(const k of c){if(k.id===C)continue;const l=Dn(k.id,t);if(ns(l)===S)return k.id}return null},[c,t]),W=s.useCallback((C,b)=>{const S=ns(b),k=_(C,S);if(k){F({actionId:C,combo:S,conflictActionId:k}),j("");return}const l={...t,[C]:S};r(C,S),H(l),F(null),j(""),P(_n(S)?"This shortcut can conflict with browser defaults. It is still saved.":""),L(y=>{const U={...y};return delete U[C],U})},[_,H,r,t]),Q=s.useCallback(()=>{if(!A)return;const C={...t,[A.conflictActionId]:an,[A.actionId]:A.combo};r(A.conflictActionId,an),r(A.actionId,A.combo),H(C),F(null),j(""),P(_n(A.combo)?"This shortcut can conflict with browser defaults. It is still saved.":""),L(b=>{const S={...b};return delete S[A.actionId],S})},[A,H,r,t]),M=s.useCallback(C=>{const b={...t};delete b[C],i(C),H(b),L(S=>{const k={...S};return delete k[C],k}),F(null),j(""),P("")},[i,H,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(h,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{o(),H({}),L({}),F(null),j(""),P("")},children:"Reset All"}),children:[(p||u||A)&&e.jsxs("div",{className:"mb-2 space-y-2",children:[A&&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(h,{type:"button",size:"xs",className:"!font-normal",onClick:Q,children:"Overwrite"}),e.jsx(h,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>F(null),children:"Cancel"})]})]}),p&&e.jsx("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3 typography-meta text-foreground",children:p}),u&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 typography-meta text-foreground",children:u})]}),e.jsx("div",{children:c.map((C,b)=>{const S=C.id==="switch_context_surface",k=S?Ei(C.id,t):Dn(C.id,t),l=g[C.id],y=l??k,U=typeof l=="string"&&ns(l)!==ns(k),K=y===""||ns(y)===an,G=v===C.id?"Press keys...":S&&!K?`${On(y)} + 1…0`:On(y);return e.jsx("div",{className:J("py-1.5",b>0&&"border-t border-border/40"),children:e.jsxs(ct,{label:w(C.id,C.label),alignEnd:!1,children:[e.jsx(ne,{readOnly:!0,value:G,onFocus:()=>{x(C.id),j("")},onBlur:()=>{v===C.id&&x(null)},onKeyDown:ae=>{if(ae.preventDefault(),ae.stopPropagation(),ae.key==="Escape"){x(null);return}const ge=S?ic(ae):rc(ae);ge&&(L(le=>({...le,[C.id]:ge})),x(null),F(null),j(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),e.jsx(h,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const ae=g[C.id];if(!ae){j("Capture a shortcut first.");return}W(C.id,ae)},disabled:!U,children:"Save Changes"}),e.jsx(h,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>M(C.id),children:"Reset"})]})},C.id)})})]})},ri=()=>{const[t,r]=s.useState(0);return s.useEffect(()=>Cn(()=>r(i=>i+1)),[]),t},cc=({section:t})=>{const{isMobile:r}=Mt();ri();const i=r&&ps(),o=at()&&fa();if(!t)return e.jsxs(Be,{className:"pichamber-page-body space-y-3 sm:space-y-6",children:[e.jsx(Fa,{}),e.jsx(ti,{}),o&&e.jsx(ai,{}),e.jsx(Zr,{}),ps()&&!at()&&!zr()&&e.jsx(ei,{}),i&&e.jsx(Qr,{})]});const c=()=>{switch(t){case"general":return e.jsx(uc,{});case"visual":return e.jsx(mc,{});case"chat":return e.jsx(pc,{});case"sessions":return e.jsx(hc,{});case"shortcuts":return e.jsx(dc,{});case"git":return e.jsx(gc,{});case"github":return e.jsx(fc,{});case"notifications":return e.jsx(xc,{});case"tunnel":return e.jsx(bc,{});default:return null}},w={general:"General",visual:"Appearance",chat:"Chat",sessions:"Sessions",shortcuts:"Shortcuts",git:"Git",github:"Git",notifications:"Notifications",tunnel:"External Tunnel"}[t],v={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(Be,{title:r?void 0:w,description:r?void 0:v,className:"pichamber-page-body",children:c()})},dc=()=>e.jsx(lc,{}),uc=()=>{ri();const t=at()&&fa(),r=ps()&&!at()&&!zr();return e.jsxs(e.Fragment,{children:[t&&e.jsx(ai,{}),r&&e.jsx(ei,{}),e.jsx(Fa,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar","terminalQuickKeys","terminalShell","terminalLoginShell","perfHud"]})]})},mc=()=>e.jsx(Fa,{visibleSettings:["theme","windowControlsPosition","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat","weekStart","fontSize","terminalFontSize","editorFontSize","spacing","inputBarOffset"]}),pc=()=>e.jsx(Fa,{visibleSettings:["userMessageRendering","mermaidRendering","reasoning","showToolFileIcons","showTurnChangedFiles","expandedTools","collapsibleUserMessages","stickyUserHeader","promptNavigatorEnabled","wideChatLayout","codeBlockLineWrap","splitAssistantMessageActions","subagentReadOnlyBanner","diffLayout","dotfiles","fileViewerPreview","followUpBehavior","persistDraft","inputSpellcheck"]}),hc=()=>e.jsxs(e.Fragment,{children:[e.jsx(ti,{}),e.jsx(Zr,{})]}),gc=()=>e.jsx(En,{}),fc=()=>e.jsx(En,{}),xc=()=>e.jsx(Wl,{}),bc=()=>e.jsx(nc,{}),vc=[{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:"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.subagent-read-only-banner",page:"chat",title:"Allow Prompting Subagent Sessions",keywords:["subagent","read only","prompt","banner"]},{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:"sessions.opencode-binary",page:"general",title:"OpenCode CLI binary path",keywords:["opencode","cli","binary","path"]},{id:"sessions.opencode-update-notifications",page:"general",title:"Show update notifications",keywords:["opencode","cli","updates"],isAvailable:t=>!t.isWindowsArm64},{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","prompt","template"]},{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:"magic-prompts.visible-prompt",page:"magic-prompts",title:"Visible Prompt",keywords:["prompt text","user message","template"]},{id:"magic-prompts.instructions",page:"magic-prompts",title:"Instructions",keywords:["hidden prompt","instructions","template"]},{id:"magic-prompts.reset-overrides",page:"magic-prompts",title:"Reset All Overrides",keywords:["reset","default prompts","overrides"]},{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:"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 yr(t){return t.trim().toLocaleLowerCase()}function yc({query:t,runtimeCtx:r,visiblePageSlugs:i,getPageTitle:o}){const c=yr(t);if(!c)return[];const w=i?new Set(i):null,v=c.split(/\s+/).filter(Boolean);return vc.flatMap(x=>{if(w&&!w.has(x.page))return[];const g=ma(x.page);if(!g||g.isAvailable&&!g.isAvailable(r)||x.isAvailable&&!x.isAvailable(r))return[];const L=x.title,p=x.description??null,j=yr([L,p,o(x.page),...x.keywords??[]].filter(Boolean).join(" "));return v.every(u=>j.includes(u))?[{...x,title:L,description:p,pageTitle:o(x.page)}]:[]})}const wr=256,jr=280,ii="__pichamberSettingsDetail",wc=["general","appearance","chat","notifications","sessions","shortcuts","about","projects","remote-instances","tunnel","git","providers","behavior","magic-prompts","snippets","skills.installed"],jc=["general","projects","agent"];function kc(t,r){return{isWeb:!t&&ps(),isDesktop:t,isMobile:r}}function kr(t,r){return t.isAvailable?t.isAvailable(r):!0}function kn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nc(t,r){const i=new Set(r);let o=t,c=1;for(;i.has(o);)o=`${t}-${c}`,c+=1;return o}function Sc(t){if(!kn(t))return null;const r=t[ii];if(!kn(r))return null;const i=r.page,o=r.stage;return typeof i!="string"||o!=="page-content"?null:{page:Hr(i),stage:o}}function Cc(){return typeof window>"u"||!kn(window.history.state)?{}:window.history.state}const Pc=({onClose:t,forceMobile:r,isWindowed:i,visiblePageSlugs:o,initialMobileStage:c="nav"})=>{const w=Mt(),v=r??w.isMobile,x=Ai(),[g,L]=s.useState(null),p=T(O=>O.settingsPage),j=T(O=>O.isSettingsDialogOpen),u=T(O=>O.setSettingsPage),P=Hr(p),[A,F]=s.useState(c),H=s.useRef(c==="nav"?P:null);s.useEffect(()=>{!v&&P==="home"&&u("general")},[v,u,P]);const[_,W]=s.useState(""),[Q,M]=s.useState(!1),C=s.useRef(null),[b,S]=s.useState(null),[k,l]=s.useState(0),y=s.useRef(null),U=s.useRef([]),K=s.useRef(0),G=s.useRef(!1),ae=s.useMemo(()=>at(),[]),ge=s.useMemo(()=>at()&&fa(),[]),le=s.useMemo(()=>at()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),re=s.useMemo(()=>at()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="win32",[]),de=s.useMemo(()=>at()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="linux",[]),we=s.useMemo(()=>lo(),[]),ke=s.useMemo(()=>kc(ae,v),[ae,v]),D=s.useMemo(()=>{const O=o?new Set(o):null;return vo.filter(X=>X.slug!=="home").filter(X=>!O||O.has(X.slug)).filter(X=>kr(X,ke)).filter(X=>!(v&&X.slug==="remote-instances"))},[v,ke,o]),q=s.useMemo(()=>{const O=new Map(wc.map((X,pe)=>[X,pe]));return D.slice().sort((X,pe)=>(O.get(X.slug)??999)-(O.get(pe.slug)??999))},[D]),ce=La(O=>O.activeProjectId);s.useEffect(()=>{!j&&!i||(P==="skills.installed"&&Ns.getState().loadSkills(),P==="snippets"&&Ot.getState().loadSnippets())},[ce,j,i,P]);const ie=s.useCallback(O=>{if(u(O),H.current=O,!v)return;const X=ma(O);if(!X||X.slug==="home"){F("nav");return}F(X.kind==="split"?"page-sidebar":"page-content")},[v,u]),I=s.useMemo(()=>ma(P),[P]),fe=s.useMemo(()=>({general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",tunnel:"tunnel"}),[]),Se=s.useCallback(O=>{switch(O){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"shortcuts":return"Shortcuts";case"sessions":return"Sessions";case"magic-prompts":return"PiChamber Utility Prompts";case"snippets":return"Snippets";case"notifications":return"Notifications";case"tunnel":return"External Tunnel";case"about":return"About";default:return"Settings"}},[]),V=s.useMemo(()=>yc({query:_,runtimeCtx:{...ke,isDesktopLocalOrigin:ge,isMac:le,isWindows:re,isLinux:de,isWindowsArm64:we},visiblePageSlugs:o,getPageTitle:Se}),[Se,we,ge,le,re,de,ke,_,o]),ye=s.useCallback(O=>{if(O.id.startsWith("snippets.")){const X=Ot.getState(),pe=Nc("new-snippet",X.snippets.map(Ee=>Ee.name));return X.setSnippetDraft({name:pe,scope:"global"}),X.setSelectedSnippet(pe),O.id==="snippets.create"?"snippets.content":O.id}return O.id==="providers.connect"&&yn.getState().setSelectedProviderId(null),O.id},[]),Te=s.useMemo(()=>{const O=[],X=new Map;for(const pe of V){let Ee=X.get(pe.page);Ee||(Ee={page:pe.page,pageTitle:pe.pageTitle,results:[]},X.set(pe.page,Ee),O.push(Ee)),Ee.results.push(pe)}return O},[V]);s.useEffect(()=>{l(0),K.current=0,G.current=!1},[_]),s.useEffect(()=>{K.current=k},[k]),s.useEffect(()=>{U.current[k]?.scrollIntoView({block:"nearest"})},[k]),s.useEffect(()=>{k>=V.length&&l(Math.max(0,V.length-1)),U.current.length=V.length},[k,V.length]);const ue=s.useCallback(O=>{const X=ye(O);S(X),ie(O.page),v&&F("page-content")},[v,ie,ye]),Fe=s.useCallback(O=>{if(O.key==="Escape"){if(O.preventDefault(),_.trim()){W("");return}v&&Q&&M(!1);return}if(_.trim()&&V.length!==0){if(O.key==="ArrowDown"){O.preventDefault(),G.current=!0,l(X=>(X+1)%V.length);return}if(O.key==="ArrowUp"){O.preventDefault(),G.current=!0,l(X=>(X-1+V.length)%V.length);return}if(O.key==="Enter"){O.preventDefault();const X=(K.current%V.length+V.length)%V.length,pe=V[X]??V[0];pe&&ue(pe)}}},[v,Q,ue,_,V]);s.useEffect(()=>{const O=b;if(!O)return;let X=!1;const pe=window.requestAnimationFrame(()=>{if(X)return;const Ee=typeof CSS<"u"&&CSS.escape?CSS.escape(O):O.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),Ce=y.current?.querySelector(`[data-settings-item="${Ee}"]`);Ce&&(S(null),Ce.scrollIntoView({block:"center",behavior:"smooth"}),Ce.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{Ce.removeAttribute("data-settings-search-highlight")},1600))});return()=>{X=!0,window.cancelAnimationFrame(pe)}},[b,P]);const Ve=s.useCallback(()=>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:yo,children:"Not available"}),e.jsx("p",{className:"typography-ui text-muted-foreground mt-1",children:"This settings page is not available in this runtime."})]})}),[]),kt=s.useCallback((O,X)=>{switch(O){case"projects":return e.jsx(Lo,{onItemSelect:X.onItemSelect});case"magic-prompts":return e.jsx(hl,{onItemSelect:X.onItemSelect});default:return null}},[]),Re=s.useCallback(O=>{const X=ma(O);if(X&&!kr(X,ke))return Ve();switch(O){case"projects":return e.jsx(Ro,{});case"remote-instances":return e.jsx(Qo,{});case"behavior":return e.jsx(Po,{});case"skills.installed":return e.jsx(Eo,{});case"providers":return e.jsx(ul,{});case"about":return e.jsx(Be,{title:v?void 0:"About",children:e.jsx(Qr,{})});case"magic-prompts":return e.jsx(gl,{});case"snippets":return e.jsx(bl,{});case"git":return e.jsx(kl,{});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"tunnel":{const pe=fe[O]??"visual";return e.jsx(cc,{section:pe})}default:return null}},[v,fe,Ve,ke]);s.useEffect(()=>{if(!v||A!=="nav"||P==="home"||H.current===P)return;const O=ma(P);!O||O.slug==="home"||(H.current=P,F(O.kind==="split"?"page-sidebar":"page-content"))},[v,A,P]);const rt=v&&A!=="nav",Lt=A==="page-content"&&I?.kind==="split"&&!0,gt=rt?"Back to Settings":"Close settings",N=Mi();s.useCallback(O=>{if(typeof window>"u")return;const X=Sc(window.history.state);X?.page===O&&X.stage==="page-content"||window.history.pushState({...Cc(),[ii]:{page:O,stage:"page-content"}},"",window.location.href)},[]);const me=s.useCallback(()=>{F("page-content")},[]),z=s.useCallback(()=>{F("nav")},[]),ee=s.useCallback(()=>{F("page-sidebar")},[]);s.useEffect(()=>{(!v||A!=="nav")&&M(!1)},[v,A]),s.useEffect(()=>{Q&&window.setTimeout(()=>C.current?.focus(),0)},[Q]),s.useEffect(()=>{const O=async()=>{try{const{loadMobileConnections:Ee,isActiveRuntimeConnection:Ce}=await pa(async()=>{const{loadMobileConnections:Oe,isActiveRuntimeConnection:nt}=await import("./renderMobileApp-KS_pt-qc.js").then(dt=>dt.m);return{loadMobileConnections:Oe,isActiveRuntimeConnection:nt}},__vite__mapDeps([79,3,4,80,81,1,2,5,82,0,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,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124])),De=(await Ee().catch(()=>[])).find(Oe=>Ce(Oe));if(De){L(De.label);return}}catch{}if(x?.instanceLabel){L(x.instanceLabel);return}try{const{desktopHostsGet:Ee}=await pa(async()=>{const{desktopHostsGet:mt}=await import("./index-BAqpUCjs.js").then(pt=>pt.c2);return{desktopHostsGet:mt}},__vite__mapDeps([1,2,3,4,5])),{buildLocalDesktopHost:Ce,getLocalDesktopOrigin:$e,resolveCurrentDesktopHost:De}=await pa(async()=>{const{buildLocalDesktopHost:mt,getLocalDesktopOrigin:pt,resolveCurrentDesktopHost:ze}=await import("./SessionSwitcherDropdown-DROjbyIu.js").then(zt=>zt.e$);return{buildLocalDesktopHost:mt,getLocalDesktopOrigin:pt,resolveCurrentDesktopHost:ze}},__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])),Oe=await Ee().catch(()=>({hosts:[]})),dt=[Ce($e()),...Oe.hosts],ut=De(dt);if(ut&&ut.label&&ut.label!=="Instance"){L(ut.label);return}}catch{}const X=qs(),pe=Zt();if(pe==="local"){L("Local");return}if(pe.startsWith("relay:")){const Ee=pe.split(":")[1]?.split("@")[0];L(Ee?`Relay ${Ee.slice(0,8)}`:"Private relay");return}if(pe.startsWith("host:")){L(pe.replace("host:",""));return}if(X)try{const Ee=new URL(X);L(Ee.host);return}catch{L(X);return}L(null)};return O(),Cn(()=>{O()})},[x?.instanceLabel]);const xe=()=>{const O=_.trim().length>0,X=v?Q&&O:O;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[v?X?null:e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>{if(x?.openInstances){x.openInstances();return}ie("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",g?"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:g?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:g}),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(f,{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(f,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{value:_,onChange:pe=>W(pe.target.value),onKeyDown:Fe,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"}),O&&e.jsx("button",{type:"button",onClick:()=>W(""),"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(f,{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:X?V.length>0?(()=>{let pe=0;return Te.map(Ee=>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:Ee.pageTitle}),Ee.results.map(Ce=>{const $e=pe;pe+=1;const De=$e===k,Oe=!!Ce.description;return e.jsxs("button",{type:"button",ref:nt=>{U.current[$e]=nt},onMouseMove:()=>{G.current=!1,l($e)},onClick:()=>ue(Ce),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",Oe?"min-h-11 py-1.5":"py-2",De?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ce.title}),Oe&&e.jsx("span",{className:"typography-micro text-muted-foreground/70 line-clamp-2",children:Ce.description})]},Ce.id)})]},Ee.page))})():e.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:"No matching settings"}):(()=>{const pe=new Map;for(const Ce of q){const $e=Ce.group,De=pe.get($e);De?De.push(Ce):pe.set($e,[Ce])}return jc.map(Ce=>({group:Ce,pages:pe.get(Ce)??[]})).filter(Ce=>Ce.pages.length>0).map(({group:Ce,pages:$e},De)=>e.jsxs("div",{className:"space-y-0.5",children:[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",De===0?"pt-1":"pt-4 sm:pt-3"),children:Ce==="general"?"PiChamber":Ce==="projects"?"Workspace":"Agent"}),$e.map(Oe=>{const nt=P===Oe.slug&&!(v&&A==="nav"),dt=wo(Oe.slug);return dt?e.jsx(Rr,{children:e.jsx(Dr,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>ie(Oe.slug),"aria-current":nt?"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",nt?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[e.jsx(f,{name:dt,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:Se(Oe.slug)}),Oe.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"})]})]})})},Oe.slug):null})]},Ce))})()})})]})},Ue=()=>{if(A==="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(us,{children:xe()})})});if(!I)return e.jsx("div",{className:"flex-1 bg-background"});if(A==="page-sidebar"){if(I.kind!=="split"){const X=Re(P);return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(us,{children:X})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(us,{children:kt(P,{onItemSelect:me})})})}const O=Re(P);return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(us,{children:O})})},He=()=>!I||P==="home"?null:I.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:jr,minWidth:jr,borderColor:"var(--interactive-border)"},children:e.jsx(us,{children:kt(P,{})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(us,{children:Re(P)})})]}):e.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(us,{children:Re(P)})});return e.jsxs("div",{ref:y,"data-settings-view":"true",className:J("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),children:[v?e.jsxs("div",{className:J("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",A!=="nav"&&"border-b","bg-background"),style:A!=="nav"?{borderColor:"var(--interactive-border)"}:void 0,children:[rt?e.jsx("button",{type:"button",onClick:z,"aria-label":gt,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(f,{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:A==="nav"?"Settings":I?Se(I.slug):"Settings"}),Lt&&e.jsx("button",{type:"button",onClick:ee,"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(f,{name:"list-unordered",className:"h-5 w-5"})}),v&&A==="nav"?e.jsx("button",{type:"button",onClick:()=>{const O=!Q;M(O),O?window.setTimeout(()=>C.current?.focus(),0):W("")},"aria-label":Q?"Close search":"Search settings","aria-expanded":Q,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(f,{name:Q?"close":"search",className:"h-5 w-5"})}):null,t&&e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",title:`Close Settings (${N}+,)`,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(f,{name:"close",className:"h-5 w-5"})})]}):e.jsx(e.Fragment,{children:rt&&e.jsx("div",{className:J("absolute left-3 z-50",i?"top-2":"top-3"),children:e.jsx("button",{type:"button",onClick:z,"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(f,{name:"arrow-left-s",className:"h-5 w-5"})})})}),v&&A==="nav"&&Q?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(f,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{ref:C,value:_,onChange:O=>W(O.target.value),onKeyDown:Fe,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"}),_.trim().length>0?e.jsx("button",{type:"button",onClick:()=>W(""),"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(f,{name:"close",className:"h-3.5 w-3.5"})}):null]})}):null,e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:v?Ue():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:`${wr}px`,minWidth:`${wr}px`,borderColor:"var(--interactive-border)"},children:e.jsx(us,{children:xe()})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:He()})]})})]})},zc=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:Pc},Symbol.toStringTag,{value:"Module"}));export{Qr as A,Pc as S,zc as a};