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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/assets/{AgentsSurface-BmHImX8m.js → AgentsSurface-wsW9VCRp.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-EwCf4Yxu.js} +1 -1
  3. package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-BX6N99cQ.js} +1 -1
  4. package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CI0eSnPP.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-GLj2W7VE.js} +1 -1
  6. package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-CI0tfZQL.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-B85tZ9m7.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-Y6AuNiGl.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-BJHBud6i.js} +1 -1
  10. package/dist/assets/{GitView-MIDG5RYW.js → GitView-DueE69kW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-Cg-xkdIu.js} +3 -3
  12. package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-Cvg6lc40.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-DExPx-QM.js} +1 -1
  14. package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-_c3HZ34I.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-CZnaqO-_.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-C9AYPiwo.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DOpnN-8S.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CmHMPZ69.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-CZCQ4t1J.js} +1 -1
  20. package/dist/assets/SettingsView-D5PO5M3z.js +11 -0
  21. package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-DXV5UOE8.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-CO1ZiI1x.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-GOwNLj-y.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-BoaiZji6.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-Chq1X8nw.js} +1 -1
  26. package/dist/assets/VisualFrame-u7aRcX7O.js +22 -0
  27. package/dist/assets/VisualsArtifact-D9vPjihW.js +1 -0
  28. package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-BjpDEohv.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DmPCxbok.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-CukNcUeY.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CDyfNPYO.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-uI7Y7L5k.js} +1 -1
  33. package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-B9Mxac4R.js} +1 -1
  34. package/dist/assets/{index-DMX9wT1Z.js → index-BWq2ibCw.js} +1 -1
  35. package/dist/assets/index-BxKPJ9uG.js +11 -0
  36. package/dist/assets/index-C5JgjS20.css +1 -0
  37. package/dist/assets/{main-BirYxac2.js → main-CWfC-9xT.js} +4 -4
  38. package/dist/assets/{main-BW9J3Y72.js → main-ckQ0ciIN.js} +2 -2
  39. package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-p2q2Kxwo.js} +1 -1
  40. package/dist/assets/{miniChat-BRB11eEs.js → miniChat-x2TrwRYA.js} +2 -2
  41. package/dist/assets/{mobile-DJZYYCuB.js → mobile-B0x2G8h1.js} +2 -2
  42. package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-D542OJlG.js} +1 -1
  43. package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Q_RZUCnt.js} +1 -1
  44. package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-CSFGSknx.js} +1 -1
  45. package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CFIdesZT.js} +2 -2
  46. package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-C5JE0mRX.js} +1 -1
  47. package/dist/assets/renderMobileApp-B1ybjcGM.js +11 -0
  48. package/dist/assets/runtimeEndpointReset-DyZSKCYM.js +66 -0
  49. package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-BR_dhe7_.js} +1 -1
  50. package/dist/assets/{selection-BTEdLRVK.js → selection-CfOpW4rA.js} +1 -1
  51. package/dist/assets/useAppFontEffects-COMvkffC.js +226 -0
  52. package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-M1AE2YuX.js} +1 -1
  53. package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-D0i2BYYP.js} +1 -1
  54. package/dist/assets/{web-components-C_DsTJis.js → web-components-wOQkOurQ.js} +1 -1
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +3 -3
  57. package/dist/mobile.html +3 -3
  58. package/package.json +1 -1
  59. package/plugins/featured.json +12 -0
  60. package/plugins/subagents/package.json +1 -1
  61. package/plugins/visuals/extension.js +8 -5
  62. package/plugins/visuals/package.json +1 -1
  63. package/server/index.js +90 -27
  64. package/server/lib/git/DOCUMENTATION.md +4 -0
  65. package/server/lib/git/service.js +70 -5
  66. package/server/lib/git/service.test.js +179 -0
  67. package/server/lib/github/DOCUMENTATION.md +2 -0
  68. package/server/lib/marketplace/DOCUMENTATION.md +95 -0
  69. package/server/lib/marketplace/featured.js +176 -0
  70. package/server/lib/marketplace/featured.test.js +207 -0
  71. package/server/lib/marketplace/npm-registry.js +255 -0
  72. package/server/lib/marketplace/npm-registry.test.js +227 -0
  73. package/server/lib/marketplace/routes.js +64 -0
  74. package/server/lib/marketplace/routes.test.js +119 -0
  75. package/server/lib/marketplace/service.js +225 -0
  76. package/server/lib/marketplace/service.test.js +174 -0
  77. package/server/lib/notifications/DOCUMENTATION.md +10 -4
  78. package/server/lib/notifications/pi-notification-watcher.js +92 -33
  79. package/server/lib/notifications/pi-notification-watcher.test.js +79 -0
  80. package/server/lib/open-url/DOCUMENTATION.md +1 -0
  81. package/server/lib/pi/merged-event-stream.js +316 -0
  82. package/server/lib/pi/merged-event-stream.test.js +95 -0
  83. package/server/lib/pi/routes-daemon-pool.test.js +348 -0
  84. package/server/lib/pi/routes-merged-events.test.js +327 -0
  85. package/server/lib/pi/routes-sandbox.test.js +1684 -0
  86. package/server/lib/pi/routes.js +491 -90
  87. package/server/lib/pi/routes.test.js +87 -2
  88. package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
  89. package/server/lib/pi/sandbox/launcher.js +122 -0
  90. package/server/lib/pi/sandbox/launcher.test.js +91 -0
  91. package/server/lib/pi/sandbox/nono-launcher.js +455 -0
  92. package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
  93. package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
  94. package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
  95. package/server/lib/pi/sandbox/nono-profile.json +22 -0
  96. package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
  97. package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
  98. package/server/lib/pi/sandbox/project-sandbox.js +207 -0
  99. package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
  100. package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
  101. package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
  102. package/server/lib/pi/sandbox/trust-ask.js +135 -0
  103. package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
  104. package/server/lib/pi/sandbox/worktree-ids.js +96 -0
  105. package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
  106. package/server/lib/pi/session-daemon/DOCUMENTATION.md +26 -6
  107. package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
  108. package/server/lib/pi/session-daemon/daemon-process.js +10 -1
  109. package/server/lib/pi/session-daemon/extension-config.js +206 -23
  110. package/server/lib/pi/session-daemon/extension-config.test.js +180 -0
  111. package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
  112. package/server/lib/pi/session-daemon/session-daemon.js +368 -56
  113. package/server/lib/pi/session-daemon/session-daemon.test.js +227 -0
  114. package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
  115. package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
  116. package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
  117. package/server/lib/pi/session-daemon/session-lease.js +93 -15
  118. package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
  119. package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
  120. package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
  121. package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
  122. package/server/lib/pi/session-daemon/supervisor.js +386 -35
  123. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  124. package/server/lib/pi/ui-settings-store.js +90 -3
  125. package/server/lib/pi/ui-settings-store.test.js +118 -0
  126. package/server/lib/plugins/DOCUMENTATION.md +17 -5
  127. package/server/lib/plugins/daemon-sync.js +16 -6
  128. package/server/lib/plugins/daemon-sync.test.js +12 -0
  129. package/server/lib/plugins/impact.test.js +2 -1
  130. package/server/lib/plugins/manifest.js +25 -0
  131. package/server/lib/plugins/manifest.test.js +9 -0
  132. package/server/lib/plugins/routes.test.js +28 -0
  133. package/server/lib/plugins/service.js +24 -2
  134. package/server/lib/server/cross-process-lock.js +28 -3
  135. package/server/lib/wallpaper/DOCUMENTATION.md +25 -0
  136. package/server/lib/wallpaper/routes.js +63 -0
  137. package/server/lib/wallpaper/routes.test.js +109 -0
  138. package/server/lib/wallpaper/store.js +87 -0
  139. package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
  140. package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
  141. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
  142. package/dist/assets/index-B2v0_mez.js +0 -11
  143. package/dist/assets/index-D3F4JrPN.css +0 -1
  144. package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
  145. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
  146. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
@@ -0,0 +1,11 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-boot-D-KEJjsM.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/nativeFileSave-D542OJlG.js","assets/index-BxKPJ9uG.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-C5JgjS20.css","assets/useAppFontEffects-COMvkffC.js","assets/runtimeSurface-BR_dhe7_.js"])))=>i.map(i=>d[i]);
2
+ import{C as Uo,b1 as Vr,j as e,bh as Fo}from"./vendor-boot-D-KEJjsM.js";import{R as l,a as D}from"./vendor-react-Bz1tRBxM.js";import{ac as ln,e as Re,ad as Rs,b as qe,I as xt,J as wa,H as Gr,ae as Bo,af as ms,ag as qr,r as Ae,ah as $o,ai as Wo,c as U,s as yn,aj as Ie,f as Oe,B as ts,ak as Ko,al as Ho,am as Qr,an as Vo,ao as Go,ap as qo,aq as Jr,ar as Qo,o as Jo,p as _e,as as Te,k as Yo,at as Xo,u as V,au as Zo,av as Yr,aw as el,ax as tl,ay as sl,a6 as Ht,az as nl,aA as al,W as rl,aB as il,l as ja,aC as ol,aD as Xr,aE as Ha,aF as Va,aG as Ga,aH as qa,aI as ll,aJ as Qa,aK as cl,aL as dl,aM as Ja,aN as ul,aO as pl,aP as ml,aQ as Xs,aR as hl,aS as fl,aT as gl,aU as xl,aV as vl,aW as bl,aX as yl,aY as wl,aZ as jl,a_ as kl,a$ as ht,w as Ya,b0 as Xa,b1 as Kn,a3 as Nl,a7 as Za,b2 as ka,b3 as er,b4 as Cl,b5 as Sl,U as Pl}from"./index-BxKPJ9uG.js";import{d7 as Tl,d8 as tr,d9 as Il,bX as Zr,B as S,I as M,bY as ei,af as ds,bv as Be,bw as $e,bx as We,da as cn,by as Ke,bz as ke,bV as Ds,db as El,dc as Al,t as B,m as bt,n as yt,o as wt,p as jt,q as kt,U as ys,dd as wn,de as qt,df as jn,dg as Qt,aj as Ll,ag as Na,ai as lt,dh as Wt,f as ee,di as la,_ as _s,dj as Ml,aZ as Ca,dk as Rl,dl as Dl,g as ti,d5 as si,cA as _l,dm as De,dn as Ol,dp as zl,dq as Ul,dr as is,ds as sr,dt as Fl,a as dn,bS as Bl,du as $l,dv as Wl,dw as Kl,dx as Hn,dy as nr,dz as Hl,dA as Vl,dB as Gl,dC as ql,cK as Ql,a2 as Ks,j as kn,dD as Jl,dE as ni,cb as Yl,bW as Xl,dF as Zl,bZ as ai,dG as ec,dH as tc,an as sc,dI as ri,dJ as ii,dK as oi,dL as li,dM as un,ak as He,dN as pn,dO as ot,dP as dt,dQ as nc,dR as ac,dS as rc,dT as ic,dU as oc,dV as lc,dW as cc,dX as dc,dY as uc,dZ as pc,$ as ci,d_ as mc,d$ as hc,e0 as fc,e1 as gc,ap as di,aq as ui,ar as xc,e2 as vc,e3 as bc,e4 as yc,aE as Mt}from"./useAppFontEffects-COMvkffC.js";import{aN as Ge,aO as hs,aP as wc,aQ as q,aR as Ee,aS as Le,aT as jc,aU as ca,aV as Hs,T as Sa,aW as Je,aX as St,aY as ft,aZ as Os,a_ as at,a$ as he,b0 as rt,b1 as Ve,b2 as Tt,b3 as _t,b4 as fs,b5 as pi,b6 as kc,b7 as vt,b8 as ve,b9 as Nn,ba as gt,bb as Jt,bc as Me,bd as Nc,be as tt,bf as Cc,bg as mi,bh as gs,bi as xs,bj as us,A as Vn,bk as hi,bl as Es,bm as ar,bn as Rt,bo as Dt,bp as Sc,bq as Gn,br as fi,bs as As,bt as Pc,aM as Tc,bu as Ic,aL as Ec}from"./runtimeEndpointReset-DyZSKCYM.js";import{_ as Yt}from"./vendor-vite-runtime-DD1OZmLC.js";import{Q as gi}from"./vendor-qrcode-gzL9QFkg.js";import{p as Ac}from"./vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js";import{c as Lc}from"./vendor-zustand-CXhN0IMY.js";import{g as Mc,s as Rc}from"./runtimeSurface-BR_dhe7_.js";import{C as Dc,a as _c,b as Oc}from"./collapsible-BjpDEohv.js";const zc=["standalone","minimal-ui","fullscreen","window-controls-overlay"],Uc=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Fc=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":zc.find(n=>Uc(n))??"browser",mn="pichamber.mobile.connections.v1",Bc="pichamber.mobile.",rr="pichamber.mobile.deviceId",xi=12,vi=8e3,$c=2500,Wc=5e3,bi=2500,vs=15e3,yi=8e3,Kc=1500,Hc=5e3,Vc=()=>{try{const t=window.localStorage.getItem(rr);if(t&&t.trim())return t.trim();const s=ln();return window.localStorage.setItem(rr,s),s}catch{return ln()}},ir=()=>`mobile:${Vc()}`,or=()=>{try{const t=Uo.getPlatform();return t==="ios"||t==="android"?t:void 0}catch{return}},wi=()=>{let t=0;return{begin:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:s=>s===t}},ss=t=>{const s=t.trim();if(!s)return"";const n=/^https?:\/\//i.test(s)?s:`http://${s}`,a=new URL(n);return a.hash="",a.search="",a.pathname=a.pathname.replace(/\/+$/,""),a.toString().replace(/\/+$/,"")},Ls=t=>{try{return new URL(t).host}catch{return t}},Ot=t=>{try{return ss(t)}catch{return t.trim().replace(/\/+$/g,"")}},Pa=(t,s)=>Ot(t)===Ot(s),Ta=t=>`relay:${t.serverId}@${t.relayUrl.trim()}`,Gc=t=>`relay://${t.serverId}`,zs=t=>t.candidates.filter(s=>s.kind==="direct"),Zt=t=>{const s=t.candidates.find(n=>n.kind==="relay");return s&&s.kind==="relay"?s.relay:null},Xt=t=>{const s=zs(t)[0];if(s)return s.url;const n=Zt(t);return n?Gc(n):""},Ue=t=>{const s=Zt(t);if(s)return Ta(s);const n=zs(t)[0];return n?Ot(n.url):""},Ms=(t,s)=>{const n=t.find(i=>i.kind==="relay"),a=n&&n.kind==="relay"?n.relay.serverId:null,r=new Set(t.filter(i=>i.kind==="direct").map(i=>Ot(i.url)));return s.some(i=>i.kind==="relay"?a!==null&&i.relay.serverId===a:r.has(Ot(i.url)))},Ia=t=>{const s=(()=>{try{return ss(t)}catch{return""}})();return s?[{kind:"direct",url:s}]:[]},lr=t=>{if(t.candidates&&t.candidates.length>0)return t.candidates;const s=[];return typeof t.url=="string"&&t.url.trim()&&!/^relay:\/\//i.test(t.url.trim())&&s.push(...Ia(t.url)),t.relay&&s.push({kind:"relay",relay:t.relay}),s},Ea=t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;const s=t;if(typeof s.relayUrl!="string"||!s.relayUrl.trim()||typeof s.serverId!="string"||!s.serverId.trim())return null;const n=s.hostEncPubJwk;if(!n||typeof n!="object"||Array.isArray(n))return null;const a=n;return a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||!a.x||typeof a.y!="string"||!a.y?null:{relayUrl:s.relayUrl,serverId:s.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:a.x,y:a.y}}},qc=t=>{if(!t||typeof t!="object")return null;const s=t;if(s.kind==="direct")return typeof s.url=="string"&&s.url.trim()?{kind:"direct",url:s.url}:null;if(s.kind==="relay"){const n=Ea(s.relay);return n?{kind:"relay",relay:n}:null}return null},Qc=t=>{if(t.mode==="relay"){const s=Ea(t.relay);return s?[{kind:"relay",relay:s}]:[]}return typeof t.url=="string"?Ia(t.url):[]},Us=t=>t.kind==="relay"?{kind:"relay",relay:{relayUrl:t.relay.relayUrl,serverId:t.relay.serverId,hostEncPubJwk:t.relay.hostEncPubJwk}}:{kind:"direct",url:t.url},Ut=()=>{if(typeof window>"u")return[];let t;try{t=JSON.parse(window.localStorage.getItem(mn)||"[]")}catch{return[]}if(!Array.isArray(t))return[];const s=Re();return t.flatMap(n=>{if(!n||typeof n!="object")return[];const a=n;if(typeof a.id!="string")return[];const r=Array.isArray(a.candidates)?a.candidates.map(qc).filter(m=>!!m):Qc(a);if(r.length===0)return[];const i=typeof a.clientToken=="string"&&a.clientToken.trim()?a.clientToken:void 0,c=typeof a.label=="string"&&a.label.trim()?a.label:Ls(Xt({candidates:r})),o=typeof a.pinnedServerId=="string"&&a.pinnedServerId.trim()?a.pinnedServerId.trim():void 0,d={id:a.id,label:c,candidates:r,lastUsedAt:typeof a.lastUsedAt=="number"?a.lastUsedAt:0,...o?{pinnedServerId:o}:{}};return s?[{...d,hasToken:!!a.hasToken||!!i}]:[{...d,clientToken:i,hasToken:!!i}]}).sort((n,a)=>a.lastUsedAt-n.lastUsedAt)},Aa=t=>{if(typeof window>"u")return;const s=Re(),n=t.slice(0,xi).map(a=>{const r={id:a.id,label:a.label,candidates:a.candidates.map(Us),lastUsedAt:a.lastUsedAt,...typeof a.pinnedServerId=="string"&&a.pinnedServerId.trim()?{pinnedServerId:a.pinnedServerId.trim()}:{}};return s?{...r,hasToken:!!(a.hasToken||a.clientToken)}:{...r,clientToken:a.clientToken}});try{window.localStorage.setItem(mn,JSON.stringify(n))}catch(a){console.warn("[mobile-storage] failed to persist connection metadata",a)}},ji=(t,s)=>{const n=t.find(i=>s.id&&i.id===s.id||Ms(i.candidates,s.candidates)),a=Re(),r={id:s.id||n?.id||ln(),label:s.label,candidates:s.candidates,lastUsedAt:Date.now(),pinnedServerId:typeof s.pinnedServerId=="string"&&s.pinnedServerId.trim()?s.pinnedServerId.trim():s.pinnedServerId===null?void 0:n?.pinnedServerId,...a?{hasToken:s.hasToken??(!!s.clientToken||n?.hasToken||!1)}:{clientToken:s.clientToken??n?.clientToken,hasToken:!!(s.clientToken??n?.clientToken)}};return[r,...t.filter(i=>i.id!==r.id&&!Ms(i.candidates,s.candidates))].slice(0,xi)},La=Ac,Jc=0,Fs=new Map,Ma=t=>`${Bc}token.${encodeURIComponent(t)}`,ki=async(t,s)=>{let n;const a=new Promise(r=>{n=window.setTimeout(()=>r(s),Wc)});try{return await Promise.race([t.catch(()=>s),a])}finally{n!==void 0&&window.clearTimeout(n)}},Ni=async(t,s,n)=>Re()?ki(s().catch(a=>(console.warn(`[mobile-storage] ${t} failed`,a),n)),n):n,Yc=t=>{if(!t||typeof t!="object")return!1;const{code:s,message:n}=t;return s==="invalidData"?!0:typeof n=="string"&&/AEADBadTagException|BadPaddingException/.test(n)},Bs=async(t,s)=>{const n=s?.bypassCache?void 0:Fs.get(t);if(typeof n=="string"&&n)return{status:"present",token:n};if(!Re())return{status:"absent"};const a=await ki(La.internalGetItem({prefixedKey:Ma(t),sync:!1}).then(i=>({kind:"ok",data:i?.data??null})).catch(i=>({kind:"error",error:i})),{kind:"timeout"});if(a.kind==="timeout")return console.warn("[mobile-storage] secure:read timed out"),{status:"failure"};if(a.kind==="error")return Yc(a.error)?(console.warn("[mobile-storage] secure:read undecryptable entry"),{status:"absent"}):(console.warn("[mobile-storage] secure:read failed",a.error),{status:"failure"});const r=a.data;return typeof r=="string"&&r.trim()?(Fs.set(t,r),{status:"present",token:r}):{status:"absent"}},Kt=async(t,s)=>{if(!Re())return!1;const n=await Ni("secure:write",async()=>(await La.internalSetItem({prefixedKey:Ma(t),data:s,sync:!1,access:Jc}),!0),!1);return n&&s.trim()?Fs.set(t,s):Fs.delete(t),n},Xc=async t=>{Fs.delete(t),await Ni("secure:delete",async()=>(await La.internalRemoveItem({prefixedKey:Ma(t),sync:!1}),!0),!1)},Ci=async(t,s)=>{let n=0,a=0;return{records:await Promise.all(t.map(async i=>{if(!i||typeof i!="object")return i;const c=i,o=typeof c.url=="string"?c.url:null,d=typeof c.clientToken=="string"?c.clientToken.trim():"";if(!o||!d)return i;if(!await s(o,d))return a+=1,i;n+=1;const{clientToken:m,...p}=c;return{...p,hasToken:!0}})),migrated:n,failed:a}},Si=async()=>{if(typeof window>"u"||!Re())return;let t;try{t=JSON.parse(window.localStorage.getItem(mn)||"[]")}catch{return}if(!Array.isArray(t)||t.filter(a=>!!a&&typeof a=="object"&&typeof a.url=="string"&&typeof a.clientToken=="string"&&!!a.clientToken.trim()).length===0)return;const n=await Ci(t,async(a,r)=>{const i=Ot(a);if(!await Kt(i,r))return!1;const c=await Bs(i,{bypassCache:!0});return c.status==="present"&&c.token===r});if(n.migrated>0)try{window.localStorage.setItem(mn,JSON.stringify(n.records))}catch(a){console.warn("[mobile-storage] failed to finalize secure token migration",a)}},Pi=async()=>(await Si(),Ut()),$s=async t=>{const s=ji(Ut(),t);return Aa(s),Re()&&t.clientToken&&await Kt(Ue({candidates:t.candidates}),t.clientToken),s},Ti=async t=>{const s=Ut(),n=s.find(r=>r.id===t)??null,a=s.filter(r=>r.id!==t);return Aa(a),n&&Re()&&await Xc(Ue(n)),a},Ra=t=>{try{return JSON.stringify(t)}catch{return String(t)}},Fe=(t,s={})=>{console.info("[mobile-connect]",t,Ra(s)),Gr("connect",{code:t,status:typeof s.status=="number"?s.status:void 0,detail:typeof s.reason=="string"?s.reason:typeof s.result=="string"?s.result:void 0})},Zc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},ed=t=>{if(typeof t!="string")return t??void 0;try{return JSON.parse(t)}catch{return t}},td=async(t,s,n)=>{if(!Re())return null;const a=n?.timeoutMs??vi;try{const{CapacitorHttp:r}=await Yt(async()=>{const{CapacitorHttp:o}=await import("./vendor-boot-D-KEJjsM.js").then(d=>d.cr);return{CapacitorHttp:o}},__vite__mapDeps([0,1,2])),i=Object.fromEntries(new Headers(s?.headers).entries()),c=await r.request({url:t,method:s?.method||"GET",headers:i,data:ed(s?.body),connectTimeout:a,readTimeout:a});return{ok:c.status>=200&&c.status<300,status:c.status,source:"native-http",json:async()=>Zc(c.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",Ra({url:t,error:r instanceof Error?r.message:String(r)})),null}},sd=async(t,s)=>{const n=await fetch(t,s).catch(a=>(console.warn("[mobile-connect]","browser-fetch failed",Ra({url:t,error:a instanceof Error?a.message:String(a)})),null));return n?{ok:n.ok,status:n.status,source:"browser-fetch",json:()=>n.json()}:null},zt=async(t,s,n)=>{let a;const r=new Promise(i=>{a=window.setTimeout(()=>{n?.(),i(null)},t)});try{return await Promise.race([s,r])}catch{return null}finally{a!==void 0&&window.clearTimeout(a)}},es=async(t,s,n)=>{const a=n?.totalTimeoutMs??vi,r=Date.now(),i=Math.min($c,a),c=await zt(i,td(t,s,{timeoutMs:i}));if(c)return c;const o=new AbortController,d=Math.max(500,a-(Date.now()-r));return zt(d,sd(t,{...s,signal:o.signal}),()=>o.abort())},Cn=async t=>{if(!t)return null;const s=await t.json().catch(()=>null);if(!s||typeof s!="object")return null;const n=s;return{authenticated:typeof n.authenticated=="boolean"?n.authenticated:void 0,disabled:typeof n.disabled=="boolean"?n.disabled:void 0,scope:typeof n.scope=="string"?n.scope:void 0}},nd=async(t,s,n,a=vs,r)=>{if(r?.shouldAbort?.())return{outcome:"unreachable"};const i=qr({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk}),c=o=>o==="ok"&&r?.keepTunnel?{outcome:o,tunnel:i}:(i.close(),{outcome:o});try{const o=s?{Authorization:`Bearer ${s}`}:void 0,d=await zt(a,i.fetch("/auth/session",{headers:o}).catch(()=>null));if(Fe("relay:session",{ok:d?.ok===!0,status:d?.status??null,hasToken:!!s}),!d)return c("unreachable");if(d.status===401)return c(s?"auth-failed":"needs-login");if(!d.ok&&d.status!==404)return c("auth-failed");const m=await Cn(d);return m&&m.disabled!==!0&&m.authenticated===!1?c(s?"auth-failed":"needs-login"):c("ok")}catch(o){throw i.close(),o}},ad=(t,s,n,a,r)=>{const i=typeof window<"u"?window.location.origin:"",c={relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk,...n?{grant:n}:{}};r&&Bo(c,r),wa({apiBaseUrl:i,clientToken:s,runtimeKey:a??Ta(t),relay:c})},Ii=async t=>{if(!t?.ok)return null;const s=await t.json().catch(()=>null),n=s&&typeof s=="object"?s.serverId:null;return typeof n=="string"&&n.trim()?n.trim():null},hn=async(t,s,n)=>{const a=n?.shouldAbort,r=n?.fast?{totalTimeoutMs:bi}:void 0,i=Zt({candidates:t})?.serverId??null,c=t.find(h=>h.kind==="relay")??null,o=t.filter(h=>h.kind==="direct"),d=typeof n?.pinnedServerId=="string"&&n.pinnedServerId.trim()?n.pinnedServerId.trim():null,m=async()=>{let h=!1,u=null;for(const g of o){if(a?.())return{status:"unreachable"};const v=ss(g.url)||g.url,x=await es(`${v}/health`,{method:"GET"},r);if(a?.())return{status:"unreachable"};if(!x?.ok)continue;const b=await Ii(x);if(d){if(b&&b!==d){Fe("probe:server-id-mismatch",{url:v}),h=!0;continue}}else b&&!u&&(u=b);if(i&&b&&b!==i){Fe("probe:server-id-mismatch",{url:v});continue}const j=s?{Authorization:`Bearer ${s}`}:void 0,k=await es(`${v}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:j},r);if(a?.())return{status:"unreachable"};if(k?.status===401)return{status:"needs-login"};if(!k||!k.ok&&k.status!==404)continue;const P=await Cn(k);if(P&&P.disabled!==!0&&P.authenticated===!1)return{status:"needs-login"};const E=P?.disabled===!0;return!s&&Re()&&!E&&P?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:v,...b?{serverId:b}:{}},...u?{serverId:u}:{}}}return h?{status:"unreachable",reason:"wrong-server"}:{status:"unreachable"}},p=async()=>{if(!c)return{status:"unreachable"};if(a?.())return{status:"unreachable"};const{outcome:h,tunnel:u}=await nd(c.relay,s,void 0,n?.fast?yi:void 0,{keepTunnel:!0,...a?{shouldAbort:a}:{}});return a?.()?(u?.close(),{status:"unreachable"}):h==="ok"?{status:"ok",transport:{kind:"relay",relay:c.relay,tunnel:u}}:h==="needs-login"||h==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return c?o.length===0?p():new Promise(h=>{let u=!1,g=!1,v,x=null,b=null;const j=E=>{E?.status==="ok"&&E.transport.kind==="relay"&&E.transport.tunnel?.close()},k=E=>{u||(u=!0,h(E))},P=()=>{g||u||a?.()||(v!==void 0&&(window.clearTimeout(v),v=void 0),p().then(E=>{if(b=E,u||g){j(E);return}if(E.status==="ok"||E.status==="needs-login"){k(E);return}x&&k(x)}))};m().then(E=>{if(x=E,!u){if(E.status==="ok"||E.status==="needs-login"){g=!0,v!==void 0&&window.clearTimeout(v),j(b),k(E);return}if(b){k(b);return}P()}}),v=window.setTimeout(P,Kc)}):m()},Vt=(t,s,n)=>{t.kind==="relay"?ad(t.relay,s,n?.grant,n?.runtimeKey,t.tunnel):wa({apiBaseUrl:t.url,clientToken:s,runtimeKey:n?.runtimeKey}),Di()},rd=()=>{const t=Ut()[0];return t?.label?.trim()?t.label:null},id=async()=>{const t=Rs(),s=`${qe()}|${xt()}`,n=()=>Rs()!==t||`${qe()}|${xt()}`!==s;if(await Si(),n())return{status:"no-candidate"};const a=Ut()[0];if(!a)return{status:"no-candidate"};let r;if(Re()){if(!a.hasToken)return{status:"no-candidate"};const c=await Bs(Ue(a));if(c.status==="failure")return{status:"unreachable",label:a.label};if(c.status==="absent"||!c.token)return{status:"needs-login",label:a.label};r=c.token}else if(r=a.clientToken,!r)return{status:"no-candidate"};const i=await hn(a.candidates,r,{fast:!0,pinnedServerId:a.pinnedServerId});return n()?(da(i),{status:"no-candidate"}):i.status==="needs-login"?{status:"needs-login",label:a.label}:i.status!=="ok"?{status:"unreachable",label:a.label}:(await $s({id:a.id,label:a.label,candidates:a.candidates,...!a.pinnedServerId&&i.serverId?{pinnedServerId:i.serverId}:{}}),n()?(fn(i.transport),{status:"no-candidate"}):(Vt(i.transport,r,{runtimeKey:Ue(a)}),{status:"connected"}))},Ei=async(t,s)=>{let n="";try{n=ss(t.url)}catch{return!1}if(!n)return!1;const a=t.clientToken?.trim()||void 0,r=a?{Authorization:`Bearer ${a}`}:void 0,i=s?.fast?{totalTimeoutMs:bi}:void 0;if(!(await es(`${n}/health`,{method:"GET",headers:r},i))?.ok)return!1;const o=await es(`${n}/auth/session`,{method:"GET",credentials:a?"omit":"include",headers:r},i);if(!o||!o.ok&&o.status!==404)return!1;const d=await Cn(o);return!(d&&d.disabled!==!0&&d.authenticated===!1)},cr=async(t,s)=>{const n=Zt({candidates:t})?.serverId??null,a=typeof s=="string"&&s.trim()?s.trim():null;for(const r of t){if(r.kind==="relay"){const d=qr(r.relay),m=await zt(vs,d.fetch("/health").catch(()=>null));if(Fe("establish:relay:health",{ok:m?.ok===!0,status:m?.status??null}),m?.ok)return{kind:"relay",relay:r.relay,tunnel:d};d.close();continue}const i=ss(r.url)||r.url,c=await es(`${i}/health`,{method:"GET"});if(Fe("establish:direct:health",{ok:c?.ok===!0,status:c?.status??null}),!c?.ok)continue;const o=await Ii(c);if(a&&o&&o!==a){Fe("establish:server-id-mismatch",{url:i});continue}if(n&&o&&o!==n){Fe("establish:server-id-mismatch",{url:i});continue}return{kind:"direct",url:i,...o?{serverId:o}:{}}}return null},od=t=>[...t].sort((s,n)=>{const a=(s.priority??100)-(n.priority??100);if(a!==0)return a;const r=i=>i.type==="relay"?2:i.url.startsWith("https://")?0:1;return r(s)-r(n)}).flatMap(s=>{if(s.type==="relay"){const n=Ea({relayUrl:s.relayUrl,serverId:s.serverId,hostEncPubJwk:s.hostEncPubJwk});return n?[{kind:"relay",relay:n}]:[]}return Ia(s.url)}),Ai=async(t,s)=>{if(!ms())return Ei(t,s);const n=await zt(s?.fast?yi:vs,Ae("/auth/session").then(r=>r).catch(()=>null));if(!n||!n.ok&&n.status!==404)return!1;const a=await Cn(n);return!(a&&a.disabled!==!0&&a.authenticated===!1)},ld=t=>t.kind==="relay"?ms():!ms()&&Pa(t.url,xt()),Sn=()=>{const t=qe();return t?Ut().find(s=>Ue(s)===t)??null:null},an=t=>{const s=qe();return!!s&&Ue(t)===s},Da=t=>({generation:Rs(),runtimeKey:qe(),apiBaseUrl:xt(),connectionId:t.id,secureKey:Ue(t),candidatesJson:JSON.stringify(t.candidates.map(Us))}),Li=t=>{if(Rs()!==t.generation||qe()!==t.runtimeKey||xt()!==t.apiBaseUrl)return!0;const s=Sn();if(!s||s.id!==t.connectionId||Ue(s)!==t.secureKey)return!0;try{if(JSON.stringify(s.candidates.map(Us))!==t.candidatesJson)return!0}catch{return!0}return!1},fn=t=>{try{t?.kind==="relay"&&t.tunnel?.close()}catch{}},da=t=>{t.status==="ok"&&fn(t.transport)},cd=t=>t?`${t.generation}|${t.runtimeKey}|${t.apiBaseUrl}|${t.connectionId}|${t.secureKey}|${t.candidatesJson}`:`noselection|${Rs()}|${qe()}`;let Gt=null,ua="";const dr=(t,s)=>{const n=s.finally(()=>{Gt===n&&(Gt=null,ua="")});return Gt=n,ua=t,n},qn=async()=>{const t=await dd();return Gr("reprobe",{code:t}),t},Mi=()=>{const t=Sn(),s=t?Da(t):null,n=cd(s);if(Gt&&ua===n)return Gt;if(Gt){const r=Gt.then(()=>qn(),()=>qn());return dr(n,r)}return dr(n,qn())},dd=async()=>{const t=Sn();if(!t)return"no-connection";const s=Da(t),n=()=>Li(s);let a;if(Re()){if(t.hasToken){const m=await Bs(Ue(t));if(m.status==="present")a=m.token;else return n()?"no-connection":m.status==="absent"?"needs-login":"unreachable"}if(n())return"no-connection"}else a=t.clientToken;if(!a)return"unreachable";if(n())return"no-connection";const r=t.candidates.findIndex(m=>ld(m.kind==="relay"?{kind:"relay",relay:m.relay}:{kind:"direct",url:m.url})),i=r>=0?t.candidates.slice(0,r):t.candidates,c=await hn(i,a,{fast:!0,shouldAbort:n,pinnedServerId:t.pinnedServerId});if(n())return da(c),"no-connection";if(c.status==="ok")return await $s({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&c.serverId?{pinnedServerId:c.serverId}:{}}),n()?(fn(c.transport),"no-connection"):(Vt(c.transport,a,{runtimeKey:Ue(t)}),"switched");if(c.status==="needs-login")return"needs-login";if(r>=0){if(n())return"no-connection";const m=await Ai({url:s.apiBaseUrl,clientToken:a},{fast:!0});if(n())return"no-connection";if(m)return Di(),"unchanged"}const o=r>=0?t.candidates.slice(r+1):[];if(o.length===0)return"unreachable";const d=await hn(o,a,{fast:!0,shouldAbort:n,pinnedServerId:t.pinnedServerId});return n()?(da(d),"no-connection"):d.status==="ok"?(await $s({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&d.serverId?{pinnedServerId:d.serverId}:{}}),n()?(fn(d.transport),"no-connection"):(Vt(d.transport,a,{runtimeKey:Ue(t)}),"switched")):d.status==="needs-login"?"needs-login":"unreachable"};let Qn=!1;const Ri=async()=>{if(Qn)return"skipped";const t=Sn();if(!t)return Fe("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const s=Zt(t);if(!s)return Fe("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const n=Da(t),a=()=>Li(n);Qn=!0;try{const r=await zt(vs,Ae("/api/client-auth/connection/candidates").then(u=>u).catch(()=>null));if(!r?.ok)return Fe("candidates:refresh-skip",{reason:"fetch-failed",status:r?.status??null}),"skipped";if(a())return Fe("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const i=await r.json().catch(()=>null);if(!i||i.serverId!==s.serverId)return Fe("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const c=Array.isArray(i.candidates)?i.candidates:[],o=[],d=[];for(const u of c){if(!u||typeof u!="object")continue;const g=u;if(!(g.type!=="lan"&&g.type!=="tailscale"||typeof g.url!="string"))try{const v=ss(g.url),x=g.type==="tailscale"?d:o;v&&!x.includes(v)&&x.push(v)}catch{}}if(o.length===0&&d.length===0)return Fe("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const m=zs(t).filter(u=>u.url.startsWith("https://")),p=[...o.map(u=>({kind:"direct",url:u})),...d.filter(u=>!o.includes(u)).map(u=>({kind:"direct",url:u})),...m.filter(u=>![...o,...d].includes(u.url)),{kind:"relay",relay:s}];return JSON.stringify(t.candidates.map(Us))===JSON.stringify(p.map(Us))?"unchanged":a()?(Fe("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(Fe("candidates:refreshed",{lanCount:o.length}),await $s({id:t.id,label:t.label,candidates:p}),"updated")}finally{Qn=!1}},Di=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const t=await Ri().catch(()=>"skipped");Fe("candidates:refresh-result",{result:t}),t==="updated"&&ms()&&await Mi().catch(()=>null)})()},Hc)},_i=t=>{const[s,n]=l.useState(()=>Ut()),[a,r]=l.useState(null),[i,c]=l.useState(null),[o,d]=l.useState(null),m=l.useRef(s),p=l.useRef(null),h=l.useRef(wi()),u=l.useCallback(f=>{m.current=f,n(f)},[]),g=l.useCallback(f=>{p.current=f,r(f)},[]),v=l.useCallback(f=>{p.current===f&&(p.current=null,r(null))},[]);l.useEffect(()=>{let f=!1;return Pi().then(N=>{f||u(N)}),()=>{f=!0}},[u]);const x=l.useCallback(f=>{const N=ji(m.current,f);return u(N),Aa(N),N},[u]),b=l.useCallback(async f=>{c(null),g("connect");try{const N=lr(f);if(N.length===0){c("Enter a server URL.");return}const C=f.id?m.current.find(_=>_.id===f.id):m.current.find(_=>Ms(_.candidates,N)),w=f.label?.trim()||C?.label||Ls(Xt({candidates:N})),L=f.relayGrant;let I=f.clientToken?.trim()||void 0;const T=!!I;if(!I)if(Re()){if(C?.hasToken){const _=await Bs(Ue({candidates:N}));if(_.status==="present")I=_.token;else if(_.status==="failure"){c("Could not read saved credentials. Please try again.");return}}}else I=C?.clientToken;Fe("connect:start",{candidates:N.map(_=>_.kind),hasToken:!!I});const A=await hn(N,I,{pinnedServerId:C?.pinnedServerId});if(Fe("connect:probe",{status:A.status}),A.status==="unreachable"){A.reason==="wrong-server"?c("That address belongs to a different server. Check the address or re-pair."):c("Could not reach that PiChamber server.");return}if(A.status==="needs-login"){x({id:C?.id,label:w,candidates:N}),d({id:C?.id??ln(),label:w,candidates:N,relay:Zt({candidates:N})??void 0,relayGrant:L,...C?.pinnedServerId?{pinnedServerId:C.pinnedServerId}:{}});return}const F=!C?.pinnedServerId&&A.serverId?A.serverId:void 0;I&&T&&Re()&&await Kt(Ue({candidates:N}),I),x({id:C?.id,label:w,candidates:N,clientToken:I,...F?{pinnedServerId:F}:{}}),Vt(A.transport,I??null,{runtimeKey:Ue({candidates:N}),grant:L}),t()}catch(N){console.warn("[mobile-connect] connect threw",N),c("That server URL is not valid.")}finally{v("connect")}},[g,v,t,x]),j=l.useCallback(async f=>{if(p.current==="pairing")return;c(null),g("pairing");const N=od(f.candidates),C=m.current.find(I=>Ms(I.candidates,N));let w=null,L=!1;try{if(w=await cr(N,C?.pinnedServerId),!w){c("Could not reach that PiChamber server.");return}const I=JSON.stringify({pairingId:f.pairingId,secret:f.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:or(),dedupeKey:ir()}),T={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:I},A=w.kind==="relay"?await zt(vs,w.tunnel.fetch("/api/client-auth/pairing/redeem",T).catch(()=>null)):await es(`${w.url}/api/client-auth/pairing/redeem`,T);if(!A?.ok){c("This server needs a password or client token.");return}const F=await A.json().catch(()=>null),_=typeof F?.clientToken=="string"?F.clientToken.trim():"";if(!_){c("This server needs a password or client token.");return}const z=typeof F?.server?.label=="string"?F.server.label:"",K=f.label||z||Ls(Xt({candidates:N}));if(Re()&&!await Kt(Ue({candidates:N}),_)){c("This server needs a password or client token.");return}x({id:C?.id,label:K,candidates:N,clientToken:_,...!C?.pinnedServerId&&w.kind==="direct"&&w.serverId?{pinnedServerId:w.serverId}:{}}),Vt(w.kind==="relay"?{kind:"relay",relay:w.relay,tunnel:w.tunnel}:{kind:"direct",url:w.url},_,{runtimeKey:Ue({candidates:N})}),L=w.kind==="relay",t()}catch(I){console.warn("[mobile-connect] pairing threw",I),c("This server needs a password or client token.")}finally{!L&&w?.kind==="relay"&&w.tunnel.close(),v("pairing")}},[g,v,t,x]),k=l.useCallback(async f=>{if(!o||!f.trim()||p.current==="password")return;c(null),g("password");const N=h.current.begin(),C=()=>h.current.isCurrent(N),{id:w,label:L,candidates:I}=o,T=o.pinnedServerId;let A=null,F=!1;try{if(A=await cr(I,T),!C())return;if(!A){c("Could not reach that PiChamber server.");return}const _={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:f,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:or(),dedupeKey:ir()})};Fe("password:start",{transport:A.kind});const z=A.kind==="relay"?await zt(vs,A.tunnel.fetch("/auth/session",_).catch(()=>null)):await es(`${A.url}/auth/session`,_);if(!C())return;if(Fe("password:done",{ok:z?.ok===!0,status:z?.status??null}),!z?.ok){c("Could not unlock that server. Check the password.");return}const K=await z.json().catch(()=>null);if(!C())return;const H=typeof K?.clientToken=="string"?K.clientToken.trim():"";if(Fe("password:token",{issued:!!H}),!H){if(A.kind==="direct"&&!Re()){x({id:w,label:L,candidates:I}),d(null),Vt({kind:"direct",url:A.url},null,{runtimeKey:Ue({candidates:I})}),t();return}c("This server needs a password or client token.");return}if(Re()&&(!C()||(await Kt(Ue({candidates:I}),H),!C()))||!C()||(x({id:w,label:L,candidates:I,clientToken:H,...!T&&A.kind==="direct"&&A.serverId?{pinnedServerId:A.serverId}:{}}),d(null),Vt(A.kind==="relay"?{kind:"relay",relay:A.relay,tunnel:A.tunnel}:{kind:"direct",url:A.url},H,{runtimeKey:Ue({candidates:I})}),F=A.kind==="relay",!C()))return;t()}catch(_){if(!C())return;console.warn("[mobile-connect] password threw",_),c("Could not unlock that server. Check the password.")}finally{!F&&A?.kind==="relay"&&A.tunnel.close(),C()&&v("password")}},[g,v,t,o,x]),P=l.useCallback(()=>{h.current.cancel(),v("password"),d(null),c(null)},[v]),E=l.useCallback(async f=>{c(null);let N=lr(f);const C=f.id?m.current.find(z=>z.id===f.id)??null:null;if(C){const z=N.filter(ne=>ne.kind==="direct"),K=zs(C).filter(ne=>ne.url.startsWith("https://")&&!z.some(Z=>Pa(Z.url,ne.url))),H=Zt(C);N=[...z,...K,...H?[{kind:"relay",relay:H}]:[]]}if(N.length===0)return c("Enter a server URL."),null;const w=new Set((C?zs(C):[]).map(z=>Ot(z.url))),L=new Set(N.filter(z=>z.kind==="direct").map(z=>Ot(z.url))),I=w.size!==L.size||[...L].some(z=>!w.has(z)),T=C&&!I?void 0:null,A=f.clientToken?.trim()||void 0,F=f.label?.trim()||Ls(Xt({candidates:N}));if(Re()){const z=Ue({candidates:N});if(A)await Kt(z,A);else if(C?.hasToken){const K=Ue(C);if(K&&z&&K!==z){const H=await Bs(K);H.status==="present"&&await Kt(z,H.token)}}}return x({id:f.id,label:F,candidates:N,clientToken:A,pinnedServerId:T}).find(z=>Ms(z.candidates,N))??null},[x]),y=l.useCallback(async f=>{const N=m.current.find(w=>w.id===f)??null,C=await Ti(f);return u(C),N},[u]);return{connections:s,isBusy:a!==null,isPasswordBusy:a==="password",error:i,pendingConnection:o,connect:b,redeemPairingConnection:j,submitPassword:k,cancelPassword:P,saveConnection:E,removeConnection:y,setError:c}},ud=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:id,connectionDisplayUrl:Xt,createMobilePasswordOperationTracker:wi,deleteMobileConnection:Ti,getAutoConnectTargetLabel:rd,getConnectionLabel:Ls,isActiveRuntimeConnection:an,isSameConnectionUrl:Pa,loadMobileConnections:Pi,migrateLegacyInlineTokenRecords:Ci,normalizeConnectionUrl:ss,refreshActiveConnectionCandidates:Ri,relayConnectionRuntimeKey:Ta,reprobeActiveConnection:Mi,upsertMobileConnection:$s,useMobileConnection:_i,validateActiveRuntimeSession:Ai,validateMobileConnectionSession:Ei},Symbol.toStringTag,{value:"Module"})),Oi=()=>{if(typeof window>"u")return null;const s=window.Capacitor?.Plugins?.BarcodeScanner;return s&&(typeof s.scan=="function"||typeof s.startScan=="function")?s:null},zi=()=>window.Capacitor?.getPlatform?.()==="android",Ui=t=>{const s=t.trim();if(!s)return null;if(/^pichamber:\/\//i.test(s)){const n=$o(s);return n?{pairing:n}:null}return/^https?:\/\//i.test(s)?{url:s}:null},Fi=(t,s)=>{const n=Ui(t);if(!n&&s?.pairingStringFallback){const a=Wo(t);if(a)return{status:"pairing",pairing:a}}return n?"pairing"in n?{status:"pairing",...n}:{status:"ok",...n}:{status:"invalid"}},pd=async(t,s)=>{if(!t.startScan||!t.stopScan||!t.addListener)return{status:"unsupported"};if(s?.aborted)return{status:"cancelled"};let n,a,r=!1,i=()=>{};const c=new Promise(m=>{i=m}),o=m=>{r||(r=!0,i(m))},d=()=>o({status:"cancelled"});s?.addEventListener("abort",d,{once:!0});try{return(await Promise.allSettled([Promise.resolve(t.addListener("barcodesScanned",({barcodes:p})=>{const h=p?.[0],u=(h?.rawValue??h?.displayValue??"").trim();u&&o(Fi(u,{pairingStringFallback:!0}))})).then(p=>{n=p}),Promise.resolve(t.addListener("scanError",()=>o({status:"failed"}))).then(p=>{a=p})])).some(({status:p})=>p==="rejected")?o({status:"failed"}):r||t.startScan({formats:["QR_CODE"]}).catch(()=>o({status:"failed"})),await c}finally{s?.removeEventListener("abort",d),await Promise.allSettled([Promise.resolve(n?.remove()),Promise.resolve(a?.remove()),t.stopScan()]),await Bi()}},ur=t=>{const s=t.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/);if(!s||s[4]!==void 0&&parseFloat(s[4])===0)return null;const n=parseInt(s[1],10).toString(16).padStart(2,"0"),a=parseInt(s[2],10).toString(16).padStart(2,"0"),r=parseInt(s[3],10).toString(16).padStart(2,"0");return`#${n}${a}${r}`},md=()=>typeof window>"u"||typeof window.getComputedStyle!="function"?null:ur(window.getComputedStyle(document.documentElement).backgroundColor)??(document.body?ur(window.getComputedStyle(document.body).backgroundColor):null),Bi=async()=>{if(!zi())return;const t=md();if(!t)return;const{setNativeWebViewBackground:s}=await Yt(()=>import("./nativeFileSave-D542OJlG.js"),__vite__mapDeps([3,0,1,2,4,5,6,7,8,9])).catch(()=>({setNativeWebViewBackground:void 0}));await s?.(t)},hd=()=>Oi()!==null,fd=async t=>{const s=Oi();if(!s)return{status:"unsupported"};try{if(s.requestPermissions){const c=(await s.requestPermissions())?.camera;if(c&&c!=="granted"&&c!=="limited")return{status:"permission-denied"}}if(t?.signal?.aborted)return{status:"cancelled"};if(zi())return pd(s,t?.signal);if(!s.scan)return{status:"unsupported"};const a=(await s.scan({formats:["QR_CODE"]}))?.barcodes?.[0],r=(a?.rawValue??a?.displayValue??"").trim();return r?Fi(r):{status:"cancelled"}}catch{return{status:"failed"}}},gd=t=>{switch(t.kind){case"connected":return{status:"ok",latencyMs:0};case"needs-login":return{status:"auth",latencyMs:0};case"unreachable":return{status:"unreachable",latencyMs:0};case"connecting":case"unknown":return null}},xd=(t,s)=>{const n=gd(s.status),a=Tl(n,s.probing===!0),r=[];for(const o of t.candidates){if(o.kind==="relay"){r.some(m=>m.kind==="relay")||r.push({kind:"relay",label:tr.relay,address:null});continue}const d=Il(o.url);r.some(m=>m.kind===d)||r.push({kind:d,label:tr[d],address:o.url})}let i=null;s.isCurrent&&s.status.kind==="connected"&&(i=s.status.transport==="relay"?r.find(o=>o.kind==="relay")??null:r.find(o=>o.kind!=="relay")??null);const c=r.some(o=>o.kind!=="relay");return{id:t.id,label:t.label,isCurrent:s.isCurrent,isDefault:!1,isLocal:!1,routes:r,activeRoute:i,status:a.status,latencyMs:s.status.kind==="connected"?s.status.latencyMs??null:a.latencyMs,canEdit:c,canRemove:!0,canOpenInNewWindow:!1}},Jn={autoComplete:"off",autoCorrect:"off",spellCheck:!1},vd="h-12 w-full rounded-[16px] border border-border/70 bg-surface-elevated px-4 text-[16px] text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20",bd=({onCancel:t})=>{const s=l.useRef(null);return Zr(l.useCallback(()=>(t(),!0),[t])),l.useLayoutEffect(()=>{const n={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},a={value:document.body.style.getPropertyValue("background-color"),priority:document.body.style.getPropertyPriority("background-color")};document.documentElement.style.setProperty("background-color","rgba(0, 0, 0, 0)","important"),document.body.style.setProperty("background-color","rgba(0, 0, 0, 0)","important");const r=new Map,i=o=>{!(o instanceof HTMLElement)||o===s.current||r.has(o)||(r.set(o,{opacity:o.style.opacity,pointerEvents:o.style.pointerEvents}),o.style.setProperty("opacity","0"),o.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(i);const c=new MutationObserver(o=>{o.forEach(d=>d.addedNodes.forEach(i))});return c.observe(document.body,{childList:!0}),()=>{c.disconnect(),r.forEach((o,d)=>{d.style.opacity=o.opacity,d.style.pointerEvents=o.pointerEvents}),n.value?document.documentElement.style.setProperty("background-color",n.value,n.priority):document.documentElement.style.removeProperty("background-color"),a.value?document.body.style.setProperty("background-color",a.value,a.priority):document.body.style.removeProperty("background-color"),Bi()}},[]),l.useEffect(()=>{const n=()=>{document.visibilityState==="hidden"&&t()};return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[t]),Vr.createPortal(e.jsxs("div",{ref:s,role:"dialog","aria-modal":"true","aria-label":"Scan QR code",className:"fixed inset-0 z-[1000] flex flex-col bg-transparent px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+24px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+24px)] text-foreground",children:[e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[e.jsx("div",{className:"aspect-square w-full max-w-72 rounded-[28px] border-2 border-foreground/90 shadow-[0_0_0_9999px_color-mix(in_srgb,var(--surface-background)_18%,transparent)]","aria-hidden":!0}),e.jsx("p",{className:"max-w-sm rounded-[16px] border border-border/60 bg-background px-4 py-3 text-center typography-body text-foreground shadow-sm",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}),e.jsxs(S,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:t,children:[e.jsx(M,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},yd=()=>Vr.createPortal(e.jsxs("div",{role:"status",className:"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-5 bg-background px-6 text-foreground",children:[e.jsx(ei,{width:96,height:96,isAnimated:!0}),e.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[e.jsx(M,{name:"loader-4",className:"size-[18px] animate-spin"}),e.jsx("span",{children:"Connecting..."})]})]}),document.body),wd=({className:t})=>{const[s,n]=l.useState(null);l.useEffect(()=>{let r=!1;const i=typeof AbortController<"u"?new AbortController:void 0;return(async()=>{try{const o=await Ae("/api/system/info",{signal:i?.signal,headers:{Accept:"application/json"}});if(!o.ok)return;const d=await o.json().catch(()=>null);if(!d||r)return;const m=typeof d.port=="number"&&Number.isFinite(d.port)&&d.port>0?d.port:null,p=typeof d.tunnelUrl=="string"&&d.tunnelUrl.trim().length>0?d.tunnelUrl.trim():null;n({port:m,tunnelUrl:p})}catch{}})(),()=>{r=!0,i?.abort()}},[]);const a=[];return s?.port!==null&&s?.port!==void 0&&a.push({key:"application",label:"Application",url:`http://localhost:${s.port}/`}),s?.tunnelUrl&&a.push({key:"tunnel",label:"Tunnel",url:s.tunnelUrl}),a.length===0?null:e.jsx("div",{className:U("flex flex-wrap items-center gap-2",t),children:a.map(r=>e.jsxs(S,{type:"button",variant:"outline",size:"sm",title:r.label,className:"max-w-full gap-1.5 px-2.5",onClick:()=>{ds(r.url)},children:[e.jsx(M,{name:"external-link",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"max-w-64 truncate font-mono typography-micro",children:r.url})]},r.key))})},Yn={stable:"Stable",rc:"Release candidate"},pr=({channel:t,disabled:s,label:n,onChange:a,className:r})=>e.jsxs(Be,{value:t,onValueChange:a,disabled:s,children:[e.jsx($e,{size:Ge,className:U(hs,r),"aria-label":n,children:e.jsx(We,{children:i=>Yn[cn(i)]})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"stable",children:Yn.stable}),e.jsx(ke,{value:"rc",children:Yn.rc})]})]}),jd=t=>{const[s,n]=l.useState(0),[a,r]=l.useState(0),[i,c]=l.useState("stable"),[o,d]=l.useState(!1),[m,p]=l.useState(t),[h,u]=l.useState(!1),[g,v]=l.useState(null),x=l.useRef(0);l.useEffect(()=>yn(()=>{x.current+=1,n(k=>k+1)}),[]),l.useEffect(()=>{const k=++x.current;if(!t){p(!1),v(null);return}d(!1),p(!0),u(!1),(async()=>{try{const P=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!P.ok)throw new Error("Unable to load the server update channel.");const E=await P.json().catch(()=>null);if(!E)throw new Error("Unable to load the server update channel.");x.current===k&&(c(cn(E.serverUpdateChannel)),d(!0),v(null))}catch(P){x.current===k&&v(P instanceof Error?P.message:"Unable to load the server update channel.")}finally{x.current===k&&p(!1)}})()},[t,s,a]);const b=l.useCallback(()=>r(k=>k+1),[]),j=l.useCallback(k=>{const P=cn(k),E=i,y=++x.current;c(P),u(!0),v(null),(async()=>{try{await Ie({serverUpdateChannel:P},{immediate:!0});const f=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!f.ok)throw new Error("Unable to save the server update channel.");if((await f.json().catch(()=>null))?.serverUpdateChannel!==P)throw new Error("Unable to save the server update channel.");x.current===y&&(wc(),Ds.getState().checkForUpdates())}catch(f){x.current===y&&(c(E),v(f instanceof Error?f.message:"Unable to save the server update channel."))}finally{x.current===y&&u(!1)}})()},[i]);return{channel:i,loaded:o,loading:m,saving:h,error:g,change:j,retry:b,runtimeEpoch:s}},kd="1.0.8-rc.3",mr={className:"flex-row items-center justify-between gap-3",labelClassName:"@xl:w-auto",controlClassName:"flex-none justify-end"},hr="w-44 min-w-0 max-w-none",fr=()=>{const t=xt().trim();return t?Jr(t):null},Nd={label:"Desktop app channel",ariaLabel:"Desktop app update channel",info:"Stable receives production desktop releases only. Release candidate offers the highest available version across stable and desktop RC builds. Switching to Stable changes future update eligibility and does not downgrade an installed RC.",settingsItem:"about.desktop-update-channel",load:Ho,save:Ko},Cd={label:"App channel",ariaLabel:"App update channel",info:"Stable receives production app releases only. Release candidate offers the highest available version across stable and app RC builds. Switching to Stable changes future update eligibility and does not downgrade an installed RC.",settingsItem:"about.app-update-channel",load:async()=>Al(kd),save:async t=>El(t)},Sd=()=>{const t=Oe(),s=t&&ts(),n=l.useMemo(()=>t?Nd:Re()?Cd:null,[t]),a=!s,r=jd(a),i=r.runtimeEpoch,[c,o]=l.useState(fr),[d,m]=l.useState("stable"),[p,h]=l.useState(n!==null),[u,g]=l.useState(!1),[v,x]=l.useState(null);if(l.useEffect(()=>{if(!a)return;const k=fr();if(o(k),!t)return;let P=!1;return Qr().then(E=>{if(P)return;const y=Qo(),f=Vo([Go(y),...E.hosts]),N=f.id===qo||f.id==="custom"?"":f.label.trim();o(N?Jr(N):k)}).catch(()=>{P||o(k)}),()=>{P=!0}},[t,a,i]),l.useEffect(()=>{if(!n)return;let k=!1;return h(!0),n.load().then(P=>{k||(m(P),x(null))}).catch(P=>{k||x(P instanceof Error?P.message:`Unable to load the ${n.ariaLabel.toLowerCase()}.`)}).finally(()=>{k||h(!1)}),()=>{k=!0}},[n]),!n&&!a)return null;const b=k=>{if(!n)return;const P=cn(k),E=d;m(P),g(!0),x(null),n.save(P).then(y=>{m(y),Ds.getState().reset(),Ds.getState().checkForUpdates()}).catch(y=>{m(E),x(y instanceof Error?y.message:`Unable to save the ${n.ariaLabel.toLowerCase()}.`)}).finally(()=>g(!1))},j=c?`Server update channel (${c})`:"Server update channel";return e.jsxs(q,{title:"Updates",children:[n?e.jsx(Ee,{label:n.label,info:n.info,description:v?e.jsx("span",{className:"text-[var(--status-error)]",children:v}):void 0,settingsItem:n.settingsItem,...mr,children:e.jsx(pr,{className:hr,channel:d,disabled:p||u,label:n.ariaLabel,onChange:b})}):null,a?e.jsx(Ee,{label:e.jsxs("span",{className:"@xl:whitespace-nowrap",children:["Server channel",c?e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" · ",c]}):null]}),info:"Stable receives production server releases only. Release candidate offers the highest available version across stable and server RC builds. Switching to Stable changes future update eligibility and does not downgrade an installed RC.",description:r.error?e.jsxs("span",{className:"flex flex-wrap items-center gap-x-2 text-[var(--status-error)]",children:[r.error,!r.loaded&&!r.loading?e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:r.retry,children:"Retry"}):null]}):void 0,settingsItem:"about.server-update-channel",...mr,children:e.jsx(pr,{className:hr,channel:r.channel,disabled:!r.loaded||r.loading||r.saving,label:j,onChange:r.change})}):null]})},$i="https://github.com/RyderAsKing/PiChamber",Wi="https://pi.dev/",Pd=800,Ki=({initialUpdateDialogOpen:t=!1})=>{const[s,n]=l.useState(t?"client":null),[a,r]=l.useState(!1),[i,c]=l.useState(null),o=Ds(Fo(f=>({info:f.info,serverInfo:f.serverInfo,checking:f.checking,available:f.available,error:f.error,lastChecked:f.lastChecked,downloading:f.downloading,downloaded:f.downloaded,progress:f.progress,runtimeType:f.runtimeType,checkForUpdates:f.checkForUpdates,downloadUpdate:f.downloadUpdate,restartToUpdate:f.restartToUpdate}))),d=Jo()&&!ts(),m=l.useMemo(()=>Re(),[]),p=d||m,h=i||o.info?.currentVersion||"unknown",u=o.info?.currentVersion||"1.0.8-rc.3",g=o.serverInfo?.currentVersion||i||"unknown",v=o.available,x=p&&(o.serverInfo?.available??!1),b=v||x,j=s==="server"?o.serverInfo:o.info,k=s==="server"?"web":o.runtimeType;l.useEffect(()=>{let f=!1;return(async()=>{try{const C=await Ae("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!C.ok)return;const w=await C.json().catch(()=>null),L=typeof w?.pichamberVersion=="string"&&w.pichamberVersion.trim().length>0?w.pichamberVersion.trim():null;f||c(L)}catch{f||c(null)}})(),()=>{f=!0}},[]);const P=l.useRef(!1);l.useEffect(()=>{if(o.checking)r(!0),P.current=!0;else if(a){const f=setTimeout(()=>{if(r(!1),P.current){const{info:N,serverInfo:C}=Ds.getState(),w=N!==null&&(!p||C!==null);!b&&!o.error&&w&&B.success("You are on the latest version"),P.current=!1}},Pd);return()=>clearTimeout(f)}},[o.checking,a,b,o.error,p]);const E=o.checking||a;let y=null;return E?y=e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(M,{name:"loader",className:"size-3.5 animate-spin","aria-hidden":"true"}),"Checking..."]}):p&&b?y=e.jsx("span",{className:"text-[var(--primary-base)]",children:"Updates available"}):b||(o.info!==null&&(!p||o.serverInfo!==null)&&!o.error?y=e.jsx("span",{children:"Up to date"}):(o.error||o.lastChecked!==null)&&(y=e.jsx("span",{children:"Check failed"}))),e.jsxs(e.Fragment,{children:[e.jsxs(q,{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 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 gap-1",children:[e.jsx("span",{className:Le,children:"Version"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 typography-meta text-muted-foreground",children:[p?e.jsxs(e.Fragment,{children:[e.jsx(gr,{label:"Client",version:u,updateInfo:o.info,onOpen:()=>n("client")}),e.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"·"}),e.jsx(gr,{label:"Server",version:g,updateInfo:o.serverInfo,onOpen:()=>n("server")})]}):e.jsx("span",{className:"font-mono",children:h}),y?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"·"}),y]}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-2 @xl:flex-row @xl:items-center",children:[!E&&!p&&o.available&&e.jsxs(S,{size:"sm",variant:"default",onClick:()=>n("client"),children:[e.jsx(M,{name:"download",className:"h-4 w-4 mr-1"}),`Update to ${o.info?.version||""}`]}),e.jsx(S,{size:"sm",variant:"outline",onClick:()=>o.checkForUpdates(),disabled:E,children:"Check for updates"})]})]}),o.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:o.error})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-b border-border/40 px-4 py-3",children:[e.jsx("span",{className:Le,children:"Instance URLs"}),e.jsx(wd,{className:"min-w-0 justify-end"})]}),e.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[e.jsxs("a",{href:$i,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(M,{name:"github-fill",className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:Wi,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(M,{name:"information",className:"h-4 w-4"}),e.jsx("span",{children:"Pi Agent"})]})]})]}),e.jsx(jc,{open:s!==null,onOpenChange:f=>{f||n(null)},info:j,downloading:s==="client"&&o.downloading,downloaded:s==="client"&&o.downloaded,progress:s==="client"?o.progress:null,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:k})]}),e.jsx(Sd,{}),e.jsx(Td,{})]})},gr=({label:t,version:s,updateInfo:n,onOpen:a})=>{if(!n?.available)return e.jsx("span",{className:"font-mono",children:`${t} ${s}`});const r=`Open ${t.toLowerCase()} updater${n.version?` for ${n.version}`:""}`;return e.jsxs(S,{variant:"ghost",size:"xs",onClick:a,className:"normal-case font-mono text-[var(--primary-base)]","aria-label":r,title:r,children:[e.jsx("span",{children:`${t} ${s}`}),e.jsx(M,{name:"arrow-up",className:"size-3.5","aria-hidden":"true"})]})},Td=()=>e.jsxs(e.Fragment,{children:[e.jsx(q,{title:"What is PiChamber",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(q,{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(q,{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:Wi,target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline underline-offset-4 hover:text-primary",children:"pi.dev"}),"."]})]})}),e.jsx(q,{title:"Special thanks",children:e.jsxs("div",{className:"max-w-2xl space-y-3 typography-ui text-muted-foreground",children:[e.jsxs("p",{children:["PiChamber is a community fork of"," ",e.jsx("a",{href:"https://github.com/openchamber/openchamber",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline underline-offset-4 hover:text-primary",children:"OpenChamber"})," ","by Bohdan Triapitsyn. We are grateful for the foundation and the required MIT attribution carried forward from that project."]}),e.jsx("p",{children:"Thank you to Pierre, the Pi community, xterm.js, and every contributor whose work, feedback, and ideas help make this project possible."})]})}),e.jsx(q,{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:$i,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"})]})})]}),Id=({onResolved:t})=>{const[s,n]=l.useState(!1),[a,r]=l.useState(!1);l.useEffect(()=>{let c=!0;return _e.getSettings({runtimeKey:qe()}).then(o=>{c&&n(o.pi.project.requiresTrust===!0)}).catch(()=>{}),()=>{c=!1}},[]);const i=async c=>{r(!0);try{const o=await _e.setPiSettings({scope:"project",trust:c},{runtimeKey:qe()});n(!1),wn(o)&&B.info(qt("Project trust")),t?.()}catch(o){const d=o instanceof Error&&o.message?o.message:"Failed to update project trust";jn(o)?B.info(Qt("Project trust")):B.error(d)}finally{r(!1)}};return e.jsx(bt,{open:s,onOpenChange:()=>{},children:e.jsxs(yt,{className:"max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Trust this project?"}),e.jsx(kt,{children:"This project contains Pi settings, skills, prompts, or extensions. Trusting it allows Pi to load those project resources."})]}),e.jsxs(ys,{children:[e.jsx(S,{variant:"ghost",size:"sm",disabled:a,onClick:()=>{i(!1)},children:"Keep untrusted"}),e.jsx(S,{size:"sm",disabled:a,onClick:()=>{i(!0)},children:"Trust project"})]})]})})},xe=({children:t,className:s,outerClassName:n,title:a,titleAbove:r,titleLeading:i,titleAccessory:c,description:o,headerEnd:d})=>{const m=a!=null||o!=null||d!=null,p=typeof a=="string"||typeof a=="number",h=i!=null||c!=null;return e.jsx(Ll,{useScrollShadow:!0,scrollShadowSize:16,outerClassName:U("h-full",n),className:"w-full @container",children:e.jsxs("div",{className:U("mx-auto max-w-[840px] space-y-0 px-6 py-5 @3xl:px-10 @3xl:py-7","[&>section:first-of-type]:border-t-0 [&>section:first-of-type]:pt-0",s),children:[m&&e.jsxs("div",{className:"mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-3 pb-6",children:[a!=null||o!=null?e.jsxs("div",{className:"min-w-0 flex-1 basis-64 space-y-1",children:[r!=null?e.jsx("div",{className:"mb-3",children:r}):null,a!=null?p?h?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i,e.jsx("h1",{className:U(ca,"min-w-0 truncate"),children:a}),e.jsx("span",{className:"shrink-0",children:c})]}):e.jsx("h1",{className:ca,children:a}):a:null,o!=null?typeof o=="string"||typeof o=="number"?e.jsx("p",{className:Hs,children:o}):o:null]}):null,d!=null?e.jsx("div",{className:"flex min-w-0 max-w-full shrink-0 flex-wrap items-center justify-end gap-3 [&>*]:min-w-0 [&>*]:max-w-full",children:d}):null]}),t]})})},Pn=({value:t,onChange:s,readOnly:n=!1,initialMode:a="preview",placeholder:r="Enter snippet text... Use markdown to format your snippet. It will expand as #name in the composer.",contentLabel:i="Snippet content",settingsItem:c,minHeight:o=220,hideExpandsNote:d=!1,triggerPreview:m,triggerActionLabel:p="Expands as",variableChips:h})=>{const[u,g]=l.useState(()=>n?"preview":a),v=t.trim().length>0;l.useEffect(()=>{n&&u==="write"&&g("preview")},[n,u,v]);const x=u==="write"&&!n,b=l.useRef(null),j=l.useCallback(k=>{const P=b.current?.selectionStart??t.length,E=b.current?.selectionEnd??t.length;s(t.slice(0,P)+k+t.slice(E)),requestAnimationFrame(()=>{const y=b.current;if(!y)return;y.focus();const f=P+k.length;y.setSelectionRange(f,f)})},[s,t]);return e.jsxs("div",{"data-settings-item":c,className:"overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/20 px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":u==="preview",onClick:()=>g("preview"),children:[e.jsx(M,{name:"eye",className:"size-3.5","aria-hidden":!0}),"Preview"]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":u==="write",disabled:n,onClick:()=>g("write"),className:U(n&&"opacity-50"),children:[e.jsx(M,{name:"edit",className:"size-3.5","aria-hidden":!0}),"Write"]})]}),n?e.jsx("span",{className:"hidden typography-micro text-muted-foreground @xl:inline",children:"Read-only"}):null]}),x?e.jsxs("div",{className:"p-0",children:[h&&h.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-border/60 bg-muted/20 px-3 py-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Variables"}),h.map(k=>e.jsx(S,{variant:"chip",size:"xs",onClick:()=>j(k.value),"aria-label":k.hint??`Insert ${k.value}`,title:k.hint??k.value,children:e.jsx("span",{className:"font-mono",children:k.label??k.value})},k.value))]}):null,e.jsx(Sa,{ref:b,value:t,onChange:k=>s(k.target.value),placeholder:r,simple:!0,fillContainer:!1,outerClassName:"border-0 ring-0 rounded-none bg-transparent",className:U("min-h-[220px] w-full bg-transparent px-3 py-3 font-mono typography-meta leading-6","placeholder:text-subtle-foreground"),style:{minHeight:o},"aria-label":i})]}):e.jsx("div",{className:"min-h-[220px] px-4 py-4 @xl:px-6",style:{minHeight:o},children:v?e.jsx(Na,{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(M,{name:"file-text",className:"size-6 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:n?"No content":"Nothing to preview"}),n?null:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Start writing in the Write tab to see a live preview."})]})}),n?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border/40 bg-muted/10 px-3 py-2 typography-micro text-muted-foreground",children:[!d&&m?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(M,{name:"information",className:"size-3.5 shrink-0 opacity-60","aria-hidden":!0}),p," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:m})," in the composer"]}):e.jsx("span",{}),e.jsxs("span",{className:"tabular-nums",children:[t.length," chars"]})]})]})},Ed=()=>{const{isMobile:t}=lt(),[s,n]=l.useState(null),[a,r]=l.useState({}),[i,c]=l.useState(null),[o,d]=l.useState(!1),m=l.useCallback(async()=>{const h=await _e.listResources({runtimeKey:qe()});n(h.agents),r(Object.fromEntries(h.agents.map(u=>[u.id,u.content??""]))),d(!1)},[]);l.useEffect(()=>{m().catch(()=>d(!0))},[m]);const p=async h=>{c(h.id);try{const u=await _e.updateResource({resourceId:h.id,content:a[h.id]??""},{runtimeKey:qe()});n(u.agents),r(Object.fromEntries(u.agents.map(g=>[g.id,g.content??""]))),wn(u)?B.info(qt("Behavior")):B.success("Behavior saved successfully")}catch(u){jn(u)?B.info(Qt("Behavior")):B.error("Failed to save behavior")}finally{c(null)}};return e.jsxs(e.Fragment,{children:[e.jsx(Id,{onResolved:()=>{m().catch(()=>d(!0))}}),e.jsxs(xe,{title:t?void 0:"Behavior",description:t?void 0:"Guide how the agent responds.",children:[o?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,(s??[]).map((h,u)=>{const g=a[h.id]??"",v=h.location==="global"?"Global AGENTS.md":`Project ${h.name}`,x=h.editable===!0,b=g!==(h.content??"");return e.jsxs(q,{title:v,divider:u>0,settingsItem:h.location==="global"?"behavior.global-agents":"behavior.project-agents",contentClassName:"space-y-3",info:x?"Markdown supported. Changes are saved immediately and applied when active sessions are idle.":"Read-only — this file is managed by a package or template.",children:[e.jsx(Pn,{value:g,onChange:j=>r(k=>({...k,[h.id]:j})),readOnly:!x,placeholder:x?"Describe how the agent should behave. Use markdown for structure.":void 0,settingsItem:h.location==="global"?"behavior.global-agents":"behavior.project-agents",hideExpandsNote:!0,minHeight:260}),x?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:b?"Unsaved changes":"No changes"}),e.jsx(S,{size:"xs",onClick:()=>{p(h)},disabled:i!==null||!b,children:i===h.id?"Saving...":"Save changes"})]}):null]},h.id)})]})]})},Ad=({skill:t,onSelect:s,showLocationPill:n=!0})=>{const a=t.location==="project"?"Project":t.location==="global"?"Global":t.location,r=t.description?.trim()||"No description";return e.jsxs("button",{type:"button",onClick:()=>s(t.name),"aria-label":`${t.name} skill, ${a}`,className:U("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[n?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:U("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:a})}):null,e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:t.name}),e.jsx("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:r})]})]})},Ld=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"h-5 w-16 animate-pulse rounded-full bg-muted"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-full animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-muted"})]})]},n))}),Md=()=>{const{isMobile:t}=lt(),s=Wt(C=>C.selectedSkillName),n=Wt(C=>C.setSelectedSkill),a=Wt(C=>C.skills),r=Wt(C=>C.isLoading),i=Wt(C=>C.loadSkills),[c,o]=l.useState(""),[d,m]=l.useState("all"),[p,h]=l.useState(!1),u=l.useMemo(()=>a.find(C=>C.name===s)??null,[a,s]),g=Wt(C=>C.updateSkillContent),[v,x]=l.useState(!1),[b,j]=l.useState(""),[k,P]=l.useState(!1);l.useEffect(()=>{u&&j(u.content??""),x(!1)},[u?.id,u?.content]);const E=l.useCallback(async()=>{if(!p){h(!0);try{const{invalidateSkillsLoadCache:C}=await Yt(async()=>{const{invalidateSkillsLoadCache:w}=await import("./useAppFontEffects-COMvkffC.js").then(L=>L.f3);return{invalidateSkillsLoadCache:w}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));C(),await i()}finally{h(!1)}}},[i,p]);l.useEffect(()=>{i()},[i]);const y=l.useMemo(()=>[...a].sort((C,w)=>{if(C.location!==w.location){if(C.location==="project")return-1;if(w.location==="project")return 1;if(C.location==="global")return-1;if(w.location==="global")return 1}return C.name.localeCompare(w.name,void 0,{sensitivity:"base"})}),[a]),f=l.useMemo(()=>{let C=y;d!=="all"&&(C=C.filter(L=>L.location===d));const w=c.trim().toLowerCase();return w?C.filter(L=>{const I=L.name.toLowerCase(),T=(L.description??"").toLowerCase();return I.includes(w)||T.includes(w)}):C},[y,d,c]),N=l.useMemo(()=>{let C=0,w=0;for(const L of a)L.location==="project"?C+=1:L.location==="global"&&(w+=1);return{all:a.length,project:C,global:w}},[a]);if(u){const C=u.location==="project"?"Project":u.location==="global"?"Global":u.location,w=typeof u.content=="string"&&u.content.trim().length>0,L=u.editable===!0,I=b!==(u.content??""),T=async()=>{if(!L||k)return;P(!0);const F=await g(u.name,b);P(!1),F?(B.success("Skill saved"),x(!1)):B.error("Failed to save skill")},A=()=>{j(u.content??""),x(!1)};return e.jsx(e.Fragment,{children:e.jsxs(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>n(null),"aria-label":"Back to skills",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{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:L&&!v?e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>x(!0),children:[e.jsx(M,{name:"edit",className:"size-3.5"}),"Edit"]}):void 0,children:[e.jsxs(q,{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:C}),L?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(M,{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"]})]}),L?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(q,{title:"Skill guide",settingsItem:"skills.content",info:v?"Markdown supported. Preview your changes before saving.":"Rendered from the SKILL.md markdown file discovered by Pi.",headerAction:L&&v?e.jsx("span",{className:"typography-micro text-muted-foreground",children:I?"Unsaved changes":"No changes"}):void 0,children:[v?e.jsxs(e.Fragment,{children:[e.jsx(Pn,{value:b,onChange:j,placeholder:"Write the skill guide in markdown...",hideExpandsNote:!0,minHeight:360}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-3",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:A,disabled:k,children:"Cancel"}),e.jsx(S,{size:"xs",onClick:()=>{T()},disabled:k||!I,children:k?"Saving...":"Save changes"})]})]}):w?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(Na,{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(M,{name:"book-open",className:"size-6 text-subtle-foreground","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."}),L?e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>x(!0),className:"mt-2",children:[e.jsx(M,{name:"edit",className:"size-3.5"}),"Add content"]}):null]}),L&&!v&&w?e.jsx("div",{className:"flex justify-end pt-3",children:e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>x(!0),children:[e.jsx(M,{name:"edit",className:"size-3.5"}),"Edit"]})}):null]})]})})}return r&&a.length===0?e.jsx(e.Fragment,{children:e.jsx(xe,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(M,{name:"refresh",className:U("size-4",p&&"animate-spin")})})}),children:e.jsx(q,{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(Ld,{count:6})})})})}):f.length===0&&c.trim()===""&&a.length===0?e.jsx(e.Fragment,{children:e.jsx(xe,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:c,onChange:C=>o(C.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-full pl-8"}),c?e.jsx("button",{type:"button",onClick:()=>o(""),"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(M,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(M,{name:"refresh",className:U("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(M,{name:"book-open",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No skills configured"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Skills appear here when Pi discovers SKILL.md files."})]})})}):e.jsx(e.Fragment,{children:e.jsx(xe,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:c,onChange:C=>o(C.target.value),placeholder:"Search skills","aria-label":"Search skills",className:"h-9 w-[18rem] max-w-full pl-8"}),c?e.jsx("button",{type:"button",onClick:()=>o(""),"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(M,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{E()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(M,{name:"refresh",className:U("size-4",p&&"animate-spin")})})]}),children:e.jsxs(q,{title:"Skills",divider:!1,settingsItem:"skills.discovery",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="all",onClick:()=>m("all"),children:["All ",N.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="project",onClick:()=>m("project"),children:["Project ",N.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="global",onClick:()=>m("global"),children:["Global ",N.global]})]}),f.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:c.trim()?`No skills match “${c}”.`:`No ${d} skills.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{o(""),m("all")},children:"Clear filters"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:f.map(C=>e.jsx(Ad,{skill:C,onSelect:n,showLocationPill:d==="all"},C.id))})]})})})},Rd=t=>{if(!t||typeof t!="object")return;const s=t.code;return typeof s=="string"?s:void 0},Dd=(t,s)=>{switch(t){case"PROJECT_UNTRUSTED":return"This project is not trusted, so Pi will not change its settings.";case"RESOURCE_NOT_FOUND":return`${s} is no longer there. The list has been read again.`;case"PACKAGE_NOT_CONFIGURED":return`${s} is no longer in Pi's settings.`;case"PACKAGE_REMOVE_FAILED":return`Pi could not remove ${s}. Its files may still be installed.`;case"PACKAGE_ALREADY_INSTALLED":return`${s} is already installed there.`;case"PACKAGE_INSTALL_FAILED":return`npm could not install ${s}. Check the server's network and try again.`;case"PACKAGE_UPDATE_FAILED":return`Pi could not update ${s}. The installed version stays.`;case"PACKAGE_PINNED":return`${s} is pinned to a version, so Pi does not update it.`;case"DAEMON_UNAVAILABLE":return`Pi did not answer in time. ${s} may still finish; the list will show it.`;case"PI_SETTINGS_INVALID":return"Pi's settings file could not be read or written.";default:return`${s} could not be saved.`}},Ws=(t,s)=>{if(t.ok){Te("saved"),t.deferred&&B.info(qt(s));return}if(Te("error"),jn(t.error)){B.info(Qt(s));return}B.error(Dd(Rd(t.error),s))},_a=(t,s,n)=>{if(!t.ok){Ws(t,s);return}Te("saved");const a=n==="install"?`Installed ${s}`:`Updated ${s}`;if(t.deferred){B.info(`${a}. Sessions pick it up when their turn ends.`);return}B.success(`${a}. New turns use it.`)};function gn({children:t,title:s,className:n}){return e.jsx("span",{title:s,className:U("inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",n),children:t})}function Hi(){return e.jsx("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:e.jsx(ei,{width:12,height:12})})}function Vi(){return e.jsxs(gn,{title:"Made for PiChamber and comes with it",children:[e.jsx(Hi,{}),"Native"]})}function Oa(){return e.jsxs(gn,{title:"Enhanced for PiChamber: adds features only PiChamber shows. It works in the terminal too.",children:[e.jsx(Hi,{}),"Enhanced"]})}const _d=t=>{const s=t.trim();return s.startsWith("npm:")?s.slice(4).trim().match(/^(@?[^@]+(?:\/[^@]+)?)(?:@.+)?$/)?.[1]:void 0},Vs=t=>t.kind==="npm"?_d(t.source)??t.name:void 0,Od={npm:"npm package",git:"Git package",local:"Local folder"},Gi=t=>[Od[t.kind],t.version?`v${t.version}`:null,t.pinned?"pinned":null].filter(Boolean).join(" · "),qi=t=>{const s=new Map;for(const{config:n,view:a}of t)for(const r of n?.packages??[]){const i=Vs(r);if(!i)continue;const c=s.get(i);c&&!(r.scope==="project"&&c.pkg.scope!=="project")||s.set(i,{pkg:r,view:a})}return s},xr=t=>{const[s,...n]=t.split("+")[0].split("-"),a=s.split(".").map(r=>Number.parseInt(r,10));if(!(a.length===0||a.some(r=>!Number.isFinite(r))))return{parts:a,prerelease:n.join("-")}},zd=(t,s)=>{const n=t.split("."),a=s.split(".");for(let r=0;r<Math.max(n.length,a.length);r+=1){const i=n[r],c=a[r];if(i===void 0)return-1;if(c===void 0)return 1;if(i===c)continue;const o=/^\d+$/.test(i),d=/^\d+$/.test(c);return o&&d?i.length!==c.length?i.length<c.length?-1:1:i<c?-1:1:o!==d?o?-1:1:i<c?-1:1}return 0},Ud=(t,s)=>{const n=xr(t),a=xr(s);if(!n||!a)return 0;for(let r=0;r<Math.max(n.parts.length,a.parts.length);r+=1){const i=(n.parts[r]??0)-(a.parts[r]??0);if(i!==0)return Math.sign(i)}return n.prerelease===a.prerelease?0:n.prerelease?a.prerelease?zd(n.prerelease,a.prerelease):-1:1},za=(t,s)=>{const n=Vs(t);if(!n||t.pinned||!t.installed||!t.version)return;const a=s[n];return a&&Ud(a,t.version)>0?a:void 0},vr=t=>t.toLowerCase().split(/[^a-z0-9]+/).filter(s=>s.length>=3),Fd=(t,s)=>{const n=vr(s);return n.length===0?[]:t.filter(a=>{if(!a.bundled)return!1;const r=[a.name,...a.keywords??[]].flatMap(vr);return n.some(i=>r.some(c=>c.startsWith(i)))})},Qi=t=>t<1e3?t.toLocaleString():t<1e4?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}k`:t<1e6?`${Math.round(t/1e3)}k`:`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`,Ji=(t,s,n)=>t?.replaced?.find(a=>a.kind===s&&a.id===n),Yi=t=>t.by?`Not loaded: ${t.by.name} takes its place`:"Not loaded: another extension takes its place",Bd=t=>{if(!t.registers)return"the same tool, command, or flag";const{kind:s,name:n}=t.registers;return s==="command"?`the /${n} command`:s==="flag"?`the --${n} flag`:`the ${n} tool`},$d=t=>`Pi loads ${t.by?.name??"another extension"} instead. Both register ${Bd(t)}, and Pi keeps only one.`,Wd=(t,s)=>{const n=s.by?.id;if(!t||!n)return null;const a=t.extensions.find(r=>r.id===n);return a?a.global!==void 0?!a.global||a.project?.state==="load"?null:{id:a.id,name:a.name,scope:"global"}:a.scope==="project"&&a.project?.enabled&&t.project.trusted&&t.directory?{id:a.id,name:a.name,scope:"project"}:null:null},Kd=(t,s)=>{const n=new Map,a=new Map(t.extensions.map(r=>[r.id,r.name]));for(const r of t.replaced??[]){const i=r.kind==="plugin"?s[r.id]&&`the ${s[r.id]} plugin`:a.get(r.id)&&`Pi's ${a.get(r.id)}`;if(!i)continue;r.kind==="builtin"&&n.set(r.id,{text:Yi(r),warning:!0});const c=r.by?.id;c&&a.has(c)&&!n.has(c)&&n.set(c,{text:`Loaded in place of ${i}`,warning:!1})}return n};function bs(t){const s=Je(r=>r.entries[t?.trim()??""]),n=Je(r=>r.load);l.useEffect(()=>{if(n(t),typeof window>"u"||typeof document>"u")return;const r=()=>{document.visibilityState!=="hidden"&&n(t)};return document.addEventListener("visibilitychange",r),window.addEventListener("focus",r),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("focus",r)}},[t,n]);const a=s?.status==="ready"&&s.loadedAt===0;return l.useEffect(()=>{a&&n(t)},[a,t,n]),s}const Hd="Extensions are code Pi loads into every session. This is the list the pi config command shows, and it writes the same settings, so a change here also applies in the terminal. It changes Pi on the machine that runs the PiChamber server.",Vd="These ship with Pi. Its llama.cpp provider is built in too, but PiChamber does not load it, so it is not listed.",Gd={mcp:"Connects MCP servers and offers their tools",codemode:"Lets the model run a script that calls the other tools","tool-search":"Lets the model find tools that are not declared to it"},Xi=(t,s)=>s==="project"?t.project?.enabled??t.global??!1:t.global??!1,Zi=(t,s)=>`${t.filter(n=>Xi(n,s)).length} of ${t.length} on`;function Xn({title:t,items:s,view:n}){return e.jsxs(e.Fragment,{children:[t,s.length>0?e.jsx("span",{className:"ml-2 typography-micro font-normal tabular-nums text-muted-foreground",children:Zi(s,n)}):null]})}function eo({item:t,view:s,directory:n,readOnly:a,notes:r}){const i=Je(u=>u.setGlobal),c=Je(u=>u.setProjectEnabled),o=Je(u=>u.pending[t.id]===!0),d=Xi(t,s),m=d?r.get(t.id):void 0;let p=null;a?p=e.jsx("span",{className:Tt,children:d?"On":"Off"}):s==="project"&&t.project&&n?p=e.jsx(la,{checked:t.project.enabled,disabled:o,ariaLabel:`${t.name} in this project`,onChange:u=>{Te("saving"),c(t.id,u,n).then(g=>Ws(g,t.name))}}):s==="global"&&t.global!==void 0&&(p=e.jsx(la,{checked:t.global,disabled:o,ariaLabel:t.name,onChange:u=>{Te("saving"),i(t.id,u).then(g=>Ws(g,t.name))}}));let h;return m?h=e.jsx("p",{className:U("line-clamp-2 text-pretty typography-meta",m.warning?"text-[var(--status-warning)]":"text-muted-foreground"),children:m.text}):s==="project"&&t.project&&t.scope!=="project"&&t.project.enabled!==t.project.inherited?h=t.project.enabled?"On in this project only":"Off in this project only":t.group==="builtin"?h=Gd[t.name]:t.group==="settings"&&(h="Listed in Pi's settings"),e.jsx(Ve,{title:t.name,dimmed:!d,detail:h,trailing:p})}function Zn({items:t,...s}){return e.jsx(rt,{children:t.map(n=>e.jsx(eo,{item:n,...s},n.id))})}function qd({pkg:t,items:s,onRemove:n,onOpenPackage:a,...r}){const{view:i,readOnly:c,directory:o}=r,d=Je(P=>P.pending[t.id]===!0),m=Je(P=>P.updatePackage),p=St(P=>P.latest),h=!c&&t.scope===(i==="project"?"project":"user"),u=h?za(t,p):void 0,[g,v]=l.useState(null),x=t.scope==="project"?"This project":i==="project"?"Global":null,b=[Gi(t),x,s.length>0?Zi(s,i):null].filter(Boolean).join(" · "),j=Vs(t),k=()=>{v("update"),Te("saving"),m(t.id,t.scope==="project"?o:null).then(P=>{v(null),_a(P,j??t.source,"update")})};return e.jsxs(rt,{children:[e.jsx(Ve,{heading:!0,title:j?e.jsx("button",{type:"button",onClick:()=>a(j),"aria-label":`${j} details`,className:"truncate typography-ui-label font-medium text-foreground underline-offset-4 outline-none hover:underline focus-visible:underline",children:j}):t.source,titleAccessory:t.pichamber?e.jsx(Oa,{}):null,detail:e.jsxs("p",{className:U(Tt,"line-clamp-2 text-pretty"),children:[b,t.installed?null:e.jsx("span",{className:"text-[var(--status-warning)]",children:" · Not installed"})]}),trailing:h?e.jsxs(e.Fragment,{children:[u?e.jsx(S,{variant:"outline",size:"xs",disabled:d,onClick:k,"aria-label":`Update ${t.source} to ${u}`,children:d&&g==="update"?"Updating…":`Update to ${u}`}):null,e.jsx(S,{variant:"outline",size:"xs",disabled:d,"aria-label":`Remove ${t.source}`,onClick:()=>{v("remove"),n(t)},children:d&&g!=="update"?"Removing…":"Remove"})]}):void 0}),s.length===0?e.jsx("li",{className:U(Tt,"px-3.5 py-2.5"),children:t.installed?"No extensions in this package.":"Pi cannot load it until it is installed again."}):s.map(P=>e.jsx(eo,{item:P,...r},P.id))]})}function Qd({pkg:t,directory:s,onClose:n}){const a=Je(h=>h.removePackage),[r,i]=l.useState(!1),[c,o]=l.useState(t);l.useEffect(()=>{t&&o(t)},[t]);const d=async()=>{if(!t)return;i(!0),Te("saving");const h=await a(t.id,t.scope==="project"?s:null);i(!1),Ws(h,t.source),n()},m=c?.scope==="project"?"in this project":"in every project",p=c?.kind==="local"?"The folder itself stays where it is.":"Its installed files are deleted.";return e.jsx(bt,{open:t!==null,onOpenChange:h=>{!h&&!r&&n()},children:e.jsxs(yt,{className:"max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Remove package?"}),e.jsx(kt,{children:`Pi stops loading ${c?.source??"this package"} ${m}. ${p}`})]}),e.jsxs(ys,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:n,disabled:r,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{d()},disabled:r,children:r?"Removing…":"Remove"})]})]})})}function Jd({config:t,onRemove:s,onBrowse:n,onOpenPackage:a,...r}){const{view:i}=r,c=new Map,o=[],d=[],m=[];for(const h of t.extensions)h.group==="builtin"?m.push(h):h.group==="package"&&h.packageId?c.set(h.packageId,[...c.get(h.packageId)??[],h]):h.scope==="project"?d.push(h):o.push(h);const p=[...t.packages].sort((h,u)=>+(h.scope==="project")-+(u.scope==="project"));return e.jsxs("div",{className:"space-y-5",children:[e.jsx(at,{title:"Packages",settingsItem:"plugins.extensions.packages",contentClassName:"space-y-2",children:p.length>0?p.map(h=>e.jsx(qd,{pkg:h,items:c.get(h.id)??[],onRemove:s,onOpenPackage:a,...r},h.id)):e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("p",{className:U(he,"text-pretty"),children:"None installed yet."}),e.jsx(S,{variant:"link",size:"xs",className:"h-auto px-0 underline underline-offset-4",onClick:n,children:"Browse Pi packages"})]})}),e.jsx(at,{title:e.jsx(Xn,{title:i==="project"?"Global extensions":"Your extensions",items:o,view:i}),settingsItem:"plugins.extensions.own",children:o.length>0?e.jsx(Zn,{items:o,...r}):e.jsx("p",{className:U(he,"text-pretty"),children:p.length>0?"None outside packages.":"None yet. Pi loads the files in its extensions folder."})}),i==="project"&&d.length>0?e.jsx(at,{title:e.jsx(Xn,{title:"This project's extensions",items:d,view:i}),children:e.jsx(Zn,{items:d,...r})}):null,m.length>0?e.jsx(at,{title:e.jsx(Xn,{title:"Built into Pi",items:m,view:i}),info:Vd,settingsItem:"plugins.extensions.builtin",children:e.jsx(Zn,{items:m,...r})}):null]})}function Yd({directory:t,pluginNames:s,onBrowse:n,onOpenPackage:a}){const[r,i]=l.useState("global"),c=r==="project"&&t?"project":"global",o=c==="project"?t:null,d=bs(o),m=Je(j=>j.load),[p,h]=l.useState(null),u=d?.config??null,g=c==="project"&&u!==null&&!u.project.trusted,v=St(j=>j.loadVersions),x=(u?.packages??[]).filter(j=>j.installed&&!j.pinned&&j.version).map(Vs).filter(j=>!!j).sort().join(",");l.useEffect(()=>{x&&v(x.split(","))},[x,v]);let b;return!u&&d?.status==="error"?b=e.jsx(ft,{title:"Could not load Pi's extensions from the server",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{m(o,{force:!0})},children:"Try again"})}):u?b=e.jsxs("div",{className:"space-y-4",children:[d?.status==="error"?e.jsx(ft,{title:"Could not refresh this list",children:"It may be out of date."}):null,g?e.jsx(ft,{title:"Pi does not trust this project",children:"So it leaves out the project's own extensions and settings. This is the global list. Change it under Global, or trust the project to choose what loads here."}):null,u.installFailures.map(j=>e.jsx(ft,{title:`Pi could not load ${j.source}`,children:j.message},j.source)),e.jsx(Jd,{config:u,view:g?"global":c,readOnly:g,directory:o,notes:Kd(u,s),onRemove:h,onBrowse:n,onOpenPackage:a})]}):b=e.jsx("p",{className:he,children:"Loading extensions…"}),e.jsxs(q,{title:"Pi extensions",info:Hd,settingsItem:"plugins.extensions",headerAction:t?e.jsx(Os,{"aria-label":"Extension settings for",value:c,onChange:i,options:[{value:"global",label:"Global"},{value:"project",label:"This project"}]}):void 0,children:[b,e.jsx(Qd,{pkg:p,directory:o,onClose:()=>h(null)})]})}const Xd=t=>{const s=t.replace(/[\\/]+$/,"").split(/[\\/]/);return s[s.length-1]||t};function Zd({name:t,directory:s,projectTrusted:n,onClose:a}){const r=Je(u=>u.installPackage),[i,c]=l.useState("user"),[o,d]=l.useState(t);l.useEffect(()=>{t&&(d(t),c("user"))},[t]);const m=!!s&&n===!0,p=()=>{if(!t)return;const u=i==="project"&&m?s:null;a(),Te("saving"),r(t,u).then(g=>_a(g,t,"install"))};let h;return s&&n===!1?h="Pi does not trust this project, so it cannot install here.":s&&n===void 0&&(h="Checking this project…"),e.jsx(bt,{open:t!==null,onOpenChange:u=>{u||a()},children:e.jsxs(yt,{className:"max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{className:"break-all",children:`Install ${o??"package"}?`}),e.jsx(kt,{className:"text-pretty",children:"A Pi package runs as code on the machine that runs PiChamber, with the same access as Pi. Install only packages you trust."})]}),s?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:Le,children:"Load it in"}),e.jsxs(_t,{"aria-label":"Where to install",children:[e.jsx(fs,{selected:i==="user",onSelect:()=>c("user"),label:"Every project"}),e.jsx(fs,{selected:i==="project",onSelect:()=>c("project"),disabled:!m,label:`This project only (${Xd(s)})`,description:h})]})]}):null,e.jsxs(ys,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:a,children:"Cancel"}),e.jsx(S,{variant:"solid",size:"sm",onClick:p,children:"Install"})]})]})})}const eu={extensions:"Extensions",skills:"Skills",prompts:"Prompt templates",themes:"Themes"},tu={extensions:"Code Pi runs in every session: tools, commands, and hooks",skills:"Instructions the agent can load when a task needs them",prompts:"Saved prompts you start with a slash command",themes:"Colours for Pi in the terminal"};function ls({children:t}){return e.jsx("span",{className:U(Tt,"min-w-0 truncate text-right tabular-nums"),children:t})}function ea({title:t,url:s}){return e.jsx(Ve,{interactive:!0,title:e.jsx("button",{type:"button",onClick:()=>{ds(s)},className:U("truncate typography-ui-label text-foreground outline-none","after:absolute after:inset-0 after:content-['']","focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-[var(--interactive-focus-ring)]"),children:t}),trailing:e.jsxs(e.Fragment,{children:[e.jsx(ls,{children:s.replace(/^https?:\/\//,"")}),e.jsx(M,{name:"external-link","aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})})}const su=t=>new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});function nu({name:t,directory:s,backLabel:n,onBack:a,onInstall:r}){const i=St(N=>N.details[t]),c=St(N=>N.latest),o=St(N=>N.loadDetail),d=Je(N=>N.pending),m=Je(N=>N.updatePackage),p=bs(null)?.config,h=bs(s)?.config;l.useEffect(()=>{o(t)},[t,o]);const u=qi([{config:p,view:"global"},...s?[{config:h,view:"project"}]:[]]).get(t),g=i?.data??null,v=u?za(u.pkg,c):void 0,x=d[pi(t)]===!0,b=u?d[u.pkg.id]===!0:!1,j=e.jsxs(S,{variant:"ghost",size:"xs",onClick:a,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(M,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),n]}),k=()=>{u&&(Te("saving"),m(u.pkg.id,u.pkg.scope==="project"?s:null).then(N=>_a(N,t,"update")))};let P;x?P=e.jsx(S,{variant:"solid",size:"sm",disabled:!0,children:"Installing…"}):u&&v?P=e.jsx(S,{variant:"outline",size:"sm",disabled:b,onClick:k,children:b?"Updating…":`Update to ${v}`}):u||(P=e.jsx(S,{variant:"solid",size:"sm",onClick:()=>r(t),children:"Install"}));let E="Not installed",y;u?(E=u.pkg.scope==="project"?"Installed in this project":"Installed in every project",y=Gi(u.pkg)||void 0):x&&(E="Installing",y="npm is downloading it. This can take a minute.");let f;return!g&&i?.status==="error"?f=e.jsx(ft,{title:"Could not load this package from npm",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{o(t,{force:!0})},children:"Try again"}),children:"It may have been removed, or the PiChamber server cannot reach npm."}):g?f=e.jsxs(e.Fragment,{children:[g.isPiPackage?null:e.jsx(ft,{className:"mb-3",title:"Not marked as a Pi package",children:"It lacks the pi-package keyword, so Pi may find nothing to load in it."}),e.jsx(q,{divider:!1,title:"What it adds to Pi",children:g.contains.length>0?e.jsx(rt,{children:g.contains.map(N=>e.jsx(Ve,{title:eu[N],detail:tu[N]},N))}):e.jsx("p",{className:U(he,"text-pretty"),children:"Its package.json does not say. Pi loads what it finds in the package's extensions, skills, prompts, and themes folders."})}),e.jsx(q,{title:"In PiChamber",children:e.jsx("p",{className:U(he,"text-pretty"),children:g.pichamber?"Enhanced for PiChamber: built with the PiChamber plugin SDK to add features only PiChamber shows. PiChamber does not load those extras from packages it does not ship yet, so for now it runs as a plain Pi package, here and in the terminal.":"A plain Pi package. It works in PiChamber as it does in the terminal."})}),e.jsx(q,{title:"About",children:e.jsxs(rt,{children:[g.version?e.jsx(Ve,{title:"Latest version",trailing:e.jsx(ls,{children:g.version})}):null,g.date?e.jsx(Ve,{title:"Published",trailing:e.jsx(ls,{children:su(g.date)})}):null,g.publisher?e.jsx(Ve,{title:"Maintainer",trailing:e.jsx(ls,{children:g.publisher})}):null,g.license?e.jsx(Ve,{title:"License",trailing:e.jsx(ls,{children:g.license})}):null,g.weeklyDownloads!==void 0?e.jsx(Ve,{title:"Downloads",trailing:e.jsx(ls,{children:`${Qi(g.weeklyDownloads)} a week`})}):null]})}),e.jsx(q,{title:"Links",children:e.jsxs(rt,{children:[e.jsx(ea,{title:"npm",url:g.links.npm}),g.links.repository?e.jsx(ea,{title:"Source code",url:g.links.repository}):null,g.links.homepage?e.jsx(ea,{title:"Homepage",url:g.links.homepage}):null]})})]}):f=e.jsx("p",{className:he,children:"Loading from npm…"}),e.jsxs(xe,{title:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("h1",{className:U(ca,"min-w-0 break-all"),children:t}),g?.pichamber?e.jsx(Oa,{}):null]}),titleAbove:j,description:g?.description?e.jsx("p",{className:U(Hs,"text-pretty"),children:g.description}):void 0,children:[e.jsx(rt,{className:"mb-6",children:e.jsx(Ve,{title:E,detail:y,trailing:P})}),f]})}function to(){return l.useCallback(async t=>{Te("saving");const s=await t();return Te(s?"saved":"error"),s},[])}const br=(t,s,n)=>t===1?`1 ${s}`:`${t} ${n}`,au=t=>{if(!t||t.tools.length===0&&t.commands.length===0&&t.hooks.length===0)return"Adds nothing to the agent";const s=[];t.tools.length>0&&s.push(br(t.tools.length,"tool","tools")),t.commands.length>0&&s.push(br(t.commands.length,"command","commands")),t.hooks.length>0&&s.push("changes requests");const n=t.tools.reduce((a,r)=>a+r.tokens,0);return n>0&&s.push(`about ${n.toLocaleString()} tokens per request`),s.join(" · ")};function so({plugin:t,className:s}){const n=_s(i=>i.setEnabled),a=_s(i=>i.pending[t.id]===!0),r=to();return e.jsx(la,{checked:t.enabled,disabled:a,ariaLabel:t.name,className:s,onChange:i=>{r(()=>n(t.id,i)).then(c=>{c&&Je.getState().invalidate()})}})}function no({plugin:t}){return e.jsx(M,{name:Ml(t.icon),"aria-hidden":"true",className:U("size-5 shrink-0",t.enabled?"text-foreground":"text-muted-foreground")})}const ru=t=>t.impactError?"Could not measure what it adds to the agent":au(t.impact);function ao({plugin:t,replacement:s,showNativeTag:n=!0,onOpen:a}){return e.jsx(Ve,{interactive:!0,settingsItem:`plugins.${t.id}`,className:"items-start py-3",leading:e.jsx(no,{plugin:t}),title:e.jsx("button",{type:"button",onClick:a,"aria-label":`${t.name} settings`,className:U("truncate typography-ui-label font-medium text-foreground outline-none","after:absolute after:inset-0 after:content-['']","focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-[var(--interactive-focus-ring)]"),children:t.name}),titleAccessory:t.bundled&&n?e.jsx(Vi,{}):null,detail:e.jsxs(e.Fragment,{children:[e.jsx("p",{className:U(Tt,"line-clamp-2 text-pretty"),children:t.description}),s?e.jsx("p",{className:"truncate typography-meta text-[var(--status-warning)]",children:Yi(s)}):e.jsx("p",{className:"truncate typography-micro tabular-nums text-muted-foreground",children:t.enabled?ru(t):"Off: adds nothing to the agent"})]}),trailing:e.jsxs(e.Fragment,{children:[e.jsx(so,{plugin:t,className:"relative z-10"}),e.jsx(M,{name:"arrow-right-s","aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})})}const iu=300,yr="Pi packages are npm packages with the pi-package keyword, the same list as the Pi package gallery. Searches go from the PiChamber server to npm. Featured picks come from the PiChamber project.",ou="Every Pi package works in PiChamber. These also add features only PiChamber shows, built with the PiChamber plugin SDK. Their authors mark them with the pichamber-plugin keyword; a package's page checks its package.json.",lu=t=>[t.version?`v${t.version}`:null,t.publisher?`by ${t.publisher}`:null,t.weeklyDownloads!==void 0?`${Qi(t.weeklyDownloads)} a week`:null].filter(Boolean).join(" · "),cu=(t,s)=>[t.pkg.scope==="project"?"Installed in this project":"Installed",s&&za(t.pkg,{[Vs(t.pkg)??""]:s})?"update available":null].filter(Boolean).join(" · ");function du({pkg:t,installed:s,installing:n,onOpen:a,onInstall:r}){const i=t.unavailable?"npm did not answer for this package":lu(t),c=t.note??t.description;let o;return n?o=e.jsx(S,{variant:"outline",size:"xs",disabled:!0,className:"relative z-10",children:"Installing…"}):s?o=e.jsx("span",{className:U(Tt,"shrink-0"),children:cu(s,t.version)}):o=e.jsx(S,{variant:"outline",size:"xs",className:"relative z-10","aria-label":`Install ${t.name}`,onClick:r,children:"Install"}),e.jsx(Ve,{interactive:!0,className:"items-start py-3",title:e.jsx("button",{type:"button",onClick:a,"aria-label":`${t.name} details`,className:U("truncate typography-ui-label font-medium text-foreground outline-none","after:absolute after:inset-0 after:content-['']","focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-[var(--interactive-focus-ring)]"),children:t.name}),titleAccessory:t.pichamberKeyword?e.jsx(Oa,{}):null,detail:e.jsxs(e.Fragment,{children:[c?e.jsx("p",{className:U(Tt,"line-clamp-2 text-pretty"),children:c}):null,i?e.jsx("p",{className:"truncate typography-micro tabular-nums text-muted-foreground",children:i}):null]}),trailing:o})}function wr({packages:t,installed:s,onOpenPackage:n,onInstall:a}){const r=Je(i=>i.pending);return e.jsx(rt,{children:t.map(i=>e.jsx(du,{pkg:i,installed:s.get(i.name),installing:r[pi(i.name)]===!0,onOpen:()=>n(i.name),onInstall:()=>a(i.name)},i.name))})}function uu(t,s){const[n,a]=l.useState(t);return l.useEffect(()=>{if(t.trim()===""){a(t);return}const r=window.setTimeout(()=>a(t),s);return()=>window.clearTimeout(r)},[t,s]),n}function pu({plugins:t,directory:s,query:n,onQueryChange:a,filter:r,onFilterChange:i,onBack:c,onOpenPackage:o,onOpenPlugin:d,onInstall:m}){const p=uu(n,iu).trim(),h=r==="pichamber",u=St(T=>T.featured),g=St(T=>T.loadFeatured),v=St(T=>T.search),x=St(T=>T.searches[kc(p,h)]),b=bs(null)?.config,j=bs(s)?.config,k=l.useMemo(()=>qi([{config:b,view:"global"},...s?[{config:j,view:"project"}]:[]]),[b,j,s]),P=p===""&&!h;l.useEffect(()=>{P&&g()},[P,g]),l.useEffect(()=>{v(p,h)},[p,h,v]);const E=Fd(t,p),y=new Set(P?(u.data?.packages??[]).map(T=>T.name):[]),f=(x?.packages??[]).filter(T=>!y.has(T.name));let N;if(!x||x.status==="loading"&&x.packages.length===0)N=e.jsx("p",{className:he,children:p?"Searching npm…":"Loading packages from npm…"});else if(x.status==="error"&&x.packages.length===0)N=e.jsx(ft,{title:"Could not reach npm",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{v(p,h,{force:!0})},children:"Try again"}),children:"The PiChamber server could not get the package list. Check its network connection."});else if(f.length===0){let T;h?T=p?`No packages that support PiChamber match “${p}”.`:"No packages say they support PiChamber yet.":T=p?`No Pi packages match “${p}”.`:"npm listed no Pi packages.",N=e.jsx("p",{className:U(he,"text-pretty"),children:T})}else N=e.jsxs("div",{className:"space-y-3",children:[x.status==="error"?e.jsx(ft,{title:"Could not refresh these results",children:"They may be out of date."}):null,e.jsx(wr,{packages:f,installed:k,onOpenPackage:o,onInstall:m}),x.nextFrom!==null?e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3",children:[x.moreFailed?e.jsx("span",{className:he,children:"Could not load more."}):null,e.jsx(S,{variant:"ghost",size:"sm",disabled:x.loadingMore,onClick:()=>{v(p,h,{more:!0})},children:x.loadingMore?"Loading…":x.moreFailed?"Try again":"Show more"})]}):null]});const C=p?"Results":h?"Enhanced for PiChamber":"Popular",w=!p&&x?.total!==void 0&&!h?e.jsx("span",{className:"typography-micro tabular-nums text-muted-foreground",children:`${x.total.toLocaleString()} Pi packages`}):null;let L=0;const I=()=>(L+=1,L>1);return e.jsxs(xe,{title:"Browse",titleAbove:e.jsxs(S,{variant:"ghost",size:"xs",onClick:c,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(M,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),"Extensions & Plugins"]}),description:e.jsx("p",{className:U(Hs,"text-pretty"),children:"Pi packages from npm. Pi loads an installed package here and in the terminal."}),children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative w-full min-w-0 max-w-[24rem]",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:n,onChange:T=>a(T.target.value),placeholder:"Search Pi packages","aria-label":"Search Pi packages",className:"h-9 w-full pl-8 pr-8",autoFocus:!0}),n?e.jsx("button",{type:"button",onClick:()=>a(""),"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(M,{name:"close",className:"size-4"})}):null]}),e.jsx(Os,{"aria-label":"Show packages",value:r,onChange:i,options:[{value:"all",label:"All"},{value:"pichamber",label:"Enhanced for PiChamber"}]})]}),E.length>0?e.jsx(q,{divider:I(),title:"Built into PiChamber",description:"Already here. Turn it on; there is nothing to install.",children:e.jsx(rt,{children:E.map(T=>e.jsx(ao,{plugin:T,onOpen:()=>d(T.id)},T.id))})}):null,P?e.jsx(q,{divider:I(),title:"Featured",info:yr,children:u.data&&u.data.packages.length>0?e.jsx(wr,{packages:u.data.packages,installed:k,onOpenPackage:o,onInstall:m}):u.status==="error"?e.jsx("p",{className:he,children:"Could not load the featured packages."}):u.data?e.jsx("p",{className:he,children:"Nothing is featured right now."}):e.jsx("p",{className:he,children:"Loading…"})}):null,e.jsx(q,{divider:I(),title:C,titleAccessory:w,info:h?ou:P?void 0:yr,children:N})]})}const mu="Plugins that come with PiChamber. Plugins you install from Browse are Pi packages and show under Pi extensions, Packages. Built-in plugins start off, and a plugin that is off adds nothing to the agent.",hu="Measured by loading the plugin's agent code. Tools are described to the model on every request while the plugin is on. A plugin that is off adds nothing.",fu=[{id:"all",label:"All"},{id:"on",label:"On"},{id:"off",label:"Off"}],gu=7;function xu({plugins:t,config:s,onOpen:n}){const[a,r]=l.useState("all"),i={all:t.length,on:t.filter(o=>o.enabled).length,off:t.filter(o=>!o.enabled).length},c=t.filter(o=>a==="all"||(a==="on"?o.enabled:!o.enabled));return e.jsxs(q,{divider:!1,title:"Native plugins",info:mu,contentClassName:"space-y-3",children:[t.length>=gu?e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",role:"group","aria-label":"Show plugins",children:fu.map(({id:o,label:d})=>e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":a===o,onClick:()=>r(o),children:[d,e.jsx("span",{className:"tabular-nums text-muted-foreground",children:i[o]})]},o))}):null,c.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-xl border border-dashed border-border/60 py-10 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:a==="on"?"No plugins are on.":"Every plugin is on."}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>r("all"),children:"Show all"})]}):e.jsx(rt,{children:c.map(o=>e.jsx(ao,{plugin:o,replacement:o.enabled?Ji(s,"plugin",o.id):void 0,showNativeTag:!1,onOpen:()=>n(o.id)},o.id))})]})}function vu({plugin:t,directory:s,disabled:n}){const a=_s(m=>m.setState),r=_s(m=>m.pending),i=to(),o=(t.contributes.settings??Object.keys(t.stateSchema)).flatMap(m=>{const p=t.stateSchema[m];return p?p.scope==="project"&&!s?[]:[{key:m,field:p}]:[]});if(o.length===0)return null;const d=(m,p)=>{i(()=>a(t.id,m,p,s))};return e.jsx("div",{className:vt,children:o.map(({key:m,field:p})=>{const h=t.state[m]??p.default,u=n||r[`${t.id}
3
+ ${m}`]===!0,g=p.scope==="project"?`${p.label} (this project)`:p.label,v=`plugins.${t.id}.${m}`;return p.type==="boolean"?e.jsx(ve,{checked:h===!0,onChange:x=>d(m,x),label:g,ariaLabel:p.label,info:p.description,disabled:u,settingsItem:v},m):e.jsx(Ee,{label:g,info:p.description,settingsItem:v,children:e.jsxs(Be,{value:String(h),onValueChange:x=>d(m,x),disabled:u,children:[e.jsx($e,{size:Ge,className:hs,"aria-label":p.label,children:e.jsx(We,{children:(p.options??[]).find(x=>x.value===String(h))?.label??String(h)})}),e.jsx(Ke,{children:(p.options??[]).map(x=>e.jsx(ke,{value:x.value,children:x.label},x.value))})]})},m)})})}const bu=(t,s)=>(t.contributes.settings??Object.keys(t.stateSchema)).some(n=>{const a=t.stateSchema[n];return!!a&&(a.scope!=="project"||!!s)});function pa({children:t}){return e.jsx("span",{className:U(Tt,"min-w-0 text-right tabular-nums"),children:t})}function yu({impact:t,error:s}){return s?e.jsx(ft,{title:"Could not measure what this plugin adds to the agent"}):!t||t.tools.length===0&&t.commands.length===0&&t.hooks.length===0?e.jsx("p",{className:he,children:"Nothing. This plugin only changes PiChamber."}):e.jsxs(rt,{children:[t.tools.map(a=>e.jsx(Ve,{mono:!0,title:a.name,titleAccessory:e.jsx(gn,{children:"Tool"}),stackTrailing:!0,trailing:e.jsx(pa,{children:a.exposure==="direct"?`About ${a.tokens.toLocaleString()} tokens per request`:"Loaded when the model asks for it"})},a.name)),t.commands.map(a=>e.jsx(Ve,{mono:!0,title:`/${a}`,titleAccessory:e.jsx(gn,{children:"Command"})},a)),t.hooks.length>0?e.jsx(Ve,{wrap:!0,title:"Can change the prompt or the request before it is sent"}):null]})}function wu({plugin:t}){const s=Dl(t.contributes.ui),n=t.contributes.composerToggles??[];return s.length===0&&n.length===0?e.jsx("p",{className:he,children:"Nothing beyond what it adds to the agent."}):e.jsxs(rt,{children:[n.map(a=>e.jsx(Ve,{wrap:!0,title:`A ${a.label} switch in the composer`,detail:e.jsx("p",{className:U(Tt,"text-pretty"),children:"On in every new session. Changing it changes that session only."})},a.id)),s.map(a=>e.jsx(Ve,{wrap:!0,title:a},a))]})}function ju({replacement:t,config:s}){const n=Je(o=>o.setGlobal),a=Je(o=>o.setProjectState),r=Wd(s,t),i=Je(o=>r?o.pending[r.id]===!0:!1),c=()=>{if(!r)return;Te("saving"),(r.scope==="project"&&s?.directory?a(r.id,"unload",s.directory):n(r.id,!1)).then(d=>Ws(d,r.name))};return e.jsxs(ft,{className:"mb-3",title:"Pi is not loading this plugin",action:r?e.jsx(S,{variant:"outline",size:"sm",disabled:i,onClick:c,children:r.scope==="project"?`Turn off ${r.name} in this project`:`Turn off ${r.name} in every project`}):void 0,children:[$d(t),r?null:" To use this plugin, turn that extension off under Pi extensions."]})}function ku({plugin:t,directory:s,config:n,backLabel:a,onBack:r}){const i=bu(t,s),c=t.enabled?Ji(n,"plugin",t.id):void 0;return e.jsxs(xe,{title:t.name,titleAbove:e.jsxs(S,{variant:"ghost",size:"xs",onClick:r,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(M,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),a]}),titleLeading:e.jsx(no,{plugin:t}),titleAccessory:t.bundled?e.jsx(Vi,{}):null,description:e.jsx("p",{className:U(Hs,"text-pretty"),children:t.description}),children:[c?e.jsx(ju,{replacement:c,config:n}):null,e.jsx(rt,{className:"mb-6",children:e.jsx(Ve,{title:"Enabled",trailing:e.jsx(so,{plugin:t})})}),e.jsx(q,{divider:!1,title:"What it adds to the agent",info:hu,description:t.enabled?void 0:"Only while it is on. Off, it adds nothing.",settingsItem:`plugins.${t.id}`,children:e.jsx(yu,{impact:t.impact,error:t.impactError})}),e.jsx(q,{title:"In PiChamber",children:e.jsx(wu,{plugin:t})}),i?e.jsx(q,{title:"Options",description:t.enabled?void 0:"Turn the plugin on to change these.",children:e.jsx(vu,{plugin:t,directory:s,disabled:!t.enabled})}):null,e.jsx(q,{title:"About",children:e.jsxs(rt,{children:[e.jsx(Ve,{title:"Source",trailing:e.jsx(pa,{children:t.bundled?"Native: comes with PiChamber":"Installed"})}),e.jsx(Ve,{title:"Version",trailing:e.jsx(pa,{children:t.version})})]})})]})}const Nu=()=>{const t=Ca()??null,{plugins:s,entry:n}=Rl(t),a=_s(j=>j.load),[r,i]=l.useState({kind:"list"}),[c,o]=l.useState(""),[d,m]=l.useState("all"),[p,h]=l.useState(null),u=bs(t)?.config??null,g=t&&u?u.project.trusted:void 0,v=e.jsx(Zd,{name:p,directory:t,projectTrusted:g,onClose:()=>h(null)});if(r.kind==="plugin"){const j=s.find(k=>k.id===r.id);if(j)return e.jsx(ku,{plugin:j,directory:t,config:u,backLabel:r.from==="browse"?"Browse":"Extensions & Plugins",onBack:()=>i(r.from==="browse"?{kind:"browse"}:{kind:"list"})})}if(r.kind==="browse")return e.jsxs(e.Fragment,{children:[e.jsx(pu,{plugins:s,directory:t,query:c,onQueryChange:o,filter:d,onFilterChange:m,onBack:()=>i({kind:"list"}),onOpenPackage:j=>i({kind:"package",name:j,from:"browse"}),onOpenPlugin:j=>i({kind:"plugin",id:j,from:"browse"}),onInstall:h}),v]});if(r.kind==="package")return e.jsxs(e.Fragment,{children:[e.jsx(nu,{name:r.name,directory:t,backLabel:r.from==="browse"?"Browse":"Extensions & Plugins",onBack:()=>i(r.from==="browse"?{kind:"browse"}:{kind:"list"}),onInstall:h}),v]});let x;!n?.plugins&&n?.status==="error"?x=e.jsx(q,{divider:!1,title:"Native plugins",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{className:he,children:"Could not load plugins from the server."}),e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{a(t,{force:!0})},children:"Try again"})]})}):n?.plugins?s.length===0?x=e.jsx(q,{divider:!1,title:"Native plugins",children:e.jsx("p",{className:he,children:"This server has no plugins."})}):x=e.jsx(xu,{plugins:s,config:u,onOpen:j=>i({kind:"plugin",id:j,from:"list"})}):x=e.jsx(q,{divider:!1,title:"Native plugins",children:e.jsx("p",{className:he,children:"Loading plugins…"})});const b=()=>i({kind:"browse"});return e.jsxs(xe,{title:"Extensions & Plugins",description:e.jsx("p",{className:U(Hs,"text-pretty"),children:"Plugins add features to PiChamber and the agent. Extensions are what Pi itself loads, here and in the terminal."}),headerEnd:e.jsxs(S,{variant:"outline",size:"sm",onClick:b,"data-settings-item":"plugins.browse",children:[e.jsx(M,{name:"search","aria-hidden":"true",className:"size-3.5"}),"Browse"]}),children:[x,e.jsx(Yd,{directory:t,pluginNames:Object.fromEntries(s.map(j=>[j.id,j.name])),onBrowse:b,onOpenPackage:j=>i({kind:"package",name:j,from:"list"})})]})},Cu=({project:t,sandbox:s,onSelect:n})=>{const a=ti(t),r=!!t.label?.trim(),i=Yo(m=>m.homeDirectory),c=Xo(t.path,i),o=!s||s.mode==="off"?null:s.availability.state==="unavailable"?"Sandbox unavailable":"Sandboxed",d=s?.mode!=="off"&&s?.availability.state==="unavailable";return e.jsxs("button",{type:"button",onClick:()=>n(t.id),"aria-label":`${a} project, ${t.path}${o?`, ${o.toLowerCase()}`:""}`,className:U("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:[e.jsx(si,{directory:t.path,label:a,className:"size-8"}),o?e.jsxs("span",{title:o,className:U("inline-flex items-center gap-1 typography-micro whitespace-nowrap",d?"text-[var(--status-error)]":"text-subtle-foreground"),children:[e.jsx(M,{name:"lock",className:"size-3.5"}),d?"Unavailable":null]}):null]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a}),e.jsx(_l,{value:c,className:U("flex typography-meta text-muted-foreground",r&&"font-mono")})]})]})},Su=({profile:t,saving:s,errors:n,onSave:a,onReset:r})=>{const[i,c]=l.useState(t.content),[o,d]=l.useState(!1);l.useEffect(()=>{c(t.content)},[t.content]);const m=i!==t.content;return e.jsx(Nn,{label:"Sandbox profile",divider:!1,className:"pb-0 pt-2",children:e.jsxs("div",{className:gt,children:[e.jsx("p",{className:U(he,"max-w-[44rem] text-pretty"),children:"The profile is nono's policy for every sandboxed project on this server: which system folders and runtimes an agent can read, and the rules for signals and sockets. Project folders, allowed hosts and local ports are added for each project and are not in this file."}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("p",{className:Le,children:t.custom?"Custom profile":"Built-in profile"}),e.jsx("p",{className:"typography-meta select-text break-all font-mono text-muted-foreground",children:t.path})]}),t.unreadable?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"status",children:"The custom profile could not be read, so sandboxed projects do not run. Fix the file on the server machine, or reset to the built-in profile."}):t.custom?e.jsxs(e.Fragment,{children:[e.jsx(Sa,{value:i,onChange:p=>c(p.target.value),"aria-label":"Custom sandbox profile, JSON",rows:16,spellCheck:!1,className:"min-h-0 max-w-[44rem] font-mono",disabled:s}),e.jsxs("p",{className:U(he,"max-w-[44rem] text-pretty"),children:[e.jsx("span",{className:"text-[var(--status-warning)]",children:"A looser profile weakens every sandboxed project on this server."})," ","Saving checks the profile with nono, then restarts running sandboxes after their current turn. You can also edit the file on the server machine. A custom profile no longer follows updates to the built-in one."]})]}):e.jsx("p",{className:U(he,"max-w-[44rem] text-pretty"),children:"Customising copies this profile to PiChamber's data folder, where sandboxed code cannot write, and uses the copy instead. You can then edit it here or on the server machine."}),n.length>0?e.jsx("div",{role:"alert",className:"max-w-[44rem] space-y-1",children:n.map(p=>e.jsx("p",{className:"typography-meta break-words text-[var(--status-error)]",children:p},p))}):null,e.jsx("div",{className:"flex flex-wrap gap-2",children:t.custom?o?e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"destructive",size:"xs",disabled:s,onClick:()=>{r().then(()=>d(!1))},children:"Delete custom profile"}),e.jsx(S,{variant:"outline",size:"xs",disabled:s,onClick:()=>d(!1),children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[t.unreadable?null:e.jsx(S,{variant:"outline",size:"xs",disabled:s||!m,onClick:()=>{a(i)},children:s?"Saving…":"Save profile"}),e.jsx(S,{variant:"outline",size:"xs",disabled:s,onClick:()=>d(!0),children:"Reset to default"})]}):e.jsx(S,{variant:"outline",size:"xs",disabled:s,onClick:()=>{a(t.content)},children:s?"Saving…":"Customise"})})]})})},Pu=(t,s)=>{const n=t.limits??[];return s?.acceptedLimits?n.every(a=>s.acceptedLimits?.includes(a)):t.limitsAccepted===!0},Tu=(t,s)=>({acceptedLimits:s?[...t]:[]}),Iu=t=>t.available?t.version?`Available, version ${t.version}`:"Available":Ol(t.reason),Eu="https://nono.sh",jr=()=>{const t=De(y=>y.launchers),s=De(y=>y.launchersStatus),n=De(y=>y.rechecking),a=De(y=>y.loadLaunchers),r=De(y=>y.recheck),i=De(y=>y.defaults),c=De(y=>y.defaultsStatus),o=De(y=>y.savingDefaults),d=De(y=>y.defaultsError),m=De(y=>y.loadDefaults),p=De(y=>y.saveDefaults),h=De(y=>y.profile),u=De(y=>y.savingProfile),g=De(y=>y.profileErrors),v=De(y=>y.loadProfile),x=De(y=>y.saveProfile),b=De(y=>y.resetProfile),j=De(y=>Object.values(y.projects).some(f=>f.mode!=="off"));l.useEffect(()=>{s==="idle"&&a()},[s,a]),l.useEffect(()=>{m(),v()},[m,v]);const k=l.useCallback(async y=>{Te("saving");const f=await x(y);return Te(f?"saved":"error"),f},[x]),P=l.useCallback(async()=>{Te("saving");const y=await b();return Te(y?"saved":"error"),y},[b]),E=l.useCallback(async y=>{const f=De.getState().defaults,N=(y.mode===void 0||y.mode===f?.mode)&&(y.allowHosts===void 0||JSON.stringify(y.allowHosts)===JSON.stringify(f?.allowHosts))&&(y.acceptedLimits===void 0||JSON.stringify(y.acceptedLimits)===JSON.stringify(f?.acceptedLimits??[]));if(f&&!f.invalid&&N)return;Te("saving");const C=await p(y);Te(C?"saved":"error")},[p]);return e.jsx(Au,{launchers:t,loadFailed:s==="failed",rechecking:n,onRecheck:()=>{r()},defaults:i,defaultsLoadFailed:c==="failed",savingDefaults:o,defaultsError:d,onSaveDefaults:E,profile:h&&(j||h.custom)?h:null,savingProfile:u,profileErrors:g,onSaveProfile:k,onResetProfile:P})},Au=({launchers:t,loadFailed:s,rechecking:n,onRecheck:a,defaults:r=null,defaultsLoadFailed:i=!1,savingDefaults:c=!1,defaultsError:o=null,onSaveDefaults:d,profile:m=null,savingProfile:p=!1,profileErrors:h=[],onSaveProfile:u,onResetProfile:g})=>{const v=e.jsx(S,{variant:"outline",size:"xs",disabled:n,onClick:a,children:n?"Checking…":"Check again"});return e.jsx(q,{title:"Sandboxing",settingsItem:"projects.sandboxing",info:"A sandboxed project runs its sessions inside nono, so agents reach only that project's folders and allowed hosts. Only the agent is sandboxed: the terminal, Git panel and browser run outside it with your normal access.",children:e.jsxs("div",{className:gt,children:[s?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:he,children:"Sandbox status could not be loaded."}),v]}):t?t.map(x=>e.jsxs(l.Fragment,{children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-x-6 gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:Le,children:x.id}),e.jsx("p",{className:x.available?"typography-meta text-muted-foreground":"typography-meta text-[var(--status-error)]",children:Iu(x)}),x.id==="nono"?e.jsx("a",{href:Eu,target:"_blank",rel:"noopener noreferrer",className:"typography-meta text-muted-foreground underline-offset-4 transition-colors hover:text-foreground hover:underline",children:"nono.sh"}):null]}),e.jsx("div",{className:"shrink-0",children:v})]}),x.available&&x.limits&&x.limits.length>0?e.jsx(Lu,{limits:x.limits,accepted:Pu(x,r),disabled:c||!r||r.invalid===!0||!d,onChange:b=>{!r||r.invalid||!d||d(Tu(x.limits??[],b))}}):null]},x.id)):e.jsx("p",{className:he,children:"Checking…"}),r&&d?e.jsx(Mu,{defaults:r,saving:c,onSave:d}):i?e.jsx("p",{className:he,children:"The sandbox default could not be loaded."}):null,r?.invalid?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"status",children:'The saved default could not be read, so projects that follow it stay sandboxed and do not run. Turn "Sandbox projects by default" on or off to save it again; the hosts and limits can be changed after that.'}):null,o?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:o}):null,m&&u&&g?e.jsx(Su,{profile:m,saving:p,errors:h,onSave:u,onReset:g}):null]})})},Lu=({limits:t,accepted:s,disabled:n,onChange:a})=>e.jsxs(at,{title:"Not enforced on this server",description:"File access is still limited, so the sandbox stops an agent's mistakes, but not code that sets out to escape it.",contentClassName:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 gap-x-10 gap-y-3 @3xl:grid-cols-2",children:t.map(r=>{const{title:i,text:c}=zl(r);return e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("p",{className:"typography-meta font-medium text-[var(--status-warning)]",children:i}),e.jsx("p",{className:U(he,"text-pretty"),children:c})]},r)})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ve,{checked:s,disabled:n,onChange:a,label:t.length===1?"Use sandboxing with this limit":"Use sandboxing with these limits"}),s?null:e.jsx("p",{className:he,children:t.length===1?"Sandboxed projects do not run on this server until you accept it.":"Sandboxed projects do not run on this server until you accept them."})]})]}),Mu=({defaults:t,saving:s,onSave:n})=>{const[a,r]=l.useState(()=>t.allowHosts.join(`
4
+ `)),i=t.allowHosts.join(`
5
+ `);l.useEffect(()=>{r(i)},[i]);const c=Ul(a),o=m=>{const p=Fl(c,m);r(p.join(`
6
+ `)),d(p)},d=m=>{t.invalid||n({allowHosts:m})};return e.jsxs(Jt,{className:"pt-2",children:[e.jsx("div",{className:"min-w-0",children:e.jsx(ve,{checked:t.mode==="nono",disabled:s,onChange:m=>{const p=m?"nono":"off";n(t.invalid?{mode:p,allowHosts:c}:{mode:p})},label:"Sandbox projects by default",info:"Projects set to Default in their Sandbox settings follow this, including folders you add later. Projects set to On or Off keep their own choice. Turning it off resets the trust of every project that was sandboxed by it.",settingsItem:"projects.sandbox-default"})}),e.jsxs(Me,{label:"Allowed hosts for all projects",info:"Hosts every sandboxed project's agent may reach, on top of your model providers and each project's own hosts. One per line. Each host lets the agent send data there, so add only what your projects need.",settingsItem:"projects.sandbox-default-hosts",controlClassName:"w-full max-w-[32rem] flex-col items-stretch",children:[e.jsx(Sa,{value:a,onChange:m=>r(m.target.value),onBlur:()=>d(c),placeholder:"registry.npmjs.org","aria-label":"Allowed hosts for all projects, one per line",rows:3,className:"min-h-0 font-mono",disabled:s}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(S,{variant:"outline",size:"xs",disabled:s||sr(c,is.github),title:is.github.join(", "),onClick:()=>o(is.github),children:"Add GitHub"}),e.jsx(S,{variant:"outline",size:"xs",disabled:s||sr(c,is.registries),title:is.registries.join(", "),onClick:()=>o(is.registries),children:"Add package registries"})]})]})]})},Ru=()=>{const{isMobile:t}=lt(),s=dn(j=>j.projects),n=dn(j=>j.updateProjectMeta),a=V(j=>j.settingsProjectsSelectedId),r=V(j=>j.setSettingsProjectsSelectedId),[i,c]=l.useState(""),o=De(j=>j.projects),d=De(j=>j.projectsStatus),m=De(j=>j.loadProjects);l.useEffect(()=>{d==="idle"&&m()},[m,d]);const p=s.filter(j=>!o[j.id]).map(j=>j.id).sort().join(`
7
+ `),h=l.useRef("");l.useEffect(()=>{if(!p){h.current="";return}d==="ready"&&h.current!==p&&(h.current=p,m())},[p,d,m]);const u=l.useCallback(()=>{Bl.requestDirectoryDialog()},[]),g=l.useMemo(()=>a?s.find(j=>j.id===a)??null:null,[s,a]);l.useEffect(()=>{a&&!s.some(j=>j.id===a)&&r(null)},[s,a,r]);const v=l.useCallback(async j=>{g&&n(g.id,{label:j.label,defaultModel:j.defaultModel??null})},[g,n]),x=l.useMemo(()=>[...s].sort((j,k)=>{const P=(j.label?.trim()||j.path).toLowerCase(),E=(k.label?.trim()||k.path).toLowerCase();return P.localeCompare(E,void 0,{sensitivity:"base"})}),[s]),b=l.useMemo(()=>{const j=i.trim().toLowerCase();return j?x.filter(k=>{const P=(k.label??"").toLowerCase(),E=k.path.toLowerCase();return P.includes(j)||E.includes(j)}):x},[x,i]);if(g){const j=ti(g);return e.jsx(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>r(null),"aria-label":"Back to projects",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{name:"arrow-left-s",className:"size-4"})}),e.jsx(si,{directory:g.path,label:j,className:"size-5"}),e.jsx("span",{className:"truncate",children:j})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:g.path}),children:e.jsx(Nc,{project:g,onIdentitySave:v})})}return s.length===0?e.jsxs(xe,{title:t?void 0:"Projects",description:t?void 0:"Manage your projects and worktrees. Add a folder to configure its defaults and actions.",headerEnd:e.jsxs(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(M,{name:"add",className:"size-4"}),"Add folder"]}),children:[e.jsx(q,{divider:!1,settingsItem:"projects.browse",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(M,{name:"folders",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No projects yet"}),e.jsx("p",{className:"typography-micro max-w-sm text-muted-foreground",children:"Add a folder to start saving per-project defaults, session history, and header actions."}),e.jsxs(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(M,{name:"add",className:"size-4"}),"Add folder"]})]})}),e.jsx(jr,{})]}):e.jsxs(xe,{title:t?void 0:"Projects",description:t?void 0:"Manage your projects and worktrees. Click a card to configure its defaults and actions.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:i,onChange:j=>c(j.target.value),placeholder:"Search projects","aria-label":"Search projects",className:"h-9 w-[18rem] max-w-full pl-8"}),i?e.jsx("button",{type:"button",onClick:()=>c(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(M,{name:"close",className:"size-4"})}):null]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(M,{name:"add",className:"size-4"}),"Add folder"]})]}),children:[e.jsxs(q,{divider:!1,settingsItem:"projects.browse",children:[d==="failed"?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:he,children:"Sandbox state could not be loaded."}),e.jsx(S,{variant:"outline",size:"xs",onClick:()=>{m()},children:"Try again"})]}):null,b.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["No projects match “",i,"”."]}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>c(""),children:"Clear search"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:b.map(j=>e.jsx(Cu,{project:j,sandbox:o[j.id],onSelect:r},j.id))})]}),e.jsx(jr,{})]})},kr=(t,s,n)=>!t||!Number.isFinite(t)?s:new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short",hour12:n==="auto"?void 0:n==="12h"}).format(t),Du=()=>{const t=V(f=>f.timeFormatPreference),[s,n]=l.useState(!1),[a,r]=l.useState(!0),[i,c]=l.useState(!1),[o,d]=l.useState(null),[m,p]=l.useState(!1),[h,u]=l.useState([]),[g,v]=l.useState($l),[x,b]=l.useState(""),j=l.useMemo(()=>Wl(),[]),k=l.useCallback(async()=>{r(!0),b("");try{const f=await Kl();u(f)}catch(f){const N=f instanceof Error?f.message:"Could not load passkeys.";b(N)}finally{r(!1)}},[]);l.useEffect(()=>{let f=!1;return(async()=>{try{if(!j.supported){f||(n(!1),r(!1));return}f||n(!0)}catch{f||n(!1)}if(!f){const N=await Hn();if(v(N),!N.enabled){u([]),r(!1);return}await k()}})(),()=>{f=!0,nr()}},[k,j.supported]);const P=l.useCallback(async()=>{if(!g.enabled){const f="Enable the UI password lock before adding passkeys.";b(f),B.message(f);return}if(!s){b(j.reason),B.message(j.reason);return}if(i){nr(),c(!1);return}b(""),c(!0);try{await Hl(),v(await Hn()),await k(),B.success("Passkey added")}catch(f){if(Vl(f)){B.message("Passkey setup canceled");return}const N=f instanceof Error?f.message:"Could not add passkey.";b(N),B.error(N)}finally{c(!1)}},[i,k,g.enabled,j.reason,s]),E=l.useCallback(async f=>{d(f),b("");try{await Gl(f),v(await Hn()),await k(),B.success("Passkey removed")}catch(N){const C=N instanceof Error?N.message:"Could not remove passkey.";b(C),B.error(C)}finally{d(null)}},[k]),y=l.useCallback(async()=>{p(!0),b("");try{await ql(),window.location.reload()}catch(f){const N=f instanceof Error?f.message:"Could not clear saved authentication.";b(N),B.error(N),p(!1)}},[]);return e.jsxs(q,{title:"Passkeys",settingsItem:"remote-access.passkeys",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ee,{label:"Current device",children:[e.jsx(S,{type:"button",variant:i?"secondary":"outline",size:"xs",onClick:()=>{P()},disabled:a||m,className:"!font-normal",children:i?"Cancel passkey setup":"Add passkey"}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{y()},disabled:a||i||m,className:"!font-normal text-muted-foreground hover:text-foreground",children:m?"Signing out…":"Sign out everywhere"})]}),!g.enabled&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Passkeys are available only when the UI password lock is enabled."}),g.enabled&&!s&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:j.reason}),a?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading passkeys…"}):h.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No passkeys saved for this host yet."}):e.jsx("div",{className:"space-y-1 pt-1",children:h.map(f=>e.jsxs(Ee,{label:e.jsx("span",{className:"truncate",children:f.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:f.lastUsedAt?`Last used ${kr(f.lastUsedAt,"Never used",t)}`:`Added ${kr(f.createdAt,"Never used",t)}`}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{E(f.id)},disabled:o===f.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:o===f.id?"Removing…":"Delete"})]},f.id))})]}),x&&e.jsx("div",{className:"mt-1 py-1.5",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:x})})]})},_u=({addDevice:t,isDesktop:s})=>{const{phase:n,creating:a,loopbackOnly:r,pairingUrl:i,pairingQrDataUrl:c,pairingCopied:o,countdownText:d,announcedCountdownText:m,routeChips:p,error:h,closeDialog:u,regenerate:g,copyLink:v,scrollToWays:x}=t;return e.jsx(e.Fragment,{children:r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Other devices can't reach this computer yet"}),e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Turn on a route in Ways to connect so this code has somewhere to connect through."})]}),s?null:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Local network needs the server started with --lan."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s?e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:()=>x("lan"),children:"Turn on local network"}):null,e.jsx(S,{type:"button",size:"xs",variant:s?"outline":"default",className:"!font-normal",onClick:()=>x("tailscale"),children:"Set up Tailscale"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:u,children:"Cancel"})})]}):a&&!i?e.jsxs("div",{className:"flex items-center gap-2 py-6 typography-ui text-muted-foreground",role:"status",children:[e.jsx(M,{name:"loader-4",className:"h-4 w-4 animate-spin","aria-hidden":!0}),"Creating secure code…"]}):e.jsxs("div",{className:"space-y-3",children:[c?e.jsx("div",{className:"flex justify-center",children:e.jsx("img",{src:c,alt:"PiChamber connection QR code",className:U("w-full max-w-[420px] rounded-md bg-white p-4",n==="expired"&&"opacity-40 grayscale"),"aria-hidden":n==="expired"})}):null,e.jsx("p",{className:"typography-ui-label text-center text-foreground",children:n==="expired"?"Code expired":"Scan with the PiChamber app"}),n==="ready"&&d?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-center text-muted-foreground","aria-hidden":!0,children:d}),e.jsx("p",{className:"sr-only","aria-live":"polite",children:m??d})]}):null,n==="expired"?e.jsx("p",{className:"typography-meta text-center text-muted-foreground",children:"This code expired. Create a new one to keep pairing."}):null,p.length>0?e.jsx("div",{className:"flex flex-wrap justify-center gap-1.5","aria-label":"Included routes",children:p.map(b=>e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1.5 py-0.5 rounded shrink-0 leading-none border border-border/50",children:b.label},b.key))}):null,n==="ready"?e.jsxs("p",{className:"flex items-center justify-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-[var(--status-warning)] animate-pulse","aria-hidden":!0}),"Waiting for device…"]}):null,h?e.jsx("p",{className:"typography-meta text-center text-[var(--status-error)]",role:"alert",children:h}):null,i?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:i}),e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:v,"aria-label":o?"Pairing link copied":"Copy pairing link",children:[e.jsx(M,{name:o?"check":"file-copy",className:U("h-3.5 w-3.5",o&&"text-[var(--status-success)]"),"aria-hidden":!0}),o?"Copied":"Copy"]})]}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:u,children:"Cancel"}),e.jsxs(S,{type:"button",variant:n==="expired"?"default":"outline",size:"xs",className:"!font-normal",onClick:g,disabled:a,children:[e.jsx(M,{name:"refresh",className:"h-3.5 w-3.5","aria-hidden":!0}),"New code"]})]})]})})},Ou=({addDevice:t,isDesktop:s})=>{const n=!t.loopbackOnly&&!!t.pairingQrDataUrl;return e.jsx(bt,{open:t.open,onOpenChange:a=>{a||t.closeDialog()},children:e.jsxs(yt,{className:"sm:max-w-lg",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Add a device"}),n?e.jsx(kt,{children:"Scan this with the PiChamber app on your other device. It is single-use and expires."}):null]}),e.jsx(_u,{addDevice:t,isDesktop:s})]})})},Nr=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}},zu=({devices:t})=>{const s=V(p=>p.timeFormatPreference),{remoteClients:n,pendingPairings:a,loading:r,error:i,revokedClientCount:c,revokeRemoteClient:o,purgeRevokedRemoteClients:d,cancelPendingPairing:m}=t;return e.jsxs(q,{title:"Devices with access",info:"Devices that can open this server. Revoking removes a device immediately, including its live connections.",settingsItem:"remote-access.devices",contentClassName:"space-y-2.5",children:[c>0?e.jsx("div",{className:"flex justify-end",children:e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>d(),children:"Clear revoked"})}):null,r&&n.length===0&&a.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading devices..."}):n.length===0&&a.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No devices connected yet."}):e.jsxs(e.Fragment,{children:[a.map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-[var(--status-warning)] animate-pulse","aria-hidden":!0}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:p.label||"Pair new device"}),p.usesRelay?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:"Relay"}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:"Waiting to connect…"})]}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>m(p.id),"aria-label":`Cancel pairing for ${p.label||"new device"}`,children:"Cancel"})]},`pending-${p.id}`)),n.map(p=>{const h=p.clientKind==="desktop-local",u=p.lastUsedAt?Date.parse(p.lastUsedAt):Number.NaN,g=!p.revokedAt&&(h||Number.isFinite(u)&&Date.now()-u<9e4),v=p.revokedAt?"Revoked":g?p.lastTransport==="relay"&&!h?"Connected · Relay":"Connected · Local network":Number.isFinite(u)?`Last used ${Ql(u,s,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:"Never used";return e.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5",children:[e.jsx("span",{"aria-hidden":!0,className:U("h-2 w-2 shrink-0 rounded-full",p.revokedAt?"bg-muted-foreground/20":g?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:p.label}),Nr(p.devicePlatform)?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:Nr(p.devicePlatform)}):null,h?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"This device"}):null,e.jsx("span",{className:U("typography-micro truncate",g&&!p.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:v})]})}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>o(p),disabled:!!p.revokedAt,"aria-label":`Revoke ${p.label}`,children:"Revoke"})]},p.id)})]}),i?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:i}):null]})},Uu=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:vt,children:e.jsx(ve,{settingsItem:"sessions.desktop-lan-access",checked:t.draftLanEnabled,onChange:t.setDraftLanEnabled,disabled:t.isLoading||t.isSaving,label:"Let other devices on your local network open this app",info:"Restarts the app so phones, tablets, and other computers on your Wi-Fi can open it. On Windows, allow PiChamber through the firewall if a phone still cannot connect.",description:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"block text-[var(--status-warning)]/85",children:"Warning: while enabled, the app is reachable by anyone on the same local network."}),t.lanRequiresPassword||t.lanBlockedByMissingPassword?e.jsx("span",{className:"block text-[var(--status-warning)]/85",children:"LAN access requires a Desktop UI Password. Until one is set, the desktop app starts local-only."}):null]}),ariaLabel:"Allow LAN access to desktop sidecar"})}),t.error?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t.error}):null,t.lanUrl?e.jsxs("div",{className:"typography-micro text-subtle-foreground",children:[t.isDirty&&!t.draftLanEnabled?"After restart, open from another device: ":"Open from another device: ",e.jsx("span",{className:"font-mono text-foreground",children:t.lanUrl})]}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(S,{type:"button",size:"xs",onClick:t.saveAndRestart,disabled:t.saveDisabled,className:"shrink-0 !font-normal",children:t.isSaving?"Saving...":"Save + Restart"})})]}),Fu=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsxs(Me,{settingsItem:"sessions.desktop-ui-password",label:e.jsx("label",{htmlFor:"desktop-ui-password",children:"Desktop UI password"}),info:"PiChamber asks after restart, then when the login session expires: after 12 hours, or 7 days with Trust this device. Leave empty to disable login.",children:[e.jsx(ee,{id:"desktop-ui-password",type:t.showPassword?"text":"password",className:"h-8 min-w-0 flex-1",value:t.draftPassword,onChange:s=>t.handlePasswordChange(s.target.value),placeholder:"No password required",disabled:t.isLoading||t.isSaving,required:t.draftLanEnabled,"aria-invalid":t.lanRequiresPassword}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>t.setShowPassword(s=>!s),className:tt,"aria-label":t.showPassword?"Hide password":"Show password","aria-pressed":t.showPassword,children:e.jsx(M,{name:t.showPassword?"eye-off":"eye",className:"h-4 w-4"})})]}),t.error?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t.error}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(S,{type:"button",size:"xs",onClick:t.saveAndRestart,disabled:t.saveDisabled,className:"shrink-0 !font-normal",children:t.isSaving?"Saving...":"Save + Restart"})})]}),Bu=()=>{const t=Oe()&&ts(),[s,n]=D.useState(!1),[a,r]=D.useState(!1),[i,c]=D.useState(""),[o,d]=D.useState(""),[m,p]=D.useState(!1),[h,u]=D.useState(!1),[g,v]=D.useState(null),[x,b]=D.useState(!0),[j,k]=D.useState(!1),[P,E]=D.useState(null),[y,f]=D.useState(null);D.useEffect(()=>{if(!t){b(!1);return}let _=!1;return(async()=>{try{const z=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error("Failed to load desktop settings");const K=await z.json().catch(()=>null);if(_)return;const H=K?.desktopLanAccessEnabled===!0,ne=typeof K?.desktopUiPassword=="string"?K.desktopUiPassword:"";n(H),r(H),c(ne),d(ne),u(K?.desktopLanAccessActive===!0),v(typeof K?.desktopLanAccessBlockedReason=="string"?K.desktopLanAccessBlockedReason:null),E(null)}catch(z){_||E(z instanceof Error?z.message:"Failed to load desktop settings")}finally{_||b(!1)}})(),()=>{_=!0}},[t]),D.useEffect(()=>{if(!t||!a){f(null);return}let _=!1;return(async()=>{const z=await Zo();_||f(z)})(),()=>{_=!0}},[a,t]);const N=a!==s||o!==i,C=D.useMemo(()=>{if(typeof window>"u")return null;const z=xt()||window.location.href;let K=0;try{K=Number(new URL(z).port)}catch{K=Number(window.location.port)}return Number.isFinite(K)&&K>0?K:null},[]),w=a&&h&&y&&C?`http://${y}:${C}`:null,L=a&&!o.trim(),I=s&&!h&&g==="missing-password",T=x||j||!N||L,A=D.useCallback(_=>{d(_),_.trim()||r(!1)},[]),F=D.useCallback(async()=>{if(N){k(!0),E(null);try{if(!(await Ae("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:a,desktopUiPassword:o})})).ok)throw new Error("Failed to save desktop settings");if(n(a),c(o),!await Yr())throw new Error("Saved, but failed to restart app")}catch(_){E(_ instanceof Error?_.message:"Failed to save desktop settings"),k(!1)}}},[o,a,N]);return{isLocalDesktop:t,isLoading:x,isSaving:j,error:P,draftLanEnabled:a,setDraftLanEnabled:r,draftPassword:o,handlePasswordChange:A,showPassword:m,setShowPassword:p,lanAccessActive:h,lanRequiresPassword:L,lanBlockedByMissingPassword:I,lanUrl:w,isDirty:N,saveDisabled:T,saveAndRestart:()=>{F()}}},ro=()=>{const[t,s]=D.useState(!1),n=D.useRef(null);D.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]);const a=D.useCallback(r=>{Ks(r).then(i=>{i.ok&&(s(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>s(!1),2e3))})},[]);return{copied:t,copy:a}},$u={neutral:"text-muted-foreground bg-muted border-border/50",success:"text-[var(--status-success)] bg-[var(--status-success)]/10 border-[var(--status-success)]/30",warning:"text-[var(--status-warning)] bg-[var(--status-warning)]/10 border-[var(--status-warning)]/30",error:"text-[var(--status-error)] bg-[var(--status-error-background)] border-[var(--status-error-border)]",info:"text-[var(--status-info)] bg-[var(--status-info-background)] border-[var(--status-info-border)]"},Pt=({tone:t,children:s})=>e.jsx("span",{className:U("typography-micro shrink-0 rounded border px-1.5 py-px leading-relaxed",$u[t]),children:s}),cs=({id:t,icon:s,title:n,pill:a,description:r,settingsItem:i,children:c})=>e.jsx(at,{settingsItem:i,title:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",id:t,children:[e.jsx(M,{name:s,className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:Cc,children:n}),a]}),children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:r}),c]})}),io=({url:t,copyLabel:s,onOpen:n,openLabel:a})=>{const{copied:r,copy:i}=ro(),c=r?`${s} (copied)`:s,o=e.jsxs(e.Fragment,{children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono typography-micro text-foreground",children:t}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[r?e.jsx("span",{className:"typography-micro text-[var(--status-success)]",children:"Copied"}):null,e.jsx(M,{name:r?"check":"file-copy",className:U("h-3.5 w-3.5",r?"text-[var(--status-success)]":"text-muted-foreground"),"aria-hidden":!0})]}),r?e.jsx("span",{className:"sr-only",role:"status",children:"Copied"}):null]});return n?e.jsxs("div",{className:"flex min-w-0 max-w-[24rem] items-center gap-0.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] py-1 pl-2 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>i(t),"aria-label":c,title:t,className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-sm px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:o}),e.jsx("button",{type:"button",onClick:n,"aria-label":a??"Open address",title:a??void 0,className:"flex shrink-0 items-center justify-center rounded-sm p-1 text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:e.jsx(M,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})})]}):e.jsx("button",{type:"button",onClick:()=>i(t),"aria-label":c,title:t,className:"flex min-w-0 max-w-[24rem] items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2 py-1.5 text-left transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:o})},Wu=({lan:t})=>{if(Oe()&&ts()){const n=t.lanUrl?e.jsx(Pt,{tone:"success",children:"On"}):t.draftLanEnabled?e.jsx(Pt,{tone:"warning",children:"Restart needed"}):e.jsx(Pt,{tone:"neutral",children:"Off"});return e.jsx(cs,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:n,description:"Phones and computers on your Wi-Fi reach this computer directly.",settingsItem:"remote-access.lan",children:e.jsx(Uu,{lan:t})})}return e.jsx(Ku,{})},Ku=()=>{const{clientAuth:t}=kn(),[s,n]=D.useState(null),[a,r]=D.useState(!0),[i,c]=D.useState(!1);return D.useEffect(()=>{if(!t?.getPairingTransports){r(!1);return}let o=!1;return(async()=>{try{const d=await t.getPairingTransports();o||(n(d),c(!1))}catch{o||c(!0)}finally{o||r(!1)}})(),()=>{o=!0}},[t]),a?e.jsx(cs,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(Pt,{tone:"neutral",children:"Checking…"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Checking whether this server is exposed on your network…"})}):i||!s?e.jsx(cs,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(Pt,{tone:"neutral",children:"Unknown"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Couldn't check local network status. Check your connection and try again."})}):s.lan?e.jsx(cs,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(Pt,{tone:"success",children:"On"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx(io,{url:s.lan,copyLabel:"Copy local network address"})}):e.jsx(cs,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(Pt,{tone:"neutral",children:"Off"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Not exposed on your network. Start the server with --lan and a UI password to allow local devices."})})},Ua=t=>!!t&&typeof t=="object"&&typeof t.state=="string",Fa=async(t,s)=>{const n=await t.json().catch(()=>null),a=typeof n?.error=="string"&&n.error?n.error:s,r=new Error(a);throw typeof n?.code=="string"&&(r.code=n.code),r.status=t.status,r},Hu=async t=>{const s=await Ae("/api/pichamber/tailscale/status",{headers:{Accept:"application/json"}});s.ok||await Fa(s,"Failed to get Tailscale status");const n=await s.json().catch(()=>null);if(!Ua(n))throw new Error("Invalid Tailscale status response");return n},Vu=async t=>{const s=await Ae("/api/pichamber/tailscale/config",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});s.ok||await Fa(s,"Failed to update Tailscale config");const n=await s.json().catch(()=>null);if(!Ua(n))throw new Error("Invalid Tailscale status response");return n},Gu=async()=>{const t=await Ae("/api/pichamber/tailscale/retry",{method:"POST",headers:{Accept:"application/json"}});t.ok||await Fa(t,"Tailscale retry failed");const s=await t.json().catch(()=>null);if(!Ua(s))throw new Error("Invalid Tailscale status response");return s},qu=2e3,Qu=15e3,ta=t=>t==="starting"||t==="needs-approval"?qu:Qu,oo=t=>t.config.enabled?t.config.mode:"off",Ju=(t,s)=>s==="public"&&t!=="public",Cr=(t,s)=>{if(!t)return!1;const n=t.authGate;return n?s==="private"?n.privateAllowed!==!1:n.publicAllowed!==!1:!0},Yu=t=>{if(!t)return null;if(t.installed===!1)return{pill:"Not installed",tone:"neutral",controlDisabled:!0,controlDisabledReason:"Install Tailscale to use this route.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Tailscale is not installed on this computer."};if(t.running===!1||t.loggedIn===!1)return{pill:"Not signed in",tone:"warning",controlDisabled:!0,controlDisabledReason:"Open Tailscale and sign in first.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.running===!1?"The Tailscale daemon is not running.":"Tailscale is installed but you are not signed in."};switch(t.state){case"off":return{pill:"Off",tone:"neutral",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:null};case"unavailable":return t.errorCode==="not_installed"?{pill:"Not installed",tone:"neutral",controlDisabled:!0,controlDisabledReason:"Install Tailscale to use this route.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Tailscale is not installed on this computer."}:t.errorCode==="not_running"||t.errorCode==="not_logged_in"?{pill:"Not signed in",tone:"warning",controlDisabled:!0,controlDisabledReason:"Open Tailscale and sign in first.",showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorCode==="not_running"?"The Tailscale daemon is not running.":"Tailscale is installed but you are not signed in."}:{pill:"Unavailable",tone:"neutral",controlDisabled:!0,controlDisabledReason:t.errorMessage,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage};case"blocked":return{pill:"Blocked",tone:"warning",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!0,publicDnsNote:null,headline:"Tailscale needs a UI password before it can be enabled."};case"starting":return{pill:"Setting up…",tone:"info",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:null};case"needs-approval":return{pill:"Waiting for approval…",tone:"warning",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!0,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:"Your tailnet admin must approve this route."};case"active":{const s=t.config.mode==="public"&&(t.publicDns==="pending"||t.publicDns==="unknown")?t.publicDns:null;return{pill:t.config.mode==="public"?"On · Public":"On · Private",tone:t.config.mode==="public"?"warning":"success",controlDisabled:!1,controlDisabledReason:null,showUrl:!0,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:s,headline:null}}case"conflict":return{pill:"Port in use",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!0,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Another destination already uses this port in Tailscale."};case"error":return t.errorCode==="status_query_failed"?{pill:"Error",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Could not read the current Tailscale status, so nothing was changed. Try again."}:t.errorCode==="permission_denied"?{pill:"Permission needed",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!0,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Tailscale denied the serve configuration."}:{pill:"Error",tone:"error",controlDisabled:!1,controlDisabledReason:null,showUrl:!1,showPortPicker:!1,showApproval:!1,showPermissionFix:!1,showAuthCallout:!1,publicDnsNote:null,headline:t.errorMessage??"Something went wrong."};default:return null}},Xu=()=>{const[t,s]=D.useState(null),[n,a]=D.useState(!0),[r,i]=D.useState(!1),[c,o]=D.useState(null),[d,m]=D.useState(null),[p,h]=D.useState(null),[u,g]=D.useState(!1),[v,x]=D.useState(null),[b,j]=D.useState(!1),k=D.useRef(0),P=D.useCallback(T=>{s(T),i(!1),o(null)},[]),E=D.useCallback(async T=>{const A=k.current;try{const F=await Hu();if(k.current!==A)return;P(F)}catch(F){if(k.current!==A)return;T?.initial&&!t&&i(!0),o(F instanceof Error?F.message:"Failed to load Tailscale status")}finally{k.current===A&&T?.initial&&a(!1)}},[P]);D.useEffect(()=>(E({initial:!0}),()=>{k.current+=1}),[E]),D.useEffect(()=>{if(typeof window>"u")return;let T=null,A=!1;const F=async()=>{if(!A){if(typeof document<"u"&&document.visibilityState==="hidden"){_(ta(t?.state??null));return}await E(),A||_(ta(t?.state??null))}},_=K=>{A||(T=setTimeout(()=>{F()},K))};_(ta(t?.state??null));const z=()=>{document.visibilityState==="visible"&&(T&&clearTimeout(T),F())};return document.addEventListener("visibilitychange",z),()=>{A=!0,T&&clearTimeout(T),document.removeEventListener("visibilitychange",z)}},[E,t?.state]);const y=D.useCallback(async T=>{const A=k.current;g(!0),m(null),h(null);try{const F=await Vu(T);if(k.current!==A)return;P(F)}catch(F){if(k.current!==A)return;const _=F.code;m(F instanceof Error?F.message:"Failed to update Tailscale"),h(typeof _=="string"?_:null)}finally{k.current===A&&(g(!1),x(null))}},[P]),f=D.useCallback(T=>{if(!t||u)return;const A=oo(t);if(T!==A){if(Ju(A,T)){j(!0);return}x(T),y(T==="off"?{enabled:!1}:{enabled:!0,mode:T})}},[t,u,y]),N=D.useCallback(()=>{j(!1),!(!t||u)&&(x("public"),y({enabled:!0,mode:"public"}))},[t,u,y]),C=D.useCallback(()=>{j(!1)},[]),w=D.useCallback(T=>{!t||u||t.config.httpsPort!==T&&y({httpsPort:T})},[t,u,y]),L=D.useCallback(async()=>{const T=k.current;g(!0),m(null),h(null);try{const A=await Gu();if(k.current!==T)return;P(A)}catch(A){if(k.current!==T)return;const F=A.code;m(A instanceof Error?A.message:"Tailscale retry failed"),h(typeof F=="string"?F:null)}finally{k.current===T&&(g(!1),x(null))}},[P]),I=D.useCallback(()=>{a(!0),i(!1),o(null),E({initial:!0})},[E]);return{status:t,initialLoading:n,loadFailed:r,loadError:c,actionError:d,actionErrorCode:p,mutationInFlight:u,pendingMode:v,confirmPublicOpen:b,setMode:f,confirmPublic:N,cancelPublicConfirm:C,setPort:w,retryNow:L,reload:I}},Zu="https://tailscale.com/download",Sr="sudo tailscale set --operator=$USER",ep=[{value:"off",label:"Off"},{value:"private",label:"Private"},{value:"public",label:"Public"}],tp={off:"Tailscale is not used.",private:"Only devices signed in to your Tailscale.",public:"Reachable from the internet through Tailscale Funnel. Devices still need to be paired."},Pr=()=>{const t=document.getElementById("desktop-ui-password");t&&(t.scrollIntoView({block:"center",behavior:"smooth"}),window.setTimeout(()=>t.focus({preventScroll:!0}),250))},sp=(t,s)=>t?s==="auth_required"?`${t} (auth_required)`:s==="invalid_config"?`${t} (invalid_config)`:s?`${t} (${s})`:/failed to fetch|networkerror|load failed|fetch/i.test(t)?`${t} Check your connection and try again.`:t:null,np=()=>{const t=Xu(),{status:s,initialLoading:n,loadFailed:a,loadError:r,actionError:i,actionErrorCode:c,mutationInFlight:o,pendingMode:d,confirmPublicOpen:m}=t,p=Oe(),h=Yu(s),u=s?oo(s):"off",g=d??u,{copied:v,copy:x}=ro(),b=!!h?.controlDisabled,j=Cr(s,"private"),k=Cr(s,"public"),P=s?!j||!k:!1,E=A=>o?!0:A==="off"?!1:b?!0:A==="private"?!j:A==="public"?!k:!1,y=A=>A==="off"||!s?null:b?h?.controlDisabledReason??null:A==="private"&&!j||A==="public"&&!k?"Set a UI password first":null,f=D.useRef(null),N=D.useCallback(A=>{f.current?.querySelector(`[data-mode="${A}"]`)?.focus()},[]),C=D.useCallback(A=>{if(A.key!=="ArrowRight"&&A.key!=="ArrowLeft"&&A.key!=="ArrowUp"&&A.key!=="ArrowDown")return;A.preventDefault();const F=["off","private","public"],_=A.target?.closest("[data-mode]")?.dataset.mode,z=F.includes(_)?_:g,K=F.indexOf(z),H=A.key==="ArrowRight"||A.key==="ArrowDown"?1:-1;for(let ne=1;ne<=F.length;ne+=1){const Z=F[(K+H*ne+F.length)%F.length];if(!E(Z)){N(Z);return}}},[g,o,b,j,k,s]),w=n||!h?e.jsx(Pt,{tone:"neutral",children:a?"Unknown":"Checking…"}):e.jsx(Pt,{tone:o&&d?"info":h.tone,children:o&&d?"Saving…":h.pill}),L=!!s&&(s?.installed===!1||s?.errorCode==="not_installed"),I=!!s&&s?.installed!==!1&&(s?.running===!1||s?.loggedIn===!1||s?.errorCode==="not_running"||s?.errorCode==="not_logged_in"),T=sp(i,c);return e.jsxs(cs,{id:"remote-access-tailscale-row",icon:"global",title:"Tailscale",pill:w,description:"Reach this computer through your Tailscale network, at home or away.",settingsItem:"remote-access.tailscale",children:[n&&!s?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Checking Tailscale status…"}):a&&!s?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:r??"Couldn't load Tailscale status."}),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.reload,children:"Try again"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{ref:f,role:"radiogroup","aria-label":"Tailscale mode",className:"flex flex-wrap items-center gap-1",onKeyDown:C,children:ep.map(A=>{const F=E(A.value),_=y(A.value),z=g===A.value;return e.jsx(S,{type:"button",variant:"chip",size:"xs","data-mode":A.value,role:"radio","aria-checked":z,"aria-label":_?`${A.label} (${_})`:A.label,title:_??void 0,disabled:F,"aria-pressed":void 0,className:"!font-normal",onClick:()=>t.setMode(A.value),children:A.label},A.value)})}),o&&d?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Saving…"}):null,b?null:e.jsx("p",{className:he,children:tp[g]}),P&&!b?e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Set a UI password first"}),p?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:!j&&!k?"Private and Public need a desktop UI password before they can be enabled.":k?"Private needs a desktop UI password before it can be enabled.":"Public needs a desktop UI password before it can be enabled."}),e.jsx("div",{className:"mt-2",children:e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:Pr,children:"Go to password"})})]}):e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a UI password. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})]}):null,h?.headline&&h.showUrl!==!0&&!h.showAuthCallout&&!P?e.jsx("p",{className:"typography-ui-label text-foreground",children:h.headline}):null,h?.showUrl&&s?.url?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(io,{url:s.url,copyLabel:"Copy Tailscale address",onOpen:()=>{ds(s.url)},openLabel:"Open Tailscale address"}),h?.publicDnsNote==="pending"?e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx(M,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Public link is waiting for DNS. New Funnel links can take 10–15 minutes to work outside your tailnet; devices on your tailnet can connect now."]}):null,h?.publicDnsNote==="unknown"?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Couldn't check public DNS. New Funnel links can take 10–15 minutes to work outside your tailnet."}):null]}):null,L?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Install Tailscale on this computer, then sign in to the same tailnet as your phone."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{ds(Zu)},children:["Get Tailscale",e.jsx(M,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})]}),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:o,children:"Check again"})]})]}):null,I?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Open Tailscale and sign in, then check again."}),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:o,children:"Check again"})]}):null,h?.showAuthCallout&&!P?e.jsxs("div",{className:"rounded-md border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Set a password first"}),p?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a desktop UI password before it can be enabled."}),e.jsx("div",{className:"mt-2",children:e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:Pr,children:"Go to password"})})]}):e.jsx("p",{className:"typography-meta text-muted-foreground mt-0.5",children:"Tailscale needs a UI password. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})]}):null,s?.state==="starting"?e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx(M,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Setting up…"]}):null,h?.showApproval?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Waiting for approval…"}),s?.approvalUrl?e.jsxs(S,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{ds(s.approvalUrl)},children:["Approve in Tailscale",e.jsx(M,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null,h?.showPermissionFix?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex min-w-0 max-w-[24rem] items-center gap-1.5 rounded-md border border-[var(--interactive-border)] px-2 py-1.5",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono typography-micro text-foreground",children:Sr}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal shrink-0",onClick:()=>x(Sr),"aria-label":v?"Fix command copied":"Copy fix command",children:e.jsx(M,{name:v?"check":"file-copy",className:U("h-3.5 w-3.5",v&&"text-[var(--status-success)]"),"aria-hidden":!0})})]}),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:o,children:"Try again"})]}):null,s?.state==="error"&&!h?.showPermissionFix?e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.retryNow,disabled:o,children:"Try again"})}):null,T?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:T}):null,s&&s.config.enabled?e.jsx(Nn,{label:"Advanced",children:e.jsxs("div",{className:"space-y-2","data-settings-item":"remote-access.tailscale-port",children:[e.jsx("p",{className:he,children:"HTTPS port for the Tailscale address. Public (Funnel) addresses only allow 443, 8443, or 10000."}),e.jsx("div",{role:"radiogroup","aria-label":"Tailscale HTTPS port",className:"flex flex-wrap items-center gap-1",children:["443","8443","10000"].map(A=>e.jsx(S,{type:"button",variant:"chip",size:"xs",role:"radio","aria-checked":String(s.config.httpsPort)===A,"aria-label":`Port ${A}`,className:"!font-normal",disabled:o,onClick:()=>t.setPort(Number(A)),children:A},A))})]})}):null]}),e.jsx(bt,{open:m,onOpenChange:A=>{A||t.cancelPublicConfirm()},children:e.jsxs(yt,{className:"sm:max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Make PiChamber reachable from the internet?"}),e.jsx(kt,{children:"Anyone with the address can reach the sign-in page. Devices still need to be paired, and the UI password protects browser sign-in. If your phone has Tailscale, Private is the safer choice."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:t.cancelPublicConfirm,children:"Cancel"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:t.confirmPublic,children:"Make public"})]})]})})]})},ap=t=>({...t.lan?{serverUrl:t.lan}:{},includeRelay:t.relayAvailable,includeDirect:!0}),rp=t=>!t.lan&&!(t.tailscale?.available&&t.tailscale.url)&&!t.relayAvailable,ip=t=>{const s=[],n=t.candidates.find(r=>r.type==="lan"||r.type==="tunnel");if(n&&"url"in n&&n.url){let r=n.url;try{r=new URL(n.url).hostname}catch{}s.push({key:"lan",label:`Local network · ${r}`})}else if(t.lanUrl){let r=t.lanUrl;try{r=new URL(t.lanUrl).hostname}catch{}s.push({key:"lan",label:`Local network · ${r}`})}const a=t.candidates.find(r=>r.type==="tailscale");return a&&"mode"in a&&s.push({key:"tailscale",label:`Tailscale · ${a.mode==="public"?"Public":"Private"}`}),t.candidates.some(r=>r.type==="relay")&&s.push({key:"relay",label:"Relay · works away from home"}),s},sa=t=>{if(!Number.isFinite(t)||t<=0)return null;const s=Math.floor(t/1e3),n=Math.floor(s/60),a=s%60;return`Expires in ${n}:${String(a).padStart(2,"0")}`},op=(t,s)=>{if(!Number.isFinite(t)||!Number.isFinite(s))return!1;if(t<=0||s<=0)return t<=0!=s<=0;const n=a=>Math.floor(a/6e4);return n(t)!==n(s)?!0:t<=1e4&&Math.floor(t/1e3)!==Math.floor(s/1e3)},lp=t=>{if(t.succeeded)return"succeeded";if(!t.hasPayload||!t.expiresAt)return"creating";const s=Date.parse(t.expiresAt);return Number.isFinite(s)?s<=t.nowMs?"expired":"ready":"creating"},cp=1e3,dp=(t,s)=>{const[n,a]=D.useState(!1),[r,i]=D.useState(!1),[c,o]=D.useState(!1),[d,m]=D.useState(null),[p,h]=D.useState(null),[u,g]=D.useState(!1),[v,x]=D.useState(null),[b,j]=D.useState(null),[k,P]=D.useState([]),[E,y]=D.useState(null),[f,N]=D.useState(null),[C,w]=D.useState(()=>Date.now()),[L,I]=D.useState(!1),[T,A]=D.useState(null),F=D.useRef(!1),_=D.useRef(0),z=D.useRef(null),K=c?"creating":lp({expiresAt:b,nowMs:C,hasPayload:!!d,succeeded:L}),H=b?Date.parse(b)-C:Number.NaN,ne=K==="ready"?sa(H):null,Z=D.useMemo(()=>ip({candidates:k,lanUrl:E}),[k,E]);D.useEffect(()=>{if(!n||!b||L)return;const re=window.setInterval(()=>{const Ne=Date.now();w(Ne);const ge=Date.parse(b)-Ne,Ce=z.current;if(z.current=ge,Ce!==null&&op(ge,Ce)){const W=sa(ge);W&&A(W)}},cp);return()=>window.clearInterval(re)},[n,b,L]);const ye=D.useCallback(async()=>{if(!t?.createPairingSession){N("Pairing is not available on this server.");return}const re=_.current+1;_.current=re,i(!0),N(null),m(null),h(null),g(!1),x(null),j(null),P([]),I(!1),F.current=!1,z.current=null;try{const Ne=await t.getPairingTransports();if(_.current!==re)return;if(y(Ne.lan),rp(Ne)){o(!0);return}o(!1);const ge=ap(Ne),{pairing:Ce,server:W}=await t.createPairingSession({allowedClientKinds:["mobile","desktop"],serverUrl:ge.serverUrl,includeRelay:ge.includeRelay,includeDirect:ge.includeDirect});if(_.current!==re){t.cancelPairing&&t.cancelPairing(Ce.id).catch(()=>{});return}const de=el({pairingId:Ce.id,secret:Ce.secret,label:W.label,fingerprint:Ce.fingerprint??void 0,expiresAt:Ce.expiresAt,candidates:W.candidates}),O=tl(de);if(m(O),h(await gi.toDataURL(O,{width:1024,margin:2,errorCorrectionLevel:"L"})),_.current!==re)return;x(Ce.id),j(Ce.expiresAt??null),P(W.candidates),w(Date.now()),z.current=Ce.expiresAt?Date.parse(Ce.expiresAt)-Date.now():null;const J=Ce.expiresAt?sa(Date.parse(Ce.expiresAt)-Date.now()):null;A(J)}catch(Ne){if(_.current!==re)return;N(Ne instanceof Error?Ne.message:String(Ne))}finally{_.current===re&&i(!1)}},[t]),oe=D.useCallback(()=>{N(null),o(!1),a(!0),ye()},[ye]),we=D.useCallback(re=>{!re||!t?.cancelPairing||t.cancelPairing(re).catch(()=>{})},[t]),le=D.useCallback(()=>{L||we(v),_.current+=1,a(!1),i(!1),x(null)},[L,v,we]),ae=D.useCallback(()=>{we(v),ye()},[we,v,ye]),pe=D.useCallback(()=>{d&&Ks(d).then(re=>{re.ok&&(g(!0),window.setTimeout(()=>g(!1),2e3))})},[d]),ce=D.useCallback(re=>{a(!1),window.requestAnimationFrame(()=>{document.getElementById(re==="lan"?"remote-access-lan-row":"remote-access-tailscale-row")?.scrollIntoView({block:"center",behavior:"smooth"})})},[]),{pendingPairings:Q,remoteClients:G,reload:Pe}=s;return D.useEffect(()=>{if(!(!n||!v||L)){if(Q.some(re=>re.id===v)){F.current=!0;return}F.current&&(I(!0),x(null),a(!1),G.some(re=>re.pairingId===v)&&B.success("Device connected."),Pe())}},[n,v,L,Q,G,Pe]),{open:n,phase:K,creating:r,loopbackOnly:c&&n&&!r&&!d,pairingUrl:d,pairingQrDataUrl:p,pairingCopied:u,expiresAt:b,countdownText:ne,announcedCountdownText:T,routeChips:Z,error:f,openDialog:oe,closeDialog:le,regenerate:ae,copyLink:pe,scrollToWays:ce}},up=t=>{const[s,n]=D.useState([]),[a,r]=D.useState([]),[i,c]=D.useState(!1),[o,d]=D.useState(null),m=D.useMemo(()=>s.filter(x=>!!x.revokedAt).length,[s]),p=D.useCallback(async x=>{if(t){x?.silent||c(!0),x?.silent||d(null);try{const[b,j]=await Promise.all([t.listClients(),t.listPendingPairings().catch(()=>null)]);n(b),j&&r(j)}catch(b){x?.silent||d(b instanceof Error?b.message:String(b))}finally{x?.silent||c(!1)}}},[t]);D.useEffect(()=>{if(!t)return;p();const x=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||p({silent:!0})},5e3);return()=>window.clearInterval(x)},[t,p]);const h=D.useCallback(async x=>{if(t)try{await t.cancelPairing(x),r(b=>b.filter(j=>j.id!==x)),await p({silent:!0})}catch(b){d(b instanceof Error?b.message:String(b))}},[t,p]),u=D.useCallback(async x=>{if(!t)return;const b=x.clientKind==="desktop-local";d(null);try{if(await t.revokeClient(x.id),b&&Oe()){const j=await Qr();await sl({hosts:j.hosts,defaultHostId:j.defaultHostId,initialHostChoiceCompleted:j.initialHostChoiceCompleted,localClientToken:null}),n(k=>k.map(P=>P.id===x.id?{...P,revokedAt:new Date().toISOString()}:P)),wa({apiBaseUrl:xt(),clientToken:null,runtimeKey:"local"});return}await p()}catch(j){d(j instanceof Error?j.message:String(j))}},[t,p]),g=D.useCallback(async()=>{if(t){d(null);try{await t.purgeRevokedClients(),await p()}catch(x){d(x instanceof Error?x.message:String(x))}}},[t,p]),v=D.useCallback(()=>{p({silent:!0})},[p]);return{remoteClients:s,pendingPairings:a,loading:i,error:o,revokedClientCount:m,reload:v,revokeRemoteClient:x=>{u(x)},purgeRevokedRemoteClients:()=>{g()},cancelPendingPairing:x=>{h(x)}}},pp=t=>{const[s,n]=l.useState("loading");return l.useEffect(()=>{let a=!1;return(async()=>{try{const r=await Jl();if(a)return;if(r.status===401){n("set");return}if(!r.ok){n("unknown");return}const i=await r.json().catch(()=>null);n(i?.disabled===!0?"not-set":"set")}catch{a||n("unknown")}})(),()=>{a=!0}},[t]),s},mp=()=>{const t=pp(!0);return t==="loading"?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Checking UI password…"}):t==="set"?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"UI password is set. The server requires it for browser sign-in."}):t==="not-set"?e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No UI password is set. Start the server with --ui-password or set PICHAMBER_UI_PASSWORD."})}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The UI password is set when the server starts."})},Tr=()=>{const{isMobile:t}=lt(),{clientAuth:s}=kn(),n=Oe(),a=n&&ts(),r=Ht()&&!Oe()&&!Re(),i=Bu(),c=up(s),o=dp(s,c);return e.jsxs(xe,{title:t?void 0:"Remote access",description:t?void 0:"How other devices reach this computer.",headerEnd:s?e.jsx("div",{"data-settings-item":"remote-access.client-auth",children:e.jsxs(S,{type:"button",size:"sm",className:"!font-normal",onClick:()=>o.openDialog(),children:[e.jsx(M,{name:"add",className:"h-4 w-4","aria-hidden":!0}),"Add a device"]})}):void 0,children:[e.jsxs(q,{title:"Ways to connect",divider:!1,settingsItem:"remote-access.ways",contentClassName:"space-y-6",children:[e.jsx(Wu,{lan:i}),e.jsx(np,{})]}),s?e.jsx(zu,{devices:c}):null,e.jsxs(q,{title:"Security",description:"The password protects browser sign-in. It is required for Local network and Tailscale access.",settingsItem:"remote-access.security",contentClassName:"space-y-3",children:[a?e.jsx(Fu,{lan:i}):null,a?null:e.jsx(mp,{})]}),r?e.jsx(Du,{}):null,e.jsx(Ou,{addDevice:o,isDesktop:n})]})},hp=({open:t,step:s,onStepChange:n,onClose:a,canScanQr:r,onScanQr:i,onImportLink:c,importSaving:o=!1,importError:d=null,onAddManual:m,manualSaving:p=!1,manualError:h=null})=>{const[u,g]=D.useState(""),[v,x]=D.useState(""),[b,j]=D.useState(""),[k,P]=D.useState(""),[E,y]=D.useState([]);D.useEffect(()=>{t||(g(""),x(""),j(""),P(""),y([]))},[t]);const f=o||p;return s==="menu"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{type:"button",className:"w-full",disabled:f,onClick:()=>n("link"),children:"Paste a pairing link"}),r&&e.jsx(S,{type:"button",variant:"outline",className:"w-full",disabled:f,onClick:()=>i?.(),children:"Scan QR code"}),e.jsx(S,{type:"button",variant:"outline",className:"w-full",disabled:f,onClick:()=>n("manual"),children:"Enter address manually"}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Manual entry is advanced: the server must already be running and reachable."})]}):s==="link"?e.jsxs("form",{className:"space-y-3",onSubmit:N=>{N.preventDefault(),c(u)},children:[e.jsx(ee,{className:"h-8",value:u,onChange:N=>g(N.target.value),placeholder:"pichamber://connect?...",disabled:f,autoFocus:!0}),d?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:d}):null,e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>n("menu"),disabled:f,children:"Back"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:a,disabled:f,children:"Cancel"}),e.jsxs(S,{type:"submit",size:"xs",className:"!font-normal",disabled:f||!u.trim(),children:[o?e.jsx(M,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null,"Import link"]})]})]})]}):e.jsxs("form",{className:"space-y-3",onSubmit:N=>{N.preventDefault(),m({label:v,url:b,token:k,headers:E})},children:[e.jsx(ee,{className:"h-8",value:v,onChange:N=>x(N.target.value),placeholder:"Label (optional)",disabled:f}),e.jsx(ee,{className:"h-8",value:b,onChange:N=>j(N.target.value),placeholder:"https://host:port",disabled:f,autoFocus:!0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"h-8",value:k,onChange:N=>P(N.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:f}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Connection tokens are saved on this device and used only when this app connects to that server."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Additional headers",e.jsx("span",{className:"ml-1.5 font-normal text-muted-foreground",children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),E.map(N=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:N.name,onChange:C=>y(w=>w.map(L=>L.id===N.id?{...L,name:C.target.value}:L)),placeholder:"Header name",disabled:f}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:N.value,onChange:C=>y(w=>w.map(L=>L.id===N.id?{...L,value:C.target.value}:L)),placeholder:"Header value",type:"password",disabled:f}),e.jsx("button",{type:"button",onClick:()=>y(C=>C.filter(w=>w.id!==N.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:f,children:e.jsx(M,{name:"close",className:"h-4 w-4","aria-hidden":"true"})})]},N.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>y(N=>[...N,ni()]),disabled:f,children:[e.jsx(M,{name:"add",className:"h-3.5 w-3.5","aria-hidden":"true"}),"Add header"]})]}),h?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:h}):null,e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>n("menu"),disabled:f,children:"Back"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:a,disabled:f,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:f||!b.trim(),children:"Add server"})]})]})]})},lo=({open:t,onOpenChange:s,canScanQr:n,onScanQr:a,onImportLink:r,importSaving:i=!1,importError:c=null,onAddManual:o,manualSaving:d=!1,manualError:m=null,initialStep:p="menu"})=>{const[h,u]=D.useState(p);return D.useEffect(()=>{t&&u(p)},[t,p]),e.jsx(bt,{open:t,onOpenChange:s,children:e.jsxs(yt,{className:"sm:max-w-lg",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Add server"}),e.jsx(kt,{children:h==="manual"?"Add another PiChamber server by address. Use this when the server is already running and you have a connection token.":h==="link"?"Paste a pairing link from another PiChamber server.":"Import a pairing link from the other server, or add one by address."})]}),e.jsx(hp,{open:t,step:h,onStepChange:u,onClose:()=>s(!1),canScanQr:n,onScanQr:a,onImportLink:r,importSaving:i,importError:c,onAddManual:o,manualSaving:d,manualError:m})]})})},fp=({open:t,onOpenChange:s,label:n,onLabelChange:a,url:r,onUrlChange:i,token:c,onTokenChange:o,headers:d,onHeadersChange:m,saving:p,error:h=null,onSave:u})=>e.jsx(bt,{open:t,onOpenChange:s,children:e.jsxs(yt,{className:"sm:max-w-lg",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Edit"}),e.jsx(kt,{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:g=>{g.preventDefault(),u()},children:[e.jsx(ee,{className:"h-8",value:n,onChange:g=>a(g.target.value),placeholder:"Label (optional)",disabled:p}),e.jsx(ee,{className:"h-8",value:r,onChange:g=>i(g.target.value),placeholder:"https://host:port",disabled:p,autoFocus:!0}),e.jsx(ee,{className:"h-8",value:c,onChange:g=>o(g.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:p}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(mi,{children:"Additional headers"}),e.jsx(gs,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),d.map(g=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:g.name,onChange:v=>m(x=>x.map(b=>b.id===g.id?{...b,name:v.target.value}:b)),placeholder:"Header name",disabled:p}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:g.value,onChange:v=>m(x=>x.map(b=>b.id===g.id?{...b,value:v.target.value}:b)),placeholder:"Header value",type:"password",disabled:p}),e.jsx("button",{type:"button",onClick:()=>m(v=>v.filter(x=>x.id!==g.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":"Remove header",disabled:p,children:e.jsx(M,{name:"close",className:"h-4 w-4"})})]},g.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>m(g=>[...g,ni()]),disabled:p,children:[e.jsx(M,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),h?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:h}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>s(!1),disabled:p,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:p,children:"Save changes"})]})]})]})}),gp=t=>t.wasLast||t.wasActive,xp=t=>t.needsLogin?{kind:"needs-login"}:t.connecting?{kind:"connecting"}:t.isCurrent?t.uncertain?{kind:"unreachable"}:{kind:"connected",transport:t.relayActive?"relay":"direct"}:{kind:"unknown"},vp=async(t,s)=>{const n=t.connections.find(a=>a.id===s);return n?(await t.connect({id:n.id,candidates:n.candidates,clientToken:n.clientToken,label:n.label}),!0):!1},bp=async(t,s,n)=>{const a=t.readConnectionCount()<=1,r=await t.removeConnection(s);return r?(gp({wasLast:a,wasActive:t.isActive(r)})&&n(),!0):!1},yp=t=>`mobile-connect:${t}`,wp=(t,s)=>Zl(yp(t),s);function jp(t){const{onConnected:s,onActiveConnectionDeleted:n}=t,a=_i(s),r=Yl(),[i,c]=D.useState(null),o=D.useSyncExternalStore(nl,ms,ms),d=D.useRef(n);d.current=n;const m=D.useRef(a);m.current=a;const p=D.useCallback(async v=>{if(!m.current.connections.some(b=>b.id===v))return!1;c(v);try{return await wp(v,()=>vp(m.current,v)),!0}finally{c(b=>b===v?null:b)}},[]),h=D.useCallback(async v=>bp({connections:m.current.connections,connect:m.current.connect,removeConnection:m.current.removeConnection,readConnectionCount:()=>Ut().length,isActive:x=>an(x)},v,()=>d.current()),[]),u=a.pendingConnection?.id??null;return{items:D.useMemo(()=>{const v=a.connections.map(x=>xd(x,{isCurrent:an(x),status:xp({isCurrent:an(x),relayActive:o,needsLogin:u!==null&&u===x.id,connecting:i!==null&&i===x.id,uncertain:r}),probing:i!==null&&i===x.id}));return Xl(v)},[a.connections,i,u,o,r]),connections:a.connections,isBusy:a.isBusy,isPasswordBusy:a.isPasswordBusy,error:a.error,pendingConnection:a.pendingConnection,connectingId:i,conn:a,connectServer:p,removeServer:h}}const kp=({onConnect:t,onActiveConnectionDeleted:s,showDiagnostics:n=!1,layout:a="sheet"})=>{const r=jp({onConnected:t,onActiveConnectionDeleted:s}),{conn:i,items:c,connectingId:o}=r,{connections:d,isBusy:m,isPasswordBusy:p,error:h,pendingConnection:u,saveConnection:g,setError:v}=i,[x,b]=l.useState(null),j=x?d.find(O=>O.id===x)??null:null,[k,P]=l.useState(""),[E,y]=l.useState(""),[f,N]=l.useState(""),[C,w]=l.useState(""),[L,I]=l.useState(!1),[T,A]=l.useState(!1),[F,_]=l.useState(!1),[z,K]=l.useState(!1),[H,ne]=l.useState(null),Z=l.useRef(null),ye=l.useMemo(()=>hd(),[]);l.useEffect(()=>{u&&I(!1)},[u]);const oe=l.useCallback(()=>{b(null),P(""),y(""),N(""),v(null)},[v]),we=l.useCallback(O=>{const J=d.find(te=>te.id===O)??null;J&&(b(O),P(Xt(J)),y(J.label),N(J.clientToken||""),v(null))},[d,v]),le=l.useCallback(O=>{O.preventDefault(),g({id:x??void 0,url:k,label:E,clientToken:f}).then(J=>{J&&oe()})},[f,x,E,oe,g,k]),ae=l.useCallback(async()=>{if(Z.current)return;v(null),A(!0);const O=new AbortController;Z.current=O;try{const J=await fd({signal:O.signal});switch(Z.current===O&&(Z.current=null,A(!1)),J.status){case"ok":_(!0),await i.connect({url:J.url,clientToken:J.clientToken,label:J.label});break;case"pairing":_(!0),await i.redeemPairingConnection(J.pairing);break;case"cancelled":break;default:{const te=J.status==="permission-denied"?"Camera access is off. Enable it in Settings to scan a QR code.":J.status==="invalid"?"That QR code is not an PiChamber connection code.":J.status==="unsupported"?"QR scanning is only available in the installed mobile app.":"Could not scan that QR code. Try again or enter the URL manually.";I(!1),v(te);break}}}finally{_(!1),Z.current===O&&(Z.current=null,A(!1))}},[i,v]);l.useEffect(()=>()=>Z.current?.abort(),[]);const pe=l.useCallback(O=>{const J=Ui(O.trim());if(!J){v("Invalid PiChamber connection link.");return}if("pairing"in J){i.redeemPairingConnection(J.pairing);return}i.connect({url:J.url})},[i,v]),ce=l.useCallback(O=>{if(!O.url.trim()){v("Enter a server URL.");return}i.connect({url:O.url,label:O.label,clientToken:O.token})},[i,v]),Q=l.useCallback(O=>{O.preventDefault(),i.submitPassword(C)},[i,C]),G=l.useCallback(()=>{w(""),i.cancelPassword()},[i]),Pe=l.useCallback(async()=>{if(!z){ne(null),K(!0);try{const O=await al();ne(O==="copied"?"Diagnostics copied to the clipboard.":O==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{ne("Diagnostics export was cancelled or unavailable.")}finally{K(!1)}}},[z]),re=l.useCallback(()=>{v(null),I(!0)},[v]),Ne=l.useCallback(()=>T?(Z.current?.abort(),!0):L?(I(!1),!0):j?(oe(),!0):u?(G(),!0):!1,[L,G,j,T,u,oe]);Zr(Ne);const ge=vd,Ce=a==="page",W=Ce?void 0:"flex h-full flex-col overflow-hidden",de=Ce?void 0:"flex-1 overflow-y-auto px-5 py-4";return u?e.jsx("div",{className:W,children:e.jsx("form",{className:de,onSubmit:Q,children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[e.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:e.jsx(M,{name:"lock",className:"size-[18px]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate typography-ui-label text-foreground",children:u.label}),e.jsx("p",{className:"truncate typography-small text-muted-foreground",children:u.candidates.some(O=>O.kind==="direct")?Xt({candidates:u.candidates}):"via PiChamber Relay"})]})]}),e.jsx("input",{...Jn,value:C,onChange:O=>w(O.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:ge}),h?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:h}):null,e.jsx(S,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:p||!C.trim(),children:p?"Connecting...":"Unlock and connect"}),e.jsx(S,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:G,children:"Use another server"})]})})}):e.jsxs(e.Fragment,{children:[T?e.jsx(bd,{onCancel:()=>Z.current?.abort()}):null,F?e.jsx(yd,{}):null,e.jsx("div",{className:W,children:e.jsx("div",{className:de,children:e.jsxs("div",{className:Ce?"space-y-4":"space-y-6",children:[e.jsx(ai,{items:c,layout:"touch",switchLabel:"Connect",pendingId:o,actionsDisabled:m,onSwitch:O=>{r.connectServer(O.id)},onEdit:O=>we(O.id),onRemove:O=>{r.removeServer(O.id)},emptyMessage:"No saved servers yet."}),h&&!L&&!j?e.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",role:"alert",children:h}):null,n?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(S,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{Pe()},disabled:z,children:[e.jsx(M,{name:"download",className:"size-[18px]"}),z?"Preparing diagnostics…":"Export diagnostics"]}),H?e.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:H}):null]}):null,j?e.jsxs("form",{className:"space-y-3",onSubmit:le,children:[e.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[e.jsx("h3",{className:"typography-ui-label text-foreground",children:"Edit server"}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:oe,children:"Cancel"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),e.jsx("input",{...Jn,value:k,onChange:O=>P(O.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:ge})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),e.jsx("input",{value:E,onChange:O=>y(O.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:ge})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),e.jsx("input",{...Jn,value:f,onChange:O=>N(O.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:ge}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),h?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:h}):null,e.jsx(S,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:"Save server"})]}):e.jsx("div",{className:"space-y-2",children:e.jsxs(S,{type:"button",size:"lg",className:"h-12 w-full",onClick:re,disabled:m,children:[e.jsx(M,{name:"add",className:"size-[18px]"}),"Add server"]})})]})})}),e.jsx(lo,{open:L,onOpenChange:O=>{I(O),O||v(null)},canScanQr:ye,onScanQr:()=>{ae()},onImportLink:pe,importSaving:m,importError:h,onAddManual:ce,manualSaving:m,manualError:h})]})},Np=({onActiveConnectionDeleted:t})=>{const{isMobile:s}=lt();return e.jsx(xe,{title:s?void 0:"Servers",description:s?void 0:"Which PiChamber server this app uses. Add other servers to switch between them.",children:e.jsx(q,{title:"Saved servers",info:"Servers this app can connect to. Add a server by address, pairing link, or QR code.",divider:!1,settingsItem:"servers.direct-hosts",contentClassName:"space-y-4",children:e.jsx(kp,{layout:"page",onConnect:()=>{},onActiveConnectionDeleted:t??(()=>{})})})})},Cp=({onActiveConnectionDeleted:t})=>l.useMemo(()=>Re(),[])?e.jsx(Np,{onActiveConnectionDeleted:t}):e.jsx(Sp,{}),Sp=()=>{const t=ec(),[s,n]=l.useState(!1),[a,r]=l.useState(null),[i,c]=l.useState(""),[o,d]=l.useState(""),[m,p]=l.useState(""),[h,u]=l.useState([]),g=l.useMemo(()=>t.items.filter(j=>!j.isLocal),[t.items]),v=t.remoteHosts;l.useEffect(()=>{v.length!==0&&t.probeAll(t.allHosts)},[v]);const x=l.useCallback(j=>{const k=t.remoteHosts.find(P=>P.id===j);k&&(r(k),c(k.label),d(k.apiUrl||k.url),p(k.clientToken||""),u(tc(k.requestHeaders)),t.setError(null))},[t]),b=l.useCallback(async()=>{if(!a)return;(await t.updateServer(a.id,{label:i,url:o,token:m,headers:h})).ok&&r(null)},[a,i,o,m,h,t]);return e.jsxs(xe,{title:"Servers",description:"Which PiChamber server this app uses. Add other servers to switch between them.",children:[e.jsxs(q,{title:"Saved servers",info:"Servers this app can switch to. Import a pairing link from the other server, or add one by address.",divider:!1,settingsItem:"servers.direct-hosts",contentClassName:"space-y-4",headerAction:e.jsx("div",{className:"flex shrink-0 items-center gap-2",children:e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{t.setError(null),n(!0)},disabled:t.saving,children:[e.jsx(M,{name:"add",className:"h-3.5 w-3.5","aria-hidden":!0}),"Add server"]})}),children:[t.loading?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading servers..."}):e.jsx(ai,{items:g,emptyMessage:"No other servers added yet.",refreshing:t.probing,actionsDisabled:t.saving,onSwitch:j=>{t.switchToHost(j.id)},onSetDefault:j=>{t.setDefaultServer(j.id)},onEdit:j=>x(j.id),onRemove:j=>{t.removeServer(j.id)}}),t.error?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:t.error}):null]}),e.jsx(lo,{open:s,onOpenChange:n,canScanQr:!1,onImportLink:async j=>{(await t.importPairingLink(j)).ok&&n(!1)},importSaving:t.saving,importError:t.error,onAddManual:async j=>{(await t.addManualServer(j)).ok&&n(!1)},manualSaving:t.saving,manualError:t.error}),e.jsx(fp,{open:!!a,onOpenChange:j=>{j||r(null)},label:i,onLabelChange:c,url:o,onUrlChange:d,token:m,onTokenChange:p,headers:h,onHeadersChange:u,saving:t.saving,error:t.error,onSave:()=>{b()}})]})},ma=128e3,ha=16384,Ir=["off","minimal","low","medium","high","xhigh","max"],Er=t=>{const s=(t??"").trim();if(!s||!/^\d+$/.test(s))return;const n=Number(s);return Number.isSafeInteger(n)&&n>0?n:void 0};function Pp(t){let s=!1,n=!1;for(const a of t)n?n=!1:s&&a==="\\"?n=!0:a==='"'&&(s=!s);return s}function fa(t){const s=[];let n=0,a=!1,r=!1;for(let c=0;c<t.length;c+=1){const o=t[c];if(r){r=!1;continue}if(a&&o==="\\"){r=!0;continue}if(o==='"'){a=!a;continue}if(!a&&(o===","||o===`
8
+ `)){const d=t.slice(n,c).trim();d&&s.push(d),n=c+1}}const i=t.slice(n).trim();return i&&s.push(i),s}function Tp(t){const s=fa(t??"");if(s.length===0)return{};const n={};for(const a of s){const r=a.indexOf("="),i=r>=0?a.slice(0,r).trim():void 0,c=i?Ir.find(d=>d===i):Ir.find(d=>a===d||a.startsWith(`${d}-`));if(!c)return{error:"Use off, minimal, low, medium, high, xhigh, or max, optionally as key=value"};if(Object.prototype.hasOwnProperty.call(n,c))return{error:`Only one ${c} value is allowed`};let o=a;if(r>=0){const d=a.slice(r+1).trim();if(!d)return{error:"Thinking values cannot be empty"};if(d==="null")o=null;else if(d.startsWith('"'))try{const m=JSON.parse(d);if(typeof m!="string")throw new Error("not a string");o=m}catch{return{error:"Quoted thinking values must be valid strings"}}else o=d}if(o!==null&&o.length>512)return{error:"Thinking values must be 512 characters or fewer"};n[c]=o}return{value:n}}function co(t){const s=t.modelId.trim(),n=(t.displayName??"").trim(),a=Er(t.contextWindowText),r=Er(t.maxTokensText),i=Tp(t.thinkingLevelMapText),c={...s?s.length>512?{modelId:"Use 512 characters or fewer"}:{}:{modelId:"Required"},...n.length>512?{displayName:"Use 512 characters or fewer"}:{},...(t.contextWindowText??"").trim()&&a===void 0?{contextWindow:"Enter a positive whole number"}:{},...(t.maxTokensText??"").trim()&&r===void 0?{maxTokens:"Enter a positive whole number"}:{},...i.error?{thinkingLevelMap:i.error}:{},...i.value&&!t.supportsThinking?{thinkingLevelMap:"Enable Supports thinking to add thinking levels"}:{}};if(Object.values(c).some(Boolean))return{errors:c};const o=[...t.inputText?["text"]:[],...t.inputImage?["image"]:[]];return{errors:c,result:{id:s,...n?{name:n}:{},...a!==void 0?{contextWindow:a}:{},...r!==void 0?{maxTokens:r}:{},...o.length>0?{input:o}:{},...t.supportsThinking?{reasoning:!0}:{},...i.value?{thinkingLevelMap:i.value}:{}}}}const Ip="@ai-sdk/openai-compatible",Ep=/^[a-z0-9][a-z0-9-_]*$/,Ap=/^https?:\/\//,Lp=/^\{env:([^}]+)\}$/,Mp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function uo(t){return Mp.some(s=>s===t)}let Rp=0;const Ba=()=>`row-${Rp++}`,xn=()=>({row:Ba(),advancedOpen:!1,modelId:"",displayName:"",contextWindowText:"",maxTokensText:"",inputText:!1,inputImage:!1,supportsThinking:!1,thinkingLevelMapText:""}),$a=()=>({row:Ba(),key:"",value:""}),Dp=()=>({providerID:"",name:"",baseURL:"",api:"openai-completions",apiKey:"",models:[xn()],headers:[$a()]});function _p(t){const s=t.trim();if(!s)return{};const a=s.match(Lp)?.[1]?.trim();return a?{env:a}:{key:s}}function Op(t){const s=t.options&&typeof t.options=="object"?t.options:{},n=typeof s.baseURL=="string"?s.baseURL:"",a=s.headers&&typeof s.headers=="object"&&!Array.isArray(s.headers)?s.headers:{},r=Object.entries(a).filter(m=>typeof m[0]=="string"&&typeof m[1]=="string").map(([m,p])=>({row:Ba(),key:m,value:p})),i=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([m,p])=>({...p&&typeof p=="object"&&!Array.isArray(p)?p:{},id:m,name:p&&typeof p=="object"&&"name"in p&&typeof p.name=="string"?p.name:m})):[],c=i.length>0?i.map(m=>({...xn(),modelId:typeof m?.id=="string"?m.id:"",displayName:typeof m?.name=="string"?m.name:"",contextWindowText:m&&"contextWindow"in m&&typeof m.contextWindow=="number"?String(m.contextWindow):"",maxTokensText:m&&"maxTokens"in m&&typeof m.maxTokens=="number"?String(m.maxTokens):"",inputText:!!(m&&"input"in m&&Array.isArray(m.input)&&m.input.includes("text")),inputImage:!!(m&&"input"in m&&Array.isArray(m.input)&&m.input.includes("image")),supportsThinking:!!(m&&("supportsThinking"in m&&m.supportsThinking===!0||"reasoning"in m&&m.reasoning===!0)),thinkingLevelMapText:m&&"thinkingLevelMap"in m&&m.thinkingLevelMap?Object.entries(m.thinkingLevelMap).map(([p,h])=>`${p}=${h===null?"null":JSON.stringify(h)}`).join(`
9
+ `):""})):[xn()],o=Array.isArray(t.env)?t.env.find(m=>typeof m=="string"&&m.trim().length>0)?.trim():void 0,d=typeof t.api=="string"&&uo(t.api)?t.api:"openai-completions";return{providerID:t.id,name:typeof t.name=="string"&&t.name.trim()?t.name:t.id,baseURL:n,api:d,apiKey:o?`{env:${o}}`:"",models:c,headers:r.length>0?r:[$a()]}}function zp(t){const s=t.form.providerID.trim(),n=t.form.name.trim(),a=t.form.baseURL.trim(),{env:r,key:i}=_p(t.form.apiKey),c=t.disabledProviders??[],o=t.editingProviderID?.trim(),d=s?Ep.test(s)?void 0:"Use lowercase letters, numbers, hyphens, or underscores":"Provider ID is required",m=n?void 0:"Display name is required",p=a?Ap.test(a)?void 0:"Base URL must start with http:// or https://":"Base URL is required",u=!!(r||i||o&&t.allowExistingAuth&&o===s)?void 0:"API key or {env:VAR_NAME} is required",g=c.includes(s),x=d||!!(o&&o===s)?void 0:t.existingProviderIDs.has(s)&&!g?"A provider with this ID is already connected":void 0,b=new Set,j=t.form.models.map(I=>{const T=co(I),A=I.modelId.trim();return A&&b.has(A)?{errors:{...T.errors,modelId:"Duplicate"}}:(A&&b.add(A),T)}),k=j.map(I=>I.errors),P=j.every(I=>I.result!==void 0),E=Object.fromEntries(j.flatMap(I=>I.result?[[I.result.id,I.result]]:[])),y=new Set,f=t.form.headers.map(I=>{const T=I.key.trim(),A=I.value.trim();return!T&&!A?{}:{key:T?y.has(T.toLowerCase())?"Duplicate":void y.add(T.toLowerCase()):"Required",value:A?void 0:"Required"}}),N=f.every(I=>!I.key&&!I.value),C=Object.fromEntries(t.form.headers.map(I=>({key:I.key.trim(),value:I.value.trim()})).filter(I=>I.key&&I.value).map(I=>[I.key,I.value])),w={providerID:d??x,name:m,baseURL:p,apiKey:u};return!d&&!x&&!m&&!p&&!u&&P&&N?{err:w,models:k,headers:f,result:{providerID:s,name:n,apiKey:i,config:{npm:Ip,name:n,api:t.form.api,...r?{env:[r]}:{},options:{baseURL:a,...Object.keys(C).length>0?{headers:C}:{}},models:E}}}:{err:w,models:k,headers:f}}const po=({value:t,onChange:s,disabled:n=!1,hasError:a=!1,id:r})=>{const[i,c]=l.useState(""),o=fa(t),d=()=>{const m=fa(i);if(m.length===0)return;const p=[...o];for(const h of m)p.includes(h)||p.push(h);s(p.join(`
10
+ `)),c("")};return e.jsxs("div",{className:"space-y-2",children:[o.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5","aria-label":"Configured thinking levels",children:o.map(m=>e.jsxs(S,{type:"button",variant:"chip",size:"xs",disabled:n,"aria-label":`Remove ${m}`,onClick:()=>s(o.filter(p=>p!==m).join(`
11
+ `)),children:[e.jsx("span",{className:"font-mono text-xs normal-case",children:m}),e.jsx(M,{name:"close",className:"size-3","aria-hidden":!0})]},m))}):null,e.jsx(ee,{id:r,value:i,onChange:m=>c(m.target.value),onKeyDown:m=>{(m.key==="Enter"||m.key===","&&!Pp(i))&&(m.preventDefault(),d())},onBlur:d,placeholder:"low-effort",className:"h-8 font-mono text-xs",disabled:n,"aria-invalid":a||void 0,"aria-label":"Add thinking level"}),e.jsx("p",{className:he,children:'Press Enter or comma to add a value. Use low-effort for standard values, or low="value" and low=null for explicit mappings.'})]})},Cs=({children:t})=>t?e.jsx("p",{role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:t}):null,Up=({model:t,errors:s,busy:n,removable:a,onChange:r,onRemove:i})=>{const c=`custom-provider-${t.row}`;return e.jsxs("div",{className:"space-y-3 border-b border-border/60 pb-4 last:border-b-0",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:`${c}-id`,children:"Model ID"}),e.jsx(ee,{id:`${c}-id`,value:t.modelId,onChange:o=>r("modelId",o.target.value,"modelId"),placeholder:"gpt-4o",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs",disabled:n,"aria-invalid":!!s?.modelId||void 0}),e.jsx(Cs,{children:s?.modelId})]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:`${c}-name`,children:"Display name"}),e.jsx(ee,{id:`${c}-name`,value:t.displayName,onChange:o=>r("displayName",o.target.value,"displayName"),placeholder:"Same as model ID",className:"mt-1 h-8 rounded-md px-3",disabled:n,"aria-invalid":!!s?.displayName||void 0}),e.jsx(Cs,{children:s?.displayName})]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:tt,disabled:!a||n,onClick:i,"aria-label":"Remove model",children:e.jsx(M,{name:"delete-bin",className:"size-4"})})]}),e.jsxs(S,{type:"button",variant:"ghost",size:"sm",className:"w-full justify-between px-0","aria-expanded":t.advancedOpen,"aria-controls":`${c}-advanced`,onClick:()=>r("advancedOpen",!t.advancedOpen),disabled:n,children:[e.jsx("span",{children:"Advanced settings"}),e.jsx(M,{name:"arrow-down-s",className:U("size-4 transition-transform",t.advancedOpen&&"rotate-180")})]}),t.advancedOpen?e.jsxs("div",{id:`${c}-advanced`,className:"grid grid-cols-1 gap-3 border-t border-border/60 pt-3 @xl:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:`${c}-context`,children:"Context window"}),e.jsx(ee,{id:`${c}-context`,value:t.contextWindowText,onChange:o=>r("contextWindowText",o.target.value,"contextWindow"),placeholder:String(ma),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:n,"aria-invalid":!!s?.contextWindow||void 0}),e.jsx(Cs,{children:s?.contextWindow})]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:`${c}-max`,children:"Max output tokens"}),e.jsx(ee,{id:`${c}-max`,value:t.maxTokensText,onChange:o=>r("maxTokensText",o.target.value,"maxTokens"),placeholder:String(ha),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:n,"aria-invalid":!!s?.maxTokens||void 0}),e.jsx(Cs,{children:s?.maxTokens})]}),e.jsxs("div",{className:"@xl:col-span-2",children:[e.jsx("span",{className:Le,children:"Input modalities"}),e.jsxs("div",{className:"mt-1 space-y-1.5",children:[e.jsx(ve,{checked:!!t.inputText,onChange:o=>r("inputText",o),label:"Text",ariaLabel:"Text input",disabled:n}),e.jsx(ve,{checked:!!t.inputImage,onChange:o=>r("inputImage",o),label:"Image",ariaLabel:"Image input",disabled:n})]})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(ve,{checked:!!t.supportsThinking,onChange:o=>r("supportsThinking",o,"thinkingLevelMap"),label:"Supports thinking",ariaLabel:"Supports thinking",disabled:n,info:"Pi defaults to off. Unchecked omits this setting."}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:`${c}-thinking`,children:"Thinking levels"}),e.jsx(po,{id:`${c}-thinking`,value:t.thinkingLevelMapText??"",onChange:o=>r("thinkingLevelMapText",o,"thinkingLevelMap"),disabled:n||!t.supportsThinking,hasError:!!s?.thinkingLevelMap}),e.jsx(Cs,{children:s?.thinkingLevelMap})]})]})]}):null]})},Fp=({existingProviderIDs:t,disabledProviders:s=[],busy:n=!1,mode:a="create",initialValues:r,allowExistingAuth:i=!1,authFailureHint:c=null,onSubmit:o,onCancel:d,onDisconnect:m})=>{const p=a==="edit",[h,u]=l.useState(()=>r??Dp()),[g,v]=l.useState({}),[x,b]=l.useState([]),[j,k]=l.useState([]),P=l.useRef(null);l.useEffect(()=>{r&&(p&&P.current===r.providerID||(P.current=p?r.providerID:null,u(r),v({}),b([]),k([])))},[r,p]);const E=(C,w)=>{u(L=>({...L,[C]:w})),v(L=>({...L,[C]:void 0}))},y=(C,w,L,I)=>{u(T=>({...T,models:T.models.map((A,F)=>F===C?{...A,[w]:L}:A)})),I&&b(T=>{const A=[...T];return A[C]={...A[C]??{},[I]:void 0},A})},f=(C,w,L)=>{u(I=>({...I,headers:I.headers.map((T,A)=>A===C?{...T,[w]:L}:T)})),k(I=>{const T=[...I];return T[C]={...T[C]??{},[w]:void 0},T})},N=async C=>{if(C.preventDefault(),n)return;const w=zp({form:h,existingProviderIDs:t,disabledProviders:s,editingProviderID:p?h.providerID:void 0,allowExistingAuth:p&&i});v(w.err),b(w.models),k(w.headers),w.result&&await o(w.result)};return e.jsxs("form",{onSubmit:N,className:"grid grid-cols-1 @3xl:grid-cols-2 @3xl:gap-x-10",children:[e.jsxs(q,{divider:!1,settingsItem:"providers.custom",className:"@3xl:col-span-2",contentClassName:gt,children:[e.jsx("p",{className:he,children:"Add a provider with a base URL, API format, credentials, and model list. Saved to Pi so it is available in chat like any other provider."}),c?e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:c}):null,e.jsxs(Jt,{children:[e.jsxs(Me,{label:"Provider ID",info:"Lowercase letters, numbers, hyphens, and underscores. Used as the Pi provider id.",children:[e.jsx(ee,{value:h.providerID,onChange:C=>E("providerID",C.target.value),placeholder:"my-provider",className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:!p,disabled:p||n,"aria-invalid":!!g.providerID,"aria-label":"Provider ID"}),g.providerID?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:g.providerID}):null]}),e.jsxs(Me,{label:"Display name",info:"Shown in the provider and model pickers.",children:[e.jsx(ee,{value:h.name,onChange:C=>E("name",C.target.value),placeholder:"My provider",className:"h-8 rounded-md px-3","aria-invalid":!!g.name,"aria-label":"Display name"}),g.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:g.name}):null]}),e.jsxs(Me,{label:"Base URL",info:"Provider API base URL. Must start with http:// or https://.",children:[e.jsx(ee,{value:h.baseURL,onChange:C=>E("baseURL",C.target.value),placeholder:"https://api.example.com/v1",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!g.baseURL,"aria-label":"Base URL"}),g.baseURL?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:g.baseURL}):null]}),e.jsx(Me,{label:"API format",info:"Select the request and response format implemented by this provider.",children:e.jsxs(Be,{value:h.api,onValueChange:C=>{uo(C)&&u(w=>({...w,api:C}))},disabled:n,children:[e.jsx($e,{size:Ge,className:xs,"aria-label":"API format",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"openai-completions",children:"OpenAI Chat Completions"}),e.jsx(ke,{value:"openai-responses",children:"OpenAI Responses"}),e.jsx(ke,{value:"anthropic-messages",children:"Anthropic Messages"}),e.jsx(ke,{value:"google-generative-ai",children:"Google Generative AI"})]})]})}),e.jsxs(Me,{label:"API key",info:p&&i?"Leave blank to keep the existing credential, or enter a new key / {env:VAR_NAME}.":"Stored in Pi authentication, not by PiChamber. Use {env:VAR_NAME} to read a key from the environment instead.",children:[e.jsx(ee,{type:"password",value:h.apiKey,onChange:C=>E("apiKey",C.target.value),placeholder:p&&i?"Leave blank to keep existing key":"sk-... or {env:VAR_NAME}",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!g.apiKey,"aria-label":"API key"}),g.apiKey?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:g.apiKey}):null]})]})]}),e.jsxs(q,{title:"Models",contentClassName:gt,children:[h.models.map((C,w)=>e.jsx(Up,{model:C,errors:x[w],busy:n,removable:h.models.length>1,onChange:(L,I,T)=>y(w,L,I,T),onRemove:()=>{h.models.length<=1||(u(L=>({...L,models:L.models.filter((I,T)=>T!==w)})),b(L=>L.filter((I,T)=>T!==w)))}},C.row)),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u(C=>({...C,models:[...C.models,xn()]})),b(C=>[...C,{}])},children:"Add model"})]}),e.jsxs(q,{title:"Headers",contentClassName:gt,children:[e.jsx("p",{className:he,children:"Optional request headers sent with every call."}),h.headers.map((C,w)=>e.jsx("div",{className:`${us} 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:Le,children:"Header name"}),e.jsx(ee,{value:C.key,onChange:L=>f(w,"key",L.target.value),placeholder:"X-Custom-Header",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header name"}),j[w]?.key?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:j[w]?.key}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,children:"Header value"}),e.jsx(ee,{value:C.value,onChange:L=>f(w,"value",L.target.value),placeholder:"value",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header value"}),j[w]?.value?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:j[w]?.value}):null]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:tt,disabled:h.headers.length<=1,onClick:()=>{h.headers.length<=1||(u(L=>({...L,headers:L.headers.filter((I,T)=>T!==w)})),k(L=>L.filter((I,T)=>T!==w)))},"aria-label":"Remove header",children:e.jsx(M,{name:"delete-bin",className:"size-4"})})]})},C.row)),e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u(C=>({...C,headers:[...C.headers,$a()]})),k(C=>[...C,{}])},children:"Add header"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4 @3xl:col-span-2",children:[d?e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:d,disabled:n,children:"Back"}):null,m?e.jsx(S,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{m()},disabled:n,children:"Disconnect"}):null,e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:n,children:n?"Saving...":p?"Update provider":"Save provider"})]})]})},et=()=>({runtimeKey:qe()}),Zs="__pi_fallback__",Bp=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},$p=t=>[...t].sort((s,n)=>s.authenticated!==n.authenticated?s.authenticated?-1:1:s.label.localeCompare(n.label,void 0,{sensitivity:"base"})),Wp=t=>{const s=t&&typeof t=="object"&&"code"in t?String(t.code):void 0;return s==="INVALID_ARGUMENT"?"Could not add this model. It may already exist, or this provider cannot accept manual models.":s==="PROVIDER_NOT_FOUND"?"This provider is no longer available. Refresh providers and try again.":s==="PI_MODEL_CONFIG_INVALID"?"Pi model configuration is invalid.":s?`Could not add model (${s}). Try again.`:"Could not add model. Try again."},Kp=({open:t,onOpenChange:s,providerId:n,providerLabel:a,onAdded:r,initialAdvancedOpen:i=!1})=>{const[c,o]=l.useState(""),[d,m]=l.useState(""),[p,h]=l.useState(""),[u,g]=l.useState(""),[v,x]=l.useState(!1),[b,j]=l.useState(!1),[k,P]=l.useState(!1),[E,y]=l.useState(""),[f,N]=l.useState(i),[C,w]=l.useState({}),[L,I]=l.useState(null),[T,A]=l.useState(!1);l.useEffect(()=>{t&&(o(""),m(""),h(""),g(""),x(!1),j(!1),P(!1),y(""),N(i),w({}),I(null),A(!1))},[t,n,i]);const F=H=>{T&&!H||s(H)},_=H=>{w(ne=>ne[H]===void 0?ne:{...ne,[H]:void 0})},z=async H=>{if(H.preventDefault(),T)return;const ne=co({modelId:c,displayName:d,contextWindowText:p,supportsThinking:k,maxTokensText:u,inputText:v,inputImage:b,thinkingLevelMapText:E});w(ne.errors);const Z=ne.result;if(!Z){(ne.errors.displayName||ne.errors.contextWindow||ne.errors.maxTokens||ne.errors.thinkingLevelMap)&&N(!0),I(null);return}A(!0),I(null);try{const ye=await _e.addProviderModel({providerId:n,model:Z},et()),oe=wn(ye);oe?B.info(qt("Model")):B.success("Model added"),s(!1),await r?.({deferred:oe,providerId:n,modelId:Z.id})}catch(ye){I(Wp(ye))}finally{A(!1)}},K=(H,ne,Z)=>Z?`${H} ${ne}`:H;return e.jsx(bt,{open:t,onOpenChange:F,children:e.jsxs(yt,{className:U(f?"max-w-3xl":"max-w-md","w-full @container p-4 sm:p-6"),children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Add model"}),e.jsx(kt,{children:`Add a manual model to ${a}. Only the Model ID is required.`})]}),e.jsxs("form",{onSubmit:z,className:"@container space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("label",{className:Le,htmlFor:"add-model-id",children:"Model ID"}),e.jsx("span",{className:"text-xs text-[var(--status-error)]","aria-hidden":!0,children:"*"})]}),e.jsx(ee,{id:"add-model-id",value:c,onChange:H=>{o(H.target.value),_("modelId")},placeholder:"my-model",className:"h-8 font-mono text-xs",autoFocus:!0,disabled:T,"aria-invalid":!!C.modelId||void 0,"aria-describedby":C.modelId?"add-model-id-error":void 0,"aria-label":"Model ID","aria-required":"true"}),C.modelId?e.jsx("p",{id:"add-model-id-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:C.modelId}):null]}),e.jsxs("div",{children:[e.jsxs(S,{type:"button",variant:"ghost",size:"sm",id:"add-model-advanced-toggle","aria-expanded":f,"aria-controls":"add-model-advanced",onClick:()=>N(H=>!H),className:"w-full justify-between px-0",children:[e.jsx("span",{children:"Advanced settings"}),e.jsx(M,{name:"arrow-down-s",className:U("size-4 transition-transform",f&&"rotate-180"),"aria-hidden":!0})]}),f?e.jsxs("div",{id:"add-model-advanced",role:"region","aria-labelledby":"add-model-advanced-toggle",className:"grid grid-cols-1 gap-4 border-t border-border/60 pt-4 @xl:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("label",{className:Le,htmlFor:"add-model-label",children:"Display name"}),e.jsx(gs,{contentClassName:"max-w-xs",children:"Shown in pickers."})]}),e.jsx(ee,{id:"add-model-label",value:d,onChange:H=>{m(H.target.value),_("displayName")},placeholder:"Same as model ID",className:"h-8",disabled:T,"aria-invalid":!!C.displayName||void 0,"aria-describedby":K("add-model-label-hint","add-model-label-error",!!C.displayName),"aria-label":"Display name"}),e.jsx("p",{id:"add-model-label-hint",className:U(he,"mt-1"),children:"Defaults to the Model ID. Leave empty to omit."}),C.displayName?e.jsx("p",{id:"add-model-label-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:C.displayName}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Le,htmlFor:"add-model-context",children:"Context window"})}),e.jsx(ee,{id:"add-model-context",value:p,onChange:H=>{h(H.target.value),_("contextWindow")},placeholder:String(ma),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:T,"aria-invalid":!!C.contextWindow||void 0,"aria-describedby":K("add-model-context-hint","add-model-context-error",!!C.contextWindow),"aria-label":"Context window"}),e.jsx("p",{id:"add-model-context-hint",className:U(he,"mt-1"),children:`Pi uses ${ma.toLocaleString()} when empty.`}),C.contextWindow?e.jsx("p",{id:"add-model-context-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:C.contextWindow}):null]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Le,htmlFor:"add-model-max-tokens",children:"Max output tokens"})}),e.jsx(ee,{id:"add-model-max-tokens",value:u,onChange:H=>{g(H.target.value),_("maxTokens")},placeholder:String(ha),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:T,"aria-invalid":!!C.maxTokens||void 0,"aria-describedby":K("add-model-max-tokens-hint","add-model-max-tokens-error",!!C.maxTokens),"aria-label":"Max output tokens"}),e.jsx("p",{id:"add-model-max-tokens-hint",className:U(he,"mt-1"),children:`Pi uses ${ha.toLocaleString()} when empty.`}),C.maxTokens?e.jsx("p",{id:"add-model-max-tokens-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:C.maxTokens}):null]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("span",{className:Le,id:"add-model-input-label",children:"Input modalities"}),e.jsx(gs,{contentClassName:"max-w-xs",children:"Select one or both; leave both off to omit."})]}),e.jsxs("div",{role:"group","aria-labelledby":"add-model-input-label","aria-describedby":"add-model-input-hint",className:"space-y-1.5",children:[e.jsx(ve,{checked:v,onChange:H=>x(H),label:"Text",ariaLabel:"Text input",disabled:T}),e.jsx(ve,{checked:b,onChange:H=>j(H),label:"Image",ariaLabel:"Image input",disabled:T})]}),e.jsx("p",{id:"add-model-input-hint",className:U(he,"mt-1"),children:"Defaults to text when omitted."})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(ve,{checked:k,onChange:H=>{P(H),_("thinkingLevelMap")},label:"Supports thinking",ariaLabel:"Supports thinking",disabled:T,info:"Pi defaults to off. Checked sends true; unchecked omits the field."}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 flex items-center gap-1.5",children:e.jsx("label",{className:Le,htmlFor:"add-model-thinking-map",children:"Thinking levels"})}),e.jsx(po,{id:"add-model-thinking-map",value:E,onChange:H=>{y(H),_("thinkingLevelMap")},disabled:T||!k,hasError:!!C.thinkingLevelMap}),e.jsx("p",{id:"add-model-thinking-map-hint",className:U(he,"mt-1"),children:"Requires Supports thinking."}),C.thinkingLevelMap?e.jsx("p",{id:"add-model-thinking-map-error",role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:C.thinkingLevelMap}):null]})]})]}):null]}),L?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:L}):null,e.jsxs(ys,{className:"gap-2",children:[e.jsx(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>F(!1),disabled:T,children:"Cancel"}),e.jsx(S,{type:"submit",size:"sm",disabled:T,children:T?"Adding…":"Add model"})]})]})]})})},Hp=({provider:t,onSelect:s})=>{const n=t.models.length,a=n===1?"1 model":`${n} models`,{hasLogo:r}=sc(t.id);return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.label} provider, ${a}${t.authenticated?", authenticated":""}`,className:U("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r?e.jsx(ri,{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(M,{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(M,{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(M,{name:"stack",className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"tabular-nums",children:a})]})]})},Vp=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"size-8 shrink-0 animate-pulse rounded-md bg-muted"}),e.jsx("div",{className:"h-4 w-16 animate-pulse rounded bg-muted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-1/2 animate-pulse rounded bg-muted"})]}),e.jsx("div",{className:"h-3 w-16 animate-pulse rounded bg-muted"})]},n))}),Ss="__pi_custom_provider__",ga=Lc(t=>({selectedProviderId:null,setSelectedProviderId:s=>t(n=>n.selectedProviderId===s?n:{selectedProviderId:s})})),Gp=(t,s,n)=>t.some(a=>a.providerID===s&&a.modelID===n),mo=l.memo(({providerId:t,model:s,storedLevel:n,isBusy:a,isHidden:r,isConnected:i,onThinkingChange:c,onToggleHidden:o})=>{const d=l.useMemo(()=>ii(s),[s]),p=l.useMemo(()=>oi(d),[d])||n!==void 0,h=l.useMemo(()=>Bp(d,n),[d,n]),u=n??Zs;return e.jsxs("div",{className:U("flex min-w-0 items-center gap-2 py-2",r&&"opacity-60"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",children:s.label||s.id}),p?e.jsxs(Be,{value:u,onValueChange:g=>c(t,s.id,g===Zs?null:g),disabled:a,children:[e.jsx($e,{size:"sm",className:"w-auto min-w-[4.5rem] max-w-[8rem] shrink-0 border-0 bg-transparent px-1.5 shadow-none gap-1 text-muted-foreground hover:bg-muted hover:text-foreground data-[placeholder]:text-muted-foreground","aria-label":`Thinking for ${s.label||s.id}`,children:e.jsx(We,{children:g=>g===Zs?"Default":g&&li(g)?un[g]:g??""})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:Zs,children:"Default"}),h.map(g=>e.jsx(ke,{value:g,children:un[g]},g))]})]}):null,s.supportsThinking?e.jsx(M,{name:"brain-ai-3",className:"size-4 shrink-0 text-muted-foreground","aria-label":"Reasoning"}):null,typeof s.contextWindow=="number"?e.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:s.contextWindow}):null,i?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>o(t,s.id),"aria-label":r?"Show model in pickers":"Hide model from pickers",title:r?"Show model in pickers":"Hide model from pickers",children:e.jsx(M,{name:r?"eye":"eye-off",className:"size-4"})}):null]})});mo.displayName="ProviderModelRow";const qp=t=>{if(!t)return null;try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"?s:null}catch{return null}},Qp=({login:t,authUrl:s,promptValue:n,onPromptValueChange:a,onSubmit:r,busy:i})=>{const[c,o]=l.useState(!1),d=t.prompt?.placeholder,m=qp(d)!==null,p=n.trim(),h=m&&d&&/^https?:\/\//i.test(p)&&!p.startsWith(d);l.useEffect(()=>{if(!c)return;const v=window.setTimeout(()=>o(!1),2e3);return()=>window.clearTimeout(v)},[c]);const u=async()=>{(await Ks(s)).ok?o(!0):B.error("Could not copy the sign-in link")},g=v=>{v.preventDefault(),!(i||p.length===0||h)&&r()};return e.jsxs("div",{className:"space-y-5 border-t border-[var(--surface-subtle)] pt-4",children:[e.jsxs(Me,{label:"1. Sign in",description:"Open the sign-in page and finish signing in.",children:[e.jsx(S,{asChild:!0,size:"sm",children:e.jsxs("a",{href:s,target:"_blank",rel:"noreferrer",children:[e.jsx(M,{name:"external-link",className:"size-4"}),"Open sign-in page"]})}),e.jsx(S,{variant:"ghost",size:"icon",className:tt,onClick:()=>{u()},"aria-label":c?"Sign-in link copied":"Copy sign-in link",title:c?"Copied":"Copy sign-in link",children:e.jsx(M,{name:c?"check":"file-copy",className:"size-4"})})]}),e.jsxs("form",{onSubmit:g,children:[e.jsxs(Me,{label:m?"2. Paste the redirect URL":"2. Paste the code",description:m?e.jsxs(e.Fragment,{children:["After you sign in, the browser opens a page starting with"," ",e.jsx("code",{className:"break-all text-foreground",children:d}),". That page may not load, which is expected. Copy the full address from the address bar and paste it here."]}):t.prompt?.message||"Copy the code shown after you sign in and paste it here.",controlClassName:"max-w-[32rem]",children:[e.jsx(ee,{className:"h-8 min-w-0 flex-1 rounded-md px-3",value:n,onChange:v=>a(v.target.value),placeholder:m?`${d}?code=…`:t.prompt?.placeholder,"aria-label":m?"Redirect URL":"Authorization code","aria-invalid":h?!0:void 0,autoComplete:"off",spellCheck:!1}),e.jsx(S,{type:"submit",size:"sm",disabled:i||p.length===0||!!h,children:i?"Connecting...":"Connect"})]}),h?e.jsxs("p",{className:"mt-2 typography-meta text-[var(--status-error)]",children:["This isn't the redirect address. Paste the URL that starts with ",d,"."]}):null]}),e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(M,{name:"loader-4",className:"size-4 shrink-0 animate-spin"}),m?"Waiting for sign-in. If your browser runs on the same machine as PiChamber, this finishes on its own.":"Waiting for the code…"]})]})},Jp=t=>{const{login:s,promptValue:n,onPromptValueChange:a,onSubmit:r,busy:i}=t;return s.authUrl&&s.prompt?.type==="manual_code"?e.jsx(Qp,{...t,authUrl:s.authUrl.url}):e.jsxs("div",{className:"space-y-3 border-t border-[var(--surface-subtle)] pt-3",children:[s.authUrl?e.jsx("a",{className:"typography-meta text-[var(--primary-base)] underline",href:s.authUrl.url,target:"_blank",rel:"noreferrer",children:s.authUrl.instructions||"Open"}):null,s.deviceCode?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("span",{className:"mr-2",children:"Device code"}),e.jsx("code",{className:"text-foreground",children:s.deviceCode.userCode}),e.jsx("a",{className:"ml-2 text-[var(--primary-base)] underline",href:s.deviceCode.verificationUri,target:"_blank",rel:"noreferrer",children:"Open"})]}):null,s.prompt?e.jsxs(Ee,{label:s.prompt.message||"Copy the authorization code from your browser and paste it here.",children:[s.prompt.type==="select"&&s.prompt.options?e.jsxs(Be,{value:n,onValueChange:a,children:[e.jsx($e,{size:Ge,className:hs,children:e.jsx(We,{})}),e.jsx(Ke,{children:s.prompt.options.map(c=>e.jsx(ke,{value:c.id,children:c.label},c.id))})]}):e.jsx(ee,{type:s.prompt.type==="secret"?"password":"text",value:n,onChange:c=>a(c.target.value),placeholder:s.prompt.placeholder,autoComplete:"off"}),e.jsx(S,{size:"sm",onClick:r,disabled:i||n.length===0,children:"Continue"})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Waiting for authorization…"})]})};function Yp(){const t=ga($=>$.selectedProviderId),s=ga($=>$.setSelectedProviderId),n=V($=>$.hiddenModels),a=V($=>$.toggleHiddenModel),r=V($=>$.hideAllModels),i=V($=>$.showAllModels),c=He($=>$.providers),o=He($=>$.settingsDefaultThinkingByModel),d=He($=>$.setSettingsDefaultThinkingByModel),m=He($=>$.setSettingsDefaultThinking),[p,h]=l.useState(null),[u,g]=l.useState(""),[v,x]=l.useState(""),[b,j]=l.useState(null),[k,P]=l.useState(!1),[E,y]=l.useState(null),[f,N]=l.useState(!1),[C,w]=l.useState(!1),[L,I]=l.useState(!1),[T,A]=l.useState(!1),[F,_]=l.useState(null),[z,K]=l.useState(new Set),[H,ne]=l.useState(""),[Z,ye]=l.useState(80),[oe,we]=l.useState(null),le=l.useCallback(async()=>{const{providers:$}=await _e.listProviders(et());h($),w(!1),He.getState().loadProviders({source:"providersPage:refresh"})},[]),ae=l.useCallback(async()=>{if(!L){I(!0);try{const{providers:$}=await _e.refreshProviders(et());h($),w(!1);const Y=He.getState();Y.invalidateProviderCache(),Y.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:$}))}catch{w(!0)}finally{I(!1)}}},[L]),pe=l.useCallback(async()=>{if(!T){A(!0),_(null);try{const{providers:$}=await _e.refreshProviders(et());h($),w(!1),_("success");const Y=He.getState();Y.invalidateProviderCache(),Y.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:$})),B.success("Model catalog refreshed")}catch{w(!0),_("error"),B.error("Could not refresh model catalog")}finally{A(!1)}}},[T]),ce=l.useCallback(async($,Y)=>{if($){we(Y);return}const ie=et();try{const{providers:X}=await _e.listProviders(ie);if(ie.runtimeKey!==qe())return;h(X),w(!1);const be=He.getState();be.invalidateProviderCache(),be.loadProviders({source:"providersPage:addModel"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:X}))}catch{if(ie.runtimeKey!==qe())return;B.error("Model added, but providers could not be refreshed")}},[]);l.useEffect(()=>{!oe||!c.some(Y=>Y.id===oe.providerId&&Y.models.some(ie=>ie.id===oe.modelId))||(we(null),ce(!1,oe))},[c,oe,ce]),l.useEffect(()=>{let $=!0;return le().catch(()=>{$&&w(!0)}),()=>{$=!1}},[le]),l.useEffect(()=>{let $=!0;const Y=et();return _e.getSettings(Y).then(ie=>{if(!$||Y.runtimeKey!==qe())return;const X=ie.pichamber.defaultThinkingByModel??{},be=ie.pichamber.defaultThinking,ze=He.getState().settingsDefaultThinkingByModel;(()=>{const Ye=Object.keys(ze),st=Object.keys(X);if(Ye.length!==st.length)return!1;for(const It of Ye)if(ze[It]!==X[It])return!1;return!0})()||d(X),be!==He.getState().settingsDefaultThinking&&m(be)}).catch(()=>{}),()=>{$=!1}},[m,d]),l.useEffect(()=>{if(!b||b.state!=="pending")return;let $=!0;const Y=window.setInterval(()=>{_e.getProviderLogin(b.providerId,b.id,et()).then(ie=>{$&&(j(ie.login),ie.login.state==="complete"&&le().catch(()=>w(!0)))}).catch(()=>{$&&j(ie=>ie&&{...ie,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})})},1e3);return()=>{$=!1,window.clearInterval(Y)}},[b,le]),l.useEffect(()=>{if(!b||b.state!=="complete"||!p)return;p.find(Y=>Y.id===b.providerId)?.authenticated===!0&&j(null)},[b,p]),l.useEffect(()=>{const $=Y=>{const ie=Y.detail;Array.isArray(ie)&&(h(ie),w(!1))};return window.addEventListener("pichamber:providers-refreshed",$),()=>window.removeEventListener("pichamber:providers-refreshed",$)},[]);const Q=p?.find($=>$.id===t)??null,G=Q?.id;l.useEffect(()=>{if(!G){y(null);return}let $=!0;return _e.getProviderConfig(G,et()).then(Y=>{$&&y(Y.config)}).catch(()=>{$&&y(null)}),()=>{$=!1}},[G]);const Pe=l.useCallback(async($,Y,ie)=>{const X=pn({providerId:$,modelId:Y});if(!X)return;const be=et(),ze=He.getState().settingsDefaultThinkingByModel,it={...ze};ie===null?delete it[X]:it[X]=ie,d(it),K(Ye=>new Set(Ye).add(X)),Te("saving");try{const Ye=await _e.setPiChamberDefaults({defaultThinkingByModel:{[X]:ie}},be);if(be.runtimeKey!==qe()){d(ze);return}const st=Ye.pichamber.defaultThinkingByModel??{};d(st),Ye.pichamber.defaultThinking!==void 0&&m(Ye.pichamber.defaultThinking),Te("saved")}catch{be.runtimeKey===qe()&&d(ze),Te("error")}finally{K(Ye=>{const st=new Set(Ye);return st.delete(X),st})}},[m,d]),re=l.useCallback(($,Y,ie)=>{Pe($,Y,ie)},[Pe]),Ne=l.useCallback(($,Y)=>{a($,Y)},[a]);l.useEffect(()=>{ye(80)},[G]);const ge=l.useMemo(()=>Q?Q.models.slice(0,Z):[],[Q,Z]),Ce=Q?Q.models.length>ge.length:!1,W=l.useMemo(()=>p?$p(p):[],[p]),de=l.useMemo(()=>{const $=H.trim().toLowerCase();return $?W.filter(Y=>{const ie=Y.label.toLowerCase(),X=Y.id.toLowerCase();return ie.includes($)||X.includes($)}):W},[W,H]);return{selectedProviderId:t,setSelectedProviderId:s,hiddenModels:n,toggleHiddenModel:a,hideAllModels:r,showAllModels:i,settingsDefaultThinkingByModel:o,setSettingsDefaultThinkingByModel:d,setSettingsDefaultThinking:m,providers:p,setProviders:h,apiKey:u,setApiKey:g,promptValue:v,setPromptValue:x,login:b,setLogin:j,customEditing:k,setCustomEditing:P,providerConfig:E,setProviderConfig:y,busy:f,setBusy:N,failed:C,setFailed:w,refreshing:L,setRefreshing:I,refreshingCatalog:T,setRefreshingCatalog:A,catalogRefreshFeedback:F,setCatalogRefreshFeedback:_,thinkingBusyKeys:z,setThinkingBusyKeys:K,providerQuery:H,setProviderQuery:ne,visibleCap:Z,setVisibleCap:ye,refresh:le,refreshProviders:ae,refreshCatalog:pe,refreshAfterModelAdd:ce,provider:Q,providerId:G,sortedProviders:W,filteredProviders:de,displayModels:ge,hasMore:Ce,saveCustomProvider:async $=>{N(!0);try{const Y=await _e.setProviderModels({providerId:$.providerID,label:$.name,baseUrl:$.config.options.baseURL,api:$.config.api,models:Object.values($.config.models).map(ie=>({...ie,providerId:$.providerID,...ie.name?{label:ie.name}:{}})),...$.config.options.headers?{headers:$.config.options.headers}:{},...$.config.env?.[0]?{apiKeyReference:`{env:${$.config.env[0]}}`}:{}},et());if(wn(Y)){B.info("Provider configuration saved. Connect it after active sessions are idle.");return}$.apiKey&&j((await _e.loginProvider({providerId:$.providerID,type:"api_key",apiKey:$.apiKey},et())).login),s($.providerID),P(!1),await le()}catch(Y){jn(Y)?B.info(Qt("Provider configuration")):w(!0)}finally{N(!1)}},startLogin:async $=>{if(!(!Q||f||$==="api_key"&&u.trim().length===0)){N(!0);try{const Y=await _e.loginProvider({providerId:Q.id,type:$,...$==="api_key"?{apiKey:u.trim()}:{}},et());g(""),x(""),j(Y.login),Y.login.state==="complete"&&await le()}catch{j({id:"",providerId:Q.id,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{N(!1)}}},submitPrompt:async()=>{if(!(!b||!b.prompt||v.length===0||f)){N(!0);try{const $=await _e.respondProviderLogin(b.providerId,b.id,v,et());x(""),j($.login),$.login.state==="complete"&&await le()}catch{try{const $=await _e.getProviderLogin(b.providerId,b.id,et());j($.login),$.login.state==="complete"&&await le()}catch{j($=>$&&{...$,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}}finally{N(!1)}}},logout:async()=>{if(!(!Q||f)){N(!0);try{await _e.logoutProvider({providerId:Q.id},et()),j(null),await le()}catch{w(!0)}finally{N(!1)}}},handleThinkingChange:re,handleToggleHidden:Ne}}const Xp=()=>{const{isMobile:t}=lt(),{selectedProviderId:s,setSelectedProviderId:n,hiddenModels:a,hideAllModels:r,showAllModels:i,settingsDefaultThinkingByModel:c,providers:o,apiKey:d,setApiKey:m,promptValue:p,setPromptValue:h,login:u,customEditing:g,setCustomEditing:v,providerConfig:x,busy:b,failed:j,refreshing:k,refreshingCatalog:P,catalogRefreshFeedback:E,thinkingBusyKeys:y,providerQuery:f,setProviderQuery:N,setVisibleCap:C,refreshProviders:w,refreshCatalog:L,refreshAfterModelAdd:I,provider:T,filteredProviders:A,displayModels:F,hasMore:_,saveCustomProvider:z,startLogin:K,submitPrompt:H,logout:ne,handleThinkingChange:Z,handleToggleHidden:ye}=Yp(),[oe,we]=l.useState(!1);if(j&&!o)return e.jsx(xe,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Providers are unavailable."}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{w()},disabled:k,children:[e.jsx(M,{name:"refresh",className:U("size-4",k&&"animate-spin")}),k?"Retrying…":"Retry"]})]})});if(g||s===Ss){const ae=x?.providerId===T?.id?x:null,pe=ae?Op({id:ae.providerId,name:ae.label,options:{baseURL:ae.baseUrl},api:ae.api,models:ae.models}):void 0;return e.jsx(xe,{title:ae?"Edit custom provider":"Custom provider",children:e.jsx(Fp,{existingProviderIDs:new Set(o?.map(ce=>ce.id)??[]),mode:ae?"edit":"create",initialValues:pe,allowExistingAuth:T?.authenticated===!0,busy:b,onSubmit:ce=>{z(ce)},onCancel:()=>{v(!1),n(T?.id??null)}})})}if(T){const ae=u?.providerId===T.id?u:null,pe=T.authenticated||ae?.state==="complete";return e.jsxs(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>n(null),"aria-label":"Back to providers",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{name:"arrow-left-s",className:"size-4"})}),e.jsx(ri,{providerId:T.id,className:"size-5 shrink-0"}),e.jsx("span",{className:"truncate",children:T.label})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:T.id}),children:[j?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,e.jsxs(q,{title:"Authentication",divider:!1,settingsItem:"providers.auth",headerAction:pe?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{ne()},disabled:b,children:b?"Disconnecting...":"Disconnect"}):null,children:[pe?e.jsxs("div",{className:"flex items-center gap-1.5 py-1.5 typography-ui-label",children:[e.jsx(M,{name:"check",className:"size-4 text-[var(--status-success)]"}),"Connected"]}):e.jsxs("div",{className:"space-y-4 py-1.5",children:[e.jsx(Ee,{label:"API key",children:e.jsxs("div",{className:"flex w-full max-w-[24rem] gap-2",children:[e.jsx(ee,{type:"password",value:d,onChange:ce=>m(ce.target.value),placeholder:"sk-...",autoComplete:"off"}),e.jsx(S,{size:"sm",onClick:()=>{K("api_key")},disabled:b||d.trim().length===0,children:b?"Saving...":"Save key"})]})}),e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{K("oauth")},disabled:b,children:"Reconnect"})]}),ae?.state==="pending"?e.jsx(Jp,{login:ae,promptValue:p,onPromptValueChange:h,onSubmit:()=>{H()},busy:b}):null,ae?.state==="failed"?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Authorization was declined or did not complete."}),ae.error?.message?e.jsx("p",{className:"typography-meta break-words text-muted-foreground",children:ae.error.message}):null]}):null]}),e.jsxs(q,{title:"Available models",settingsItem:"providers.models",titleAccessory:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>we(!0),"aria-label":`Add model to ${T.label}`,title:`Add model to ${T.label}`,children:e.jsx(M,{name:"add",className:"size-4"})}),headerAction:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{L()},disabled:P||b,"aria-label":"Refresh model catalog",title:"Refresh model catalog",children:e.jsx(M,{name:"refresh",className:U("size-4",P&&"animate-spin")})}),pe?e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>i(T.id),children:"Show all"}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>r(T.id,T.models.map(ce=>ce.id)),children:"Hide all"})]}):null,x?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>v(!0),children:"Update provider"}):null]}),children:[e.jsx("div",{"aria-live":"polite",className:"sr-only",children:P?"Refreshing model catalog":E==="success"?"Model catalog refreshed":E==="error"?"Could not refresh model catalog":""}),e.jsxs("div",{className:"divide-y divide-[var(--surface-subtle)]",children:[T.models.length===0?e.jsx("p",{className:"py-3 typography-meta text-muted-foreground",children:"No models available."}):F.map(ce=>{const Q=Gp(a,T.id,ce.id),G=pn({providerId:T.id,modelId:ce.id})??`${T.id}/${ce.id}`,Pe=c[G],re=li(Pe)?Pe:void 0,Ne=y.has(G);return e.jsx(mo,{providerId:T.id,model:ce,storedLevel:re,isBusy:Ne,isHidden:Q,isConnected:pe,onThinkingChange:Z,onToggleHidden:ye},ce.id)}),_?e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>C(ce=>ce+80),children:["Show ",Math.min(80,T.models.length-F.length)," more (",F.length," of"," ",T.models.length,")"]})}):null]})]}),e.jsx(Kp,{open:oe,onOpenChange:we,providerId:T.id,providerLabel:T.label,onAdded:ce=>{I(ce.deferred,ce)}})]})}return o===null?e.jsx(xe,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{w()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(M,{name:"refresh",className:U("size-4",k&&"animate-spin")})})}),children:e.jsx(q,{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(Vp,{count:6})})})}):A.length===0&&f.trim()===""&&o.length===0?e.jsx(xe,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:f,onChange:ae=>N(ae.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-full pl-8"})]}),e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{w()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(M,{name:"refresh",className:U("size-4",k&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Ss),children:[e.jsx(M,{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(M,{name:"cloud-off",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No providers"}),e.jsx(S,{variant:"outline",size:"sm",onClick:()=>n(Ss),children:"Add custom provider"})]})}):e.jsxs(xe,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:f,onChange:ae=>N(ae.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-full pl-8"}),f?e.jsx("button",{type:"button",onClick:()=>N(""),"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(M,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{w()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(M,{name:"refresh",className:U("size-4",k&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Ss),children:[e.jsx(M,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:[j?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Refresh failed — showing cached providers."}):null,e.jsx(q,{title:"Providers",divider:!1,settingsItem:"providers.browse",children:A.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 “",f,"”."]}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>N(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[A.map(ae=>e.jsx(Hp,{provider:ae,onSelect:n},ae.id)),e.jsxs("button",{type:"button",onClick:()=>n(Ss),"aria-label":"Add custom provider",className:U("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(M,{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"})]})]})})]})},Zp=({snippet:t,onSelect:s,showSourcePill:n=!0})=>{const a=t.source==="project"?"Project":t.source==="global"?"Global":t.source,r=t.description?.trim()||t.content.replace(/\s+/g," ").trim().slice(0,140)||"No description",i=r.length>=140||(t.description?.trim()?.length??0)===0&&t.content.length>140;return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.name} snippet, ${a}`,className:U("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[n?e.jsx("div",{className:"flex justify-start",children:e.jsx("span",{className:U("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:a})}):null,e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"truncate typography-ui-label font-medium text-foreground",children:["#",t.name]}),e.jsxs("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:[r,i?"…":null]})]})]})},ho=({count:t=6})=>e.jsx(e.Fragment,{children:Array.from({length:t}).map((s,n)=>e.jsxs("div",{className:"flex min-h-[118px] flex-col gap-3 rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4",children:[e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"h-5 w-16 animate-pulse rounded-full bg-muted"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"h-4 w-3/4 animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-full animate-pulse rounded bg-muted"}),e.jsx("div",{className:"h-3 w-2/3 animate-pulse rounded bg-muted"})]})]},n))}),em=t=>t.split(/[,\s]+/).map(s=>s.trim()).filter(s=>s.length>0),tm=()=>{const{isMobile:t}=lt(),s=Ca(),n=ot(O=>O.selectedSnippetId),a=ot(O=>O.snippetDraft),r=ot(O=>O.snippets),i=ot(O=>O.isLoading),c=ot(O=>O.setSelectedSnippet),o=ot(O=>O.setSnippetDraft),d=ot(O=>O.createSnippet),m=ot(O=>O.updateSnippet),p=ot(O=>O.deleteSnippet),h=ot(O=>O.loadSnippets),u=l.useMemo(()=>n?r.find(O=>O.id===n)??null:null,[n,r]),g=!!(a&&!u),[v,x]=l.useState(""),[b,j]=l.useState("global"),[k,P]=l.useState(""),[E,y]=l.useState(""),[f,N]=l.useState(""),[C,w]=l.useState(!1),[L,I]=l.useState(!1),[T,A]=l.useState(!1),F=l.useRef(""),_=l.useRef(""),z=l.useRef(""),K=l.useRef(""),H=l.useRef("global");l.useEffect(()=>{g&&a?(x(a.name),j(a.scope),P(a.description??""),y(""),N(a.content??""),F.current=a.content??"",_.current=a.description??"",z.current=a.name,K.current="",H.current=a.scope):u&&(x(u.name),j(u.source),P(u.description??""),y((u.aliases??[]).join(", ")),N(u.content),F.current=u.content,_.current=u.description??"",z.current=u.name,K.current=(u.aliases??[]).join(", "),H.current=u.source)},[a,g,u]);const ne=l.useCallback(()=>{g&&o(null),c(null)},[g,c,o]),Z=l.useCallback(async()=>{const O=v.trim().replace(/\s+/g,"-");if(!O){B.error("Snippet name is required");return}if(!/^[a-z0-9_-]+$/i.test(O)){B.error("Snippet name may only contain letters, numbers, dashes and underscores");return}if(!f.trim()){B.error("Snippet content is required");return}const J=em(E);if(J.length>10){B.error("Snippets support at most 10 aliases");return}for(const Ze of J)if(!/^[a-z0-9_-]+$/i.test(Ze)){B.error("Aliases may only contain letters, numbers, dashes and underscores");return}if(b==="project"&&!s?.trim()){B.error("Project snippets need an active project directory");return}w(!0);const te=g?await d(O,f,{description:k,aliases:J,scope:b,directory:s}):await m(u?.id??"",{name:O!==z.current?O:void 0,content:f!==F.current?f:void 0,description:k!==_.current?k:void 0,aliases:E.trim()!==K.current.trim()?J:void 0,...b!==H.current?{scope:b,...b==="project"&&s?{directory:s}:{}}:{}},s);w(!1),te?(g||o(null),B.success(g?"Snippet created":"Snippet updated")):B.error(g?"Failed to create snippet":"Failed to update snippet")},[E,f,d,k,s,g,v,b,u?.id,o,m]),ye=l.useCallback(async()=>{if(!u)return;I(!0);const O=await p(u.id,s);I(!1),O?(B.success("Snippet deleted"),A(!1)):B.error("Failed to delete snippet")},[p,s,u]),[oe,we]=l.useState(""),[le,ae]=l.useState("all"),[pe,ce]=l.useState(!1),Q=l.useCallback(async()=>{if(!pe){ce(!0);try{const{invalidateSnippetsLoadCache:O}=await Yt(async()=>{const{invalidateSnippetsLoadCache:J}=await import("./useAppFontEffects-COMvkffC.js").then(te=>te.f7);return{invalidateSnippetsLoadCache:J}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));O(s),await h(s)}finally{ce(!1)}}},[s,h,pe]);l.useEffect(()=>{h(s)},[s,h]);const G=l.useMemo(()=>[...r].sort((O,J)=>O.name.localeCompare(J.name)),[r]),Pe=l.useMemo(()=>{let O=G;le!=="all"&&(O=O.filter(te=>te.source===le));const J=oe.trim().toLowerCase();return J?O.filter(te=>{const Ze=te.name.toLowerCase().includes(J),$=(te.description??"").toLowerCase().includes(J),Y=te.content.toLowerCase().includes(J),ie=(te.aliases??[]).some(X=>X.toLowerCase().includes(J));return Ze||$||Y||ie}):O},[G,le,oe]),re=l.useMemo(()=>{let O=0,J=0;for(const te of r)te.source==="project"?J+=1:O+=1;return{all:r.length,global:O,project:J}},[r]),Ne=l.useCallback(async()=>{const O=new Set(r.map(Ze=>Ze.name.toLowerCase()));let J="new-snippet",te=1;for(;O.has(J.toLowerCase());)J=`new-snippet-${te++}`;o({name:J,scope:"global",content:"",description:""}),c(null)},[c,o,r]),ge=ot(O=>O.snippetsFile),Ce=l.useCallback(async()=>{if(!ge)return;(await Ks(ge)).ok?B.success("Snippets file path copied"):B.error("Could not copy the path")},[ge]),W=ge?e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Ce()},"aria-label":"Copy snippets file path",title:`Copy snippets file path: ${ge}`,children:e.jsx(M,{name:"file-copy",className:"size-4"})}):null;if(n!==null||a){if(!u&&!g)return e.jsx(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:ne,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{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(M,{name:"file-text",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The selected snippet was not found."}),e.jsx(S,{variant:"outline",size:"sm",onClick:ne,children:"Back to snippets"})]})});const O=g?v.trim()!==z.current||k!==_.current||f!==F.current||E.trim()!==K.current.trim()||b!==H.current:v.trim()!==z.current||f!==F.current||k!==_.current||E.trim()!==K.current.trim()||b!==H.current,J=O&&!C&&f.trim().length>0&&v.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:ne,"aria-label":"Back to snippets",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:g?"New snippet":`#${u?.name??v}`})]}),description:g?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a reusable text snippet"}):u?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:u.description}):void 0,headerEnd:!g&&u?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>A(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(M,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[e.jsx(q,{title:"Identity",divider:!1,settingsItem:"snippets.create",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 @xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"#"}),e.jsx(ee,{value:v,onChange:te=>x(te.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:["#",v.trim()||"name"]})," ","in chat. Letters, numbers, dashes and underscores only."]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Scope"}),e.jsxs(Be,{value:b,onValueChange:te=>j(te),children:[e.jsx($e,{size:Ge,className:"w-full",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"global",children:"Global"}),e.jsx(ke,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:b==="project"?"Available only in this project. Project snippets override same-named global snippets.":"Available in every project."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:k,onChange:te=>P(te.target.value),placeholder:"What does this snippet do?",className:"h-9 w-full"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Optional. Shown in the snippet card and autocomplete."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Aliases"}),e.jsx(ee,{value:E,onChange:te=>y(te.target.value),placeholder:"shortcut, alt-name",className:"h-9 w-full font-mono",spellCheck:!1,autoComplete:"off"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Optional alternate # triggers, comma-separated. They expand to the same literal text."})]})]})}),e.jsxs(q,{title:"Content",divider:!0,settingsItem:"snippets.content",info:"Snippets perform literal text replacement. Type #name in chat to insert the content.",headerAction:e.jsx("span",{className:"typography-micro text-muted-foreground",children:O?"Unsaved changes":"No changes"}),children:[e.jsx(Pn,{value:f,onChange:N,initialMode:g?"write":"preview",triggerPreview:`#${v.trim()||"name"}`},g?"new-snippet-editor":`snippet-editor:${u?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:ne,children:"Cancel"}),e.jsx(S,{size:"sm",onClick:()=>{Z()},disabled:!J,children:C?"Saving…":g?"Create snippet":"Save changes"})]})]}),!g&&u?e.jsx(q,{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 #",u.name,". This cannot be undone."]})]}),e.jsxs(S,{variant:"destructive",size:"sm",onClick:()=>A(!0),disabled:L,children:[e.jsx(M,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(bt,{open:T,onOpenChange:te=>!te&&A(!1),children:e.jsxs(yt,{className:"max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Delete snippet?"}),e.jsxs(kt,{children:["This will permanently delete #",u?.name??"",". This cannot be undone."]})]}),e.jsxs(ys,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>A(!1),disabled:L,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{ye()},disabled:L,children:L?"Deleting…":"Delete"})]})]})})]})}if(i&&r.length===0)return e.jsx(xe,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[W,e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:pe,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(M,{name:"refresh",className:U("size-4",pe&&"animate-spin")})})]}),children:e.jsx(q,{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(ho,{count:6})})})});const de=Pe.length===0&&r.length===0;return e.jsx(xe,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:oe,onChange:O=>we(O.target.value),placeholder:"Search snippets","aria-label":"Search snippets",className:"h-9 w-[15rem] max-w-full pl-8"}),oe?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(M,{name:"close",className:"size-4"})}):null]}),W,e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:pe,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(M,{name:"refresh",className:U("size-4",pe&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{Ne()},children:[e.jsx(M,{name:"add",className:"size-4"}),"New snippet"]})]}),children:de?e.jsx(q,{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(M,{name:"file-text",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No snippets yet"}),e.jsxs("p",{className:"typography-micro max-w-sm text-muted-foreground",children:["Snippets are reusable text. Create one and use it in chat as"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"#my-snippet"}),"."]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{Ne()},children:[e.jsx(M,{name:"add",className:"size-4"}),"New snippet"]})]})}):e.jsxs(q,{title:"Snippets",divider:!1,settingsItem:"snippets.create",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="all",onClick:()=>ae("all"),children:["All ",re.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="project",onClick:()=>ae("project"),children:["Project ",re.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="global",onClick:()=>ae("global"),children:["Global ",re.global]})]}),Pe.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:oe.trim()?`No snippets match “${oe}”.`:`No ${le} snippets.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{we(""),ae("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[Pe.map(O=>e.jsx(Zp,{snippet:O,onSelect:c,showSourcePill:le==="all"},`${O.source}:${O.id}`)),e.jsxs("button",{type:"button",onClick:()=>{Ne()},"aria-label":"Create new snippet",className:U("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(M,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New snippet"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Reusable text expansion"})]})]})]})})};function fo(t){let s=0;const n=/\$(\d+)/g;let a;for(;(a=n.exec(t))!==null;){const r=Number.parseInt(a[1]??"",10);Number.isSafeInteger(r)&&r>s&&(s=r)}return s}function sm(t){return`$${fo(t)+1}`}function nm(t){const s=fo(t);return s<1?null:`\${@:${s+1}}`}function am(t){const s=sm(t),n=nm(t);return[{value:s,label:s,hint:`Insert ${s}, the next argument`},{value:"$@",label:"$@",hint:"Insert $@, all arguments"},...n?[{value:n,label:n,hint:`Insert ${n}, all arguments after the positional ones`}]:[]]}const rm=async({previousName:t,nextName:s,previousLocation:n,nextLocation:a})=>{const r=dn.getState(),i=r.projects.find(x=>x.id===r.activeProjectId),c=i?.path?{id:i.id,path:i.path}:null,o=V.getState().globalDraftStarters??[],d=c?await ac(c):[];if(!(n==="project"?d:o).some(x=>x.type==="prompt"&&x.name===t))return!0;if(a==="project"&&!c)return!1;const h=x=>x.filter(b=>!(b.type==="prompt"&&b.name===t));let u=n==="global"?h(o):o,g=n==="project"?h(d):d;const v={type:"prompt",name:s,scope:a};return a==="project"?g.some(x=>x.type==="prompt"&&x.name===s)||(g=[...g,v]):u.some(x=>x.type==="prompt"&&x.name===s)||(u=[...u,v]),JSON.stringify(u)!==JSON.stringify(o)&&(V.getState().setGlobalDraftStarters(u),await Ie({draftStarters:u})),c&&JSON.stringify(g)!==JSON.stringify(d)?rc(c,g):!0},im=()=>{const{isMobile:t}=lt(),s=Ca(),n=dt(W=>W.selectedPromptId),a=dt(W=>W.promptDraft),r=dt(W=>W.prompts),i=dt(W=>W.isLoading),c=dt(W=>W.setSelectedPrompt),o=dt(W=>W.setPromptDraft),d=dt(W=>W.createPrompt),m=dt(W=>W.updatePrompt),p=dt(W=>W.deletePrompt),h=dt(W=>W.loadPrompts),u=l.useMemo(()=>n?r.find(W=>W.id===n)??null:null,[r,n]),g=!!(a&&!u),v=g||u?.editable===!0,x=!g&&u&&u.editable!==!0,[b,j]=l.useState(""),[k,P]=l.useState("global"),[E,y]=l.useState(""),[f,N]=l.useState(""),[C,w]=l.useState(!1),[L,I]=l.useState(!1),[T,A]=l.useState(!1),F=l.useRef(""),_=l.useRef(""),z=l.useRef(""),K=l.useRef("global");l.useEffect(()=>{g&&a?(j(a.name),P(a.location),y(a.description??""),N(a.content??""),F.current=a.name,_.current=a.description??"",z.current=a.content??"",K.current=a.location):u&&(j(u.name),P(u.location==="project"?"project":"global"),y(u.description??""),N(u.content??""),F.current=u.name,_.current=u.description??"",z.current=u.content??"",K.current=u.location==="project"?"project":"global")},[a,g,u]);const H=l.useCallback(()=>{g&&o(null),c(null)},[g,o,c]),ne=l.useCallback(async()=>{const W=b.trim().replace(/\s+/g,"-");if(!W){B.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(W)){B.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!f.trim()){B.error("Prompt content is required");return}if(k==="project"&&!s?.trim()){B.error("Project prompts need an active project directory");return}w(!0);const de=await d(W,f,{description:E,location:k,directory:s});w(!1),de==="busy"?B.info(Qt(`Prompt /${W}`)):de==="deferred"?B.info(qt(`Prompt /${W}`)):de?B.success(`Prompt /${W} created`):B.error("Failed to create prompt template")},[f,d,E,s,k,b]),Z=l.useCallback(async()=>{if(!u)return;const W=b.trim().replace(/\s+/g,"-");if(!W){B.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(W)){B.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!f.trim()){B.error("Prompt content is required");return}if(k==="project"&&!s?.trim()){B.error("Project prompts need an active project directory");return}w(!0);const de=F.current,O=K.current,J=await m(u.id,{...W!==F.current?{name:W}:{},...E!==_.current?{description:E}:{},...f!==z.current?{content:f}:{},...k!==K.current?{location:k}:{}},s);if(w(!1),J==="busy")B.info(Qt(`Prompt /${W}`));else if(J){let te=!0;if(de&&(W!==de||k!==O))try{te=await rm({previousName:de,nextName:W,previousLocation:O,nextLocation:k})}catch{te=!1}J==="deferred"?B.info(qt(`Prompt /${W}`)):B.success(`Prompt /${W} updated`),te||B.warning("The prompt was updated, but one or more pinned starters could not be updated.")}else B.error("Failed to update prompt template")},[f,E,s,k,b,u,m]),ye=l.useCallback(async()=>{if(!u)return;I(!0);const W=await p(u.id,s);I(!1),W==="busy"?B.info(Qt("Prompt template")):W==="deferred"?(B.info(qt("Prompt template")),A(!1)):W?(B.success("Prompt template deleted"),A(!1)):B.error("Failed to delete prompt template")},[p,s,u]),[oe,we]=l.useState(""),[le,ae]=l.useState("all"),[pe,ce]=l.useState(!1),Q=l.useCallback(async()=>{if(!pe){ce(!0);try{nc(s),await h(s)}finally{ce(!1)}}},[s,h,pe]);l.useEffect(()=>{h(s)},[s,h]);const G=l.useMemo(()=>[...r].sort((W,de)=>W.name.localeCompare(de.name)),[r]),Pe=l.useMemo(()=>{let W=G;le!=="all"&&(W=W.filter(O=>O.location===le));const de=oe.trim().toLowerCase();return de?W.filter(O=>O.name.toLowerCase().includes(de)||(O.description??"").toLowerCase().includes(de)||(O.content??"").toLowerCase().includes(de)):W},[le,oe,G]),re=l.useMemo(()=>{let W=0,de=0;for(const O of r)O.location==="project"?de+=1:O.location==="global"&&(W+=1);return{all:r.length,global:W,project:de}},[r]),Ne=l.useMemo(()=>am(f),[f]),ge=l.useCallback(()=>{const W=new Set(r.map(J=>J.name.toLowerCase()));let de="new-prompt",O=1;for(;W.has(de.toLowerCase());)de=`new-prompt-${O++}`;o({name:de,location:"global"}),c(null)},[r,o,c]);if(n!==null||a){if(!u&&!g)return e.jsx(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:H,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:"Not found"})]}),description:"This prompt template no longer exists.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(M,{name:"terminal",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The selected prompt template was not found."}),e.jsx(S,{variant:"outline",size:"sm",onClick:H,children:"Back to prompt templates"})]})});const W=u?.location==="project"?"Project":u?.location==="global"?"Global":u?.location??"Global",O=b.trim().replace(/\s+/g,"-")!==F.current||E!==_.current||f!==z.current||k!==K.current,J=O&&!C&&f.trim().length>0&&b.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(xe,{title:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:H,"aria-label":"Back to prompt templates",className:"-ml-1 h-7 w-7 p-0",children:e.jsx(M,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:g?"New prompt template":`/${u?.name??b}`})]}),description:g?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:"Create a native Pi command"}):u?.description?e.jsx("span",{className:"typography-settings-description text-muted-foreground",children:u.description}):void 0,headerEnd:!g&&u?.editable===!0?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>A(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(M,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[g?e.jsx(q,{title:"Identity",divider:!1,settingsItem:"prompt-templates.create",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 @xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"/"}),e.jsx(ee,{value:b,onChange:te=>j(te.target.value),placeholder:"review",className:"h-9 flex-1 font-mono",spellCheck:!1,autoComplete:"off"})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Used as"," ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["/",b.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(Be,{value:k,onValueChange:te=>P(te),children:[e.jsx($e,{size:Ge,className:"w-full",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"global",children:"Global"}),e.jsx(ke,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:k==="project"?"Available only in this trusted project.":"Available in every project."})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:E,onChange:te=>y(te.target.value),placeholder:"What does this command do?",className:"h-9 w-full"})]})]})}):e.jsxs(q,{title:"Details",divider:!1,settingsItem:"prompt-templates.create",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 typography-micro",children:[e.jsx("span",{className:U("inline-flex items-center rounded-full px-2.5 py-1 font-medium capitalize",u?.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:W}),u?.editable===!0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-[var(--status-success)]/10 px-2.5 py-1 font-medium text-[var(--status-success)]",children:[e.jsx(M,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]}):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 font-medium text-muted-foreground",children:"Read-only"})]}),x?e.jsx("p",{className:"typography-micro pt-3 text-muted-foreground",children:"This prompt was discovered from a package or path and cannot be edited."}):null,u?.location==="project"?e.jsx("p",{className:"typography-micro pt-2 text-muted-foreground",children:"Project prompts require a trusted project. Untrusted projects cannot create or edit them."}):null,v?e.jsxs("div",{className:"space-y-1.5 pt-4",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Scope"}),e.jsxs(Be,{value:k,onValueChange:te=>P(te),children:[e.jsx($e,{size:Ge,className:"w-full","aria-label":"Prompt template scope",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"global",children:"Global"}),e.jsx(ke,{value:"project",children:"Project"})]})]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:k==="project"?"Available only in this trusted project.":"Available in every project."})]}):null,v?e.jsxs("div",{className:"space-y-1.5 pt-4",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Name"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"/"}),e.jsx(ee,{value:b,onChange:te=>j(te.target.value),className:"h-9 flex-1 font-mono",spellCheck:!1,autoComplete:"off"})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Used as"," ",e.jsxs("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:["/",b.trim()||"name"]})," ","in chat. Letters, numbers, dashes and underscores only."]})]}):null,v?e.jsxs("div",{className:"space-y-1.5 pt-3",children:[e.jsx("label",{className:"typography-settings-field-label text-foreground",children:"Description"}),e.jsx(ee,{value:E,onChange:te=>y(te.target.value),className:"h-9 w-full"})]}):null]}),e.jsxs(q,{title:"Arguments",info:"Pi expands prompt arguments natively. PiChamber only inserts the /name command.",children:[e.jsxs("ul",{className:"typography-micro list-disc space-y-1 pl-5 text-muted-foreground",children:[e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$1"}),","," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$2"})," — positional arguments"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"$@"})," — all arguments"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"${1:-default}"})," — defaults when an argument is missing"]}),e.jsxs("li",{children:[e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"${@:2}"})," — slices such as arguments from position 2 onward"]})]}),e.jsxs("p",{className:"typography-micro pt-2 text-muted-foreground",children:["Example: ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"/review auth tests"})," supplies arguments that Pi substitutes into the template."]})]}),e.jsx(q,{title:"Content",divider:!0,settingsItem:"prompt-templates.content",info:"Prompt content supports Pi argument syntax such as $1 and $@. Pi expands it when the / command runs.",headerAction:v?e.jsx("span",{className:"typography-micro text-muted-foreground",children:O?"Unsaved changes":"No changes"}):void 0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Pn,{value:f,onChange:N,initialMode:g?"write":"preview",contentLabel:"Prompt content",placeholder:"Enter prompt content... Use markdown and Pi argument syntax such as $1 and $@.",triggerPreview:`/${b.trim()||"name"}`,triggerActionLabel:"Runs as",variableChips:Ne},g?"new-prompt-editor":`prompt-editor:${u?.id??""}`),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-2",children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{g?H():(j(F.current),P(K.current),y(_.current),N(z.current))},children:"Cancel"}),e.jsx(S,{size:"sm",onClick:()=>{g?ne():Z()},disabled:!J,children:C?"Saving…":g?"Create prompt":"Save changes"})]})]}):e.jsx(e.Fragment,{children:(u?.content??"").trim()?e.jsx("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] p-4 @xl:p-6",children:e.jsx(Na,{content:u?.content??"",stripFrontmatter:!0,className:"max-w-none"})}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"No content."})})}),!g&&u?.editable===!0?e.jsx(q,{title:"Danger zone",divider:!0,children:e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl border border-dashed border-border/60 bg-muted/20 px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Delete prompt"}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Permanently remove /",u.name,". This cannot be undone."]})]}),e.jsxs(S,{variant:"destructive",size:"sm",onClick:()=>A(!0),disabled:L,children:[e.jsx(M,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(bt,{open:T,onOpenChange:te=>!te&&A(!1),children:e.jsxs(yt,{className:"max-w-md",children:[e.jsxs(wt,{children:[e.jsx(jt,{children:"Delete prompt?"}),e.jsxs(kt,{children:["This will permanently delete /",u?.name??"",". This cannot be undone."]})]}),e.jsxs(ys,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>A(!1),disabled:L,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{ye()},disabled:L,children:L?"Deleting…":"Delete"})]})]})})]})}if(i&&r.length===0)return e.jsx(xe,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name.",headerEnd:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:pe,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(M,{name:"refresh",className:U("size-4",pe&&"animate-spin")})})}),children:e.jsx(q,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:e.jsx(ho,{count:6})})})});const Ce=Pe.length===0&&r.length===0;return e.jsx(xe,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name with Pi argument expansion.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(M,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:oe,onChange:W=>we(W.target.value),placeholder:"Search prompt templates","aria-label":"Search prompt templates",className:"h-9 w-[18rem] max-w-full pl-8"}),oe?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(M,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:pe,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(M,{name:"refresh",className:U("size-4",pe&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{ge()},children:[e.jsx(M,{name:"add",className:"size-4"}),"New prompt"]})]}),children:Ce?e.jsx(q,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(M,{name:"terminal",className:"size-8 text-subtle-foreground","aria-hidden":!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No prompt templates yet"}),e.jsxs("p",{className:"typography-micro max-w-sm text-muted-foreground",children:["Prompt templates are native Pi commands. Create one and run it in chat as"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:"/my-prompt"}),"."]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{ge()},children:[e.jsx(M,{name:"add",className:"size-4"}),"New prompt"]})]})}):e.jsxs(q,{title:"Prompt templates",divider:!1,settingsItem:"prompt-templates.create",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="all",onClick:()=>ae("all"),children:["All ",re.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="project",onClick:()=>ae("project"),children:["Project ",re.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":le==="global",onClick:()=>ae("global"),children:["Global ",re.global]})]}),Pe.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:oe.trim()?`No prompt templates match “${oe}”.`:`No ${le} prompt templates.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{we(""),ae("all")},children:"Clear filters"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[Pe.map(W=>{const de=W.editable===!0,O=W.location==="project"?"Project":W.location==="global"?"Global":W.location,J=W.description?.trim()||(W.content??"").replace(/\s+/g," ").trim().slice(0,140)||"No description";return e.jsxs("button",{type:"button",onClick:()=>c(W.id),"aria-label":`${W.name} prompt template, ${O}${de?"":", read-only"}`,className:U("group flex min-h-[118px] flex-col gap-3 rounded-xl border bg-[var(--surface-elevated)] p-4 text-left","border-border/60 hover:bg-interactive-hover hover:border-border","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsxs("div",{className:"flex justify-start gap-1.5",children:[e.jsx("span",{className:U("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 typography-micro font-medium capitalize",W.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:O}),de?null:e.jsx("span",{className:"inline-flex shrink-0 items-center rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:"Read-only"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"truncate typography-ui-label font-medium text-foreground",children:["/",W.name]}),e.jsx("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:J})]})]},W.id)}),e.jsxs("button",{type:"button",onClick:()=>{ge()},"aria-label":"Create new prompt template",className:U("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(M,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New prompt"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Native / command"})]})]})]})})},Wa=()=>{const t=rl(),s=V(o=>o.gitChangesViewMode),n=V(o=>o.setGitChangesViewMode),[a,r]=l.useState(!0),i=l.useMemo(()=>[{id:"flat",label:"Flat list"},{id:"tree",label:"Tree view"}],[]);l.useEffect(()=>{(async()=>{try{let d=null;if(!d){const m=ja()?.settings;if(m)try{const h=(await m.load())?.settings;h&&(d={gitChangesViewMode:h.gitChangesViewMode==="flat"||h.gitChangesViewMode==="tree"?h.gitChangesViewMode:void 0})}catch{}}if(!d){const m=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});m.ok&&(d=await m.json())}d&&(d.gitChangesViewMode==="flat"||d.gitChangesViewMode==="tree")&&n(d.gitChangesViewMode)}catch(d){console.warn("Failed to load git settings:",d)}finally{r(!1)}})()},[n]);const c=l.useCallback(o=>{o!==s&&(n(o),Ie({gitChangesViewMode:o}))},[s,n]);return a?null:e.jsxs(e.Fragment,{children:[e.jsx(q,{title:"Git preferences",divider:!1,children:e.jsxs("div",{className:vt,children:[e.jsx(at,{settingsItem:"git.changes-view",title:"Changes view",children:e.jsx(_t,{"aria-label":"Git changes view mode",children:i.map(o=>e.jsx(fs,{selected:s===o.id,onSelect:()=>{c(o.id)},label:o.label,ariaLabel:`Git changes view mode: ${o.label}`},o.id))})}),e.jsx(ve,{settingsItem:"git.gitignored-files",checked:t,onChange:il,label:"Display gitignored files",ariaLabel:"Display gitignored files"})]})}),e.jsx(om,{})]})},om=()=>{const s=kn().github??null,n=Vn(d=>d.status),a=Vn(d=>d.isLoading),r=Vn(d=>d.refresh);l.useEffect(()=>{s&&r(s)},[s,r]);const i=l.useCallback(()=>{s&&r(s,{force:!0})},[s,r]),c=l.useCallback(d=>{Ks(d).then(m=>{B[m.ok?"success":"error"](m.ok?"Command copied":"Failed to copy command")}).catch(()=>B.error("Failed to copy command"))},[]),o=n?.hosts??[];return e.jsx(q,{title:"GitHub",info:"PiChamber uses the GitHub CLI's active account on the server. There is no sign-in inside PiChamber.",children:e.jsxs("div",{className:gt,children:[s?!n&&a?e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-status",children:"Checking GitHub CLI…"}):n?e.jsxs(e.Fragment,{children:[e.jsx(Ee,{label:"GitHub CLI",info:"Version reported by gh on the machine running PiChamber.",settingsItem:"git.github-status",children:e.jsx("span",{className:"typography-ui text-foreground",children:n.installed?`Installed${n.version?` · ${n.version}`:""}`:"Not installed"})}),o.length===0?e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-account",children:"No signed-in hosts. Run gh auth login on the machine running PiChamber, then check again."}):o.map(d=>e.jsx(Ee,{label:d.host,info:"Token scopes reported by gh for this host.",settingsItem:"git.github-account",children:e.jsxs("span",{className:"typography-ui text-foreground",children:[d.authenticated&&d.login?`@${d.login}`:"Not signed in",d.scopes.length>0?` · ${d.scopes.join(", ")}`:""]})},d.host)),e.jsxs("div",{"data-settings-item":"git.github-scopes",className:"space-y-2",children:[e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Missing scopes show in place with the exact refresh command. Example:"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("code",{className:"rounded bg-[var(--surface-muted)] px-1.5 py-0.5 font-mono typography-micro text-foreground",children:"gh auth refresh -s repo"}),e.jsx("button",{type:"button",onClick:()=>c("gh auth refresh -s repo"),className:"rounded p-1 text-muted-foreground hover:bg-interactive-hover hover:text-foreground",title:"Copy gh auth refresh command","aria-label":"Copy gh auth refresh command",children:e.jsx(M,{name:"file-copy",className:"size-3.5"})})]})]}),e.jsx("div",{"data-settings-item":"git.github-check-again",children:e.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:i,disabled:a,children:[e.jsx(M,{name:"refresh",className:"size-3.5"}),a?"Checking…":"Check again"]})})]}):e.jsxs("div",{className:"space-y-2","data-settings-item":"git.github-status",children:[e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Could not reach the GitHub CLI."}),e.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:i,children:[e.jsx(M,{name:"refresh",className:"size-3.5"}),"Check again"]})]}):e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-status",children:"GitHub is not available in this runtime."}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"git push uses your normal git credentials. PiChamber never changes git or gh configuration."})]})})},Ar=()=>{const t=Fc();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},lm=()=>{const[t,s]=l.useState(()=>Ar());return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=[window.matchMedia("(display-mode: standalone)"),window.matchMedia("(display-mode: minimal-ui)"),window.matchMedia("(display-mode: fullscreen)"),window.matchMedia("(display-mode: window-controls-overlay)")],a=()=>{s(Ar())};a();for(const r of n)typeof r.addEventListener=="function"?r.addEventListener("change",a):typeof r.addListener=="function"&&r.addListener(a);return window.addEventListener("appinstalled",a),window.addEventListener("focus",a),()=>{for(const r of n)typeof r.removeEventListener=="function"?r.removeEventListener("change",a):typeof r.removeListener=="function"&&r.removeListener(a);window.removeEventListener("appinstalled",a),window.removeEventListener("focus",a)}},[]),t},cm=[{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."}],Ts="PiChamber - AI Coding Assistant",go=[{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."}],xo=[{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."}],dm=[{value:"none",label:"None"},{value:"dither",label:"Dither"},{value:"ascii",label:"ASCII"},{value:"halftone",label:"Halftone"},{value:"strands",label:"Strands"},{value:"grain",label:"Grain"}],um=[{value:"default",label:"Old"},{value:"new",label:"New"}],xa=t=>t==="portrait"||t==="landscape"?t:"system",vo=[{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."}],bo=[{id:"auto",label:"Auto",description:"Use locale week start."},{id:"monday",label:"Monday"},{id:"sunday",label:"Sunday"}],pm=[{id:"workspace",label:"Workspace"},{id:"folder",label:"By folder"},{id:"threads",label:"Threads"}],Lr=[{id:"timeline",label:"Timeline"}],mm={workspace:"Pick a folder, see its sessions.",folder:"Sessions under each folder.",timeline:"All sessions by date, archived too.",threads:"By state, with Snoozed below."},hm=[{id:"steer",label:"Steering"},{id:"queue",label:"Follow-up"}],fm=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],yo=5,gm=t=>t.metadata.name.trim().replace(/\s+(light|dark)$/i,"")||t.metadata.name.trim();function xm(t){const s=[],n=new Map;for(const a of t){const r=gm(a),i=a.metadata.variant,c=n.get(r.toLowerCase());if(c&&!c[i]){c[i]=a;continue}const o={key:c?a.metadata.id:r.toLowerCase(),name:r,[i]:a};c||n.set(r.toLowerCase(),o),s.push(o)}return s}function vm(t,s){return t.find(n=>n.light?.metadata.id===s||n.dark?.metadata.id===s)}function bm(t,s,n=yo){const a=t.slice(0,n);if(s===void 0||a.some(i=>i.key===s))return a;const r=t.find(i=>i.key===s);return!r||a.length<n?a:[...a.slice(0,n-1),r]}const mt={width:320,height:200};function ym({wallpaper:t,picture:s,ink:n,variant:a}){const r=Math.min(2,window.devicePixelRatio||1),i=document.createElement("canvas");i.width=Math.round(mt.width*r),i.height=Math.round(mt.height*r);const c=i.getContext("2d");if(!c)return null;const o=(d,m,p)=>{if(d.width===0||d.height===0)return;c.imageSmoothingEnabled=!p;const h=d.width*mt.width/m.width,u=d.height*mt.height/m.height;c.drawImage(d,0,0,h,u,0,0,i.width,i.height)};if(s){const d=document.createElement("canvas");ic({canvas:d,...mt,picture:s,variant:a,underPattern:t!=="none"}),o(d,mt,!1)}if(t!=="none"){const d=oc(t,mt.width,mt.height),m=document.createElement("canvas");lc({canvas:m,...d,ink:n,variant:a,wallpaper:t,picture:s,fade:"full"})?.draw(0);const h=s?1:a==="light"?4:2;for(let u=0;u<h;u+=1)o(m,d,cc(t))}return i.toDataURL("image/png")}const wo={},ps=new WeakMap,jo=({wallpaper:t,ink:s,variant:n})=>[t,n,s.r,s.g,s.b,Math.min(2,window.devicePixelRatio||1)].join("|");function va(t){return ps.get(t.picture??wo)?.get(jo(t))}function wm(t){const s=va(t);if(s!==void 0)return s;const n=t.picture??wo;let a=ps.get(n);a||(a=new Map,ps.set(n,a));const r=ym(t);return a.set(jo(t),r),r}function jm(t){const s=ps.get(t)?.get("thumbnail");if(s!==void 0)return s;const n=Math.min(2,window.devicePixelRatio||1),a=document.createElement("canvas");a.width=Math.round(mt.width*n),a.height=Math.round(mt.height*n);const r=a.getContext("2d");let i=null;if(r&&t.width>0&&t.height>0){const o=Math.max(a.width/t.width,a.height/t.height),d=a.width/o,m=a.height/o;r.imageSmoothingQuality="high",r.drawImage(t,(t.width-d)/2,(t.height-m)/2,d,m,0,0,a.width,a.height),i=a.toDataURL("image/jpeg",.85)}let c=ps.get(t);return c||(c=new Map,ps.set(t,c)),c.set("thumbnail",i),i}const km=/swiftshader|llvmpipe|softpipe|software|basic render/i;let en;function Nm(){return en!==void 0||(en=Cm()),en}function Cm(){if(typeof document>"u")return!1;const t=document.createElement("canvas");let s=null;try{s=t.getContext("webgl2")??t.getContext("webgl")}catch{s=null}if(!s)return!0;try{let n=String(s.getParameter(s.RENDERER)??"");if(/^webkit webgl$/i.test(n)){const a=s.getExtension("WEBGL_debug_renderer_info");a&&(n=String(s.getParameter(a.UNMASKED_RENDERER_WEBGL)??""))}return km.test(n)}catch{return!1}finally{s.getExtension("WEBGL_lose_context")?.loseContext()}}const Sm="grid max-w-[48rem] grid-cols-3 gap-2 space-y-0 @xl:gap-3 @3xl:grid-cols-6",ko="aspect-[16/10]",Pm=t=>{if(typeof window.requestIdleCallback=="function"){const n=window.requestIdleCallback(t,{timeout:200});return()=>window.cancelIdleCallback(n)}const s=window.setTimeout(t,0);return()=>window.clearTimeout(s)},Tm=({wallpaper:t,picture:s})=>{const{currentTheme:n}=ci(),a=n.colors.surface.foreground,r=n.metadata.variant==="dark"?"dark":"light",i=l.useMemo(()=>{const d=mc(a);return d?{wallpaper:t,picture:s,ink:{r:d.r,g:d.g,b:d.b},variant:r}:null},[t,s,a,r]),[c,o]=l.useState(()=>i?va(i):null);return l.useEffect(()=>{if(!i)return;const d=va(i);if(d!==void 0){o(d);return}return o(void 0),Pm(()=>o(wm(i)))},[i]),c?e.jsx("img",{src:c,alt:"",draggable:!1,className:"h-full w-full object-cover"}):null},Im=({picture:t,pending:s})=>{const n=l.useMemo(()=>t?jm(t):null,[t]);return e.jsx("div",{className:U(ko,"flex w-40 shrink-0 items-center justify-center overflow-hidden rounded-lg border",n?"border-[var(--interactive-border)]":"border-dashed border-[var(--interactive-border)]"),children:n?e.jsx("img",{src:n,alt:"Wallpaper picture",draggable:!1,className:"h-full w-full object-cover"}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:s?"Loading…":"No picture"})})},Mr=(t,s)=>t instanceof Error&&t.message?t.message:s,Em=()=>{const t=V(f=>f.draftWallpaper),s=V(f=>f.setDraftWallpaper),n=V(f=>f.draftWallpaperMotion),a=V(f=>f.setDraftWallpaperMotion),r=V(f=>f.draftWallpaperPicture),i=V(f=>f.draftWallpaperInSessions),c=V(f=>f.setDraftWallpaperInSessions),o=V(f=>f.setDraftWallpaperPicture),d=V(f=>f.draftWallpaperImageVersion),m=V(f=>f.setDraftWallpaperImageVersion),{picture:p,pending:h}=dc(d),u=l.useMemo(()=>Nm(),[]),g=r?p:null,v=l.useRef(null),[x,b]=l.useState(null),j=l.useCallback(f=>{s(f),Ie({draftWallpaper:f})},[s]),k=l.useCallback(async f=>{b("upload");try{const{version:N}=await uc(f);m(N),o(!0),Ie({draftWallpaperImageVersion:N,draftWallpaperPicture:!0})}catch(N){B.error(Mr(N,"The picture could not be saved"))}finally{b(null)}},[m,o]),P=l.useCallback(async()=>{b("remove");try{await pc(),m(null),o(!1),Ie({draftWallpaperImageVersion:null,draftWallpaperPicture:!1})}catch(f){B.error(Mr(f,"The picture could not be removed"))}finally{b(null)}},[m,o]),E=()=>v.current?.click(),y=f=>f==="none"&&!g?null:e.jsx(Tm,{wallpaper:f,picture:g});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(at,{title:"Wallpaper",info:"Behind the new-session screen, kept clear around the title and composer. Patterns are drawn in the theme's text colour, or in your picture's colours when it is on. Applies to every device connected to this server.",settingsItem:"appearance.wallpaper",description:u?"Hardware acceleration is off in this browser, so wallpapers are drawn on the processor. They still work; Moving wallpaper uses more of it.":void 0,children:e.jsx(_t,{"aria-label":"Wallpaper",className:Sm,children:dm.map(f=>e.jsx(hi,{selected:t===f.value,onSelect:()=>j(f.value),label:f.label,ariaLabel:f.label,previewClassName:ko,preview:y(f.value)},f.value))})}),e.jsx("input",{ref:v,type:"file",accept:"image/png,image/jpeg,image/webp","data-wallpaper-picture-input":"",className:"hidden","aria-hidden":"true",tabIndex:-1,onChange:f=>{const N=f.target.files?.[0];f.target.value="",N&&k(N)}}),e.jsxs(Es,{settingsItem:"appearance.wallpaper-picture",className:"space-y-3 pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Im,{picture:p,pending:d!==null&&h}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-settings-field-label text-foreground",children:"Picture"}),e.jsx(gs,{children:"Your own PNG, JPEG or WebP, stored on this server. With None it shows dimmed on its own; with a pattern it shows fainter and the pattern takes its colours. Dither, ASCII and Halftone also follow its light and dark."})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(S,{type:"button",size:"xs",variant:"outline",onClick:E,disabled:x!==null,children:x==="upload"?"Uploading…":d?"Replace":"Choose"}),d?e.jsx(S,{type:"button",size:"xs",variant:"ghost",onClick:()=>{P()},disabled:x!==null,children:x==="remove"?"Removing…":"Remove"}):null]})]})]}),e.jsx(ve,{checked:r&&d!==null,onChange:f=>{o(f),Ie({draftWallpaperPicture:f})},disabled:!d||x!==null,label:"Show behind the pattern",ariaLabel:"Show picture behind the pattern"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Es,{settingsItem:"appearance.wallpaper-sessions",className:"pt-0",children:e.jsx(ve,{checked:i,onChange:f=>{c(f),Ie({draftWallpaperInSessions:f})},disabled:t==="none"&&!(r&&d),label:"Show in open sessions",info:"Also show the wallpaper at the top of open sessions: fainter, faded out above the messages, and always still.",ariaLabel:"Show wallpaper in open sessions"})}),e.jsx(Es,{settingsItem:"appearance.wallpaper-motion",className:"pt-0",children:e.jsx(ve,{checked:n,onChange:f=>{a(f),Ie({draftWallpaperMotion:f})},disabled:!ol(t),label:"Moving wallpaper",info:"Patterns drift slowly, over your picture too. Grain and the picture itself stay still, and so does everything when your system asks for reduced motion.",ariaLabel:"Moving wallpaper"})})]})]})},Am=l.memo(function({theme:s}){const{surface:n,interactive:a,primary:r}=s.colors;return e.jsxs("span",{"aria-hidden":!0,"data-theme-swatch":s.metadata.id,className:"flex h-[22px] w-[34px] shrink-0 overflow-hidden rounded-[5px] border",style:{backgroundColor:n.background,borderColor:a.border},children:[e.jsx("span",{className:"w-[30%] border-r",style:{backgroundColor:n.muted,borderColor:a.border}}),e.jsxs("span",{className:"flex flex-1 flex-col justify-center gap-[3px] px-[4px]",children:[e.jsx("span",{className:"h-[2px] w-full rounded-full opacity-70",style:{backgroundColor:n.foreground}}),e.jsx("span",{className:"h-[3px] w-[60%] rounded-full",style:{backgroundColor:r.base}})]})]})}),Lm=({family:t,variant:s,selected:n,onSelect:a})=>{const r=t[s]??t.light??t.dark,i=t.light?t.dark?void 0:"Light only":"Dark only";return e.jsxs("div",{role:"radio",tabIndex:0,"aria-checked":n,"aria-label":i?`${t.name}, ${i.toLowerCase()}`:t.name,title:t.name,onClick:a,onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a())},className:U("flex min-w-0 max-w-full cursor-pointer items-center gap-2.5 rounded-lg border py-1.5 pl-1.5 pr-3 transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary-base)]",n?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-[var(--interactive-border)] hover:border-foreground/30"),children:[r?e.jsx(Am,{theme:r}):null,e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"truncate typography-settings-field-label font-normal text-foreground",children:t.name}),i?e.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:i}):null]})]})},Mm=({themes:t,currentTheme:s,themeMode:n,onThemeModeChange:a,onSelectFamily:r,showMobileLayoutSetting:i,mobileLayoutPreference:c,onMobileLayoutPreferenceChange:o,customThemesLoading:d,themesReloading:m,setThemesReloading:p,reloadCustomThemes:h,dockBadgeSupported:u,dockBadgeEnabled:g,setDockBadgeEnabled:v})=>{const[x,b]=l.useState(!1),j=l.useMemo(()=>xm(t),[t]),k=vm(j,s.metadata.id),P=x?j:bm(j,k?.key),E=s.metadata.variant,y=()=>{const f=Date.now();p(!0),h().finally(()=>{const N=Math.max(0,500-(Date.now()-f));window.setTimeout(()=>p(!1),N)})};return e.jsxs(q,{title:"Theme & wallpaper",divider:!1,contentClassName:"space-y-6",children:[e.jsx(Me,{label:"Mode",settingsItem:"appearance.color-mode",children:e.jsx(Os,{value:n,options:fm.map(f=>({value:f.value,label:f.label})),onChange:a,"aria-label":"Mode"})}),e.jsxs(at,{title:"Theme",settingsItem:"appearance.theme",children:[e.jsx(_t,{"aria-label":"Theme",className:"flex max-w-[48rem] flex-wrap gap-2 space-y-0",children:P.map(f=>e.jsx(Lm,{family:f,variant:E,selected:f.key===k?.key,onSelect:()=>r(f)},f.key))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 pt-3",children:[j.length>yo?e.jsx("button",{type:"button","aria-expanded":x,onClick:()=>b(f=>!f),className:"typography-settings-link",children:x?"Show fewer":`Show all ${j.length} themes`}):null,e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{type:"button",disabled:d||m,onClick:y,className:"typography-settings-link inline-flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:[e.jsx(M,{name:"restart",className:U("h-3.5 w-3.5",m&&"animate-spin")}),m?"Reloading themes...":"Reload themes"]}),e.jsx(gs,{children:"Import custom themes from ~/.config/pichamber/themes/"})]})]})]}),i&&e.jsx(Me,{label:"Mobile layout",children:e.jsx(Os,{value:c,options:um.map(f=>({value:f.value,label:f.label})),onChange:o,"aria-label":"Mobile layout"})}),e.jsx(Em,{}),u&&e.jsx(Es,{settingsItem:"appearance.dock-badge",children:e.jsx(ve,{checked:g,onChange:v,label:"Dock badge",info:"Show a count of chats with unseen activity on the macOS dock icon.",ariaLabel:"Dock badge"})})]})},Rm=({shouldShowTimeFormat:t,shouldShowWeekStart:s,timeFormatPreference:n,selectedTimeFormatLabel:a,onTimeFormatPreferenceChange:r,weekStartPreference:i,selectedWeekStartLabel:c,onWeekStartPreferenceChange:o})=>e.jsx(q,{title:"Localization",children:e.jsxs(Jt,{className:"gap-4 @md:grid-cols-2 @md:gap-8 @3xl:gap-10",children:[t&&e.jsx(Me,{label:"Time format",settingsItem:"appearance.time-format",children:e.jsxs(Be,{value:n,onValueChange:d=>r(d),children:[e.jsx($e,{"aria-label":"Select time format",size:Ge,className:xs,children:e.jsx(We,{children:a})}),e.jsx(Ke,{children:vo.map(d=>e.jsx(ke,{value:d.id,children:d.label},d.id))})]})}),s&&e.jsx(Me,{label:"Week starts on",settingsItem:"appearance.week-start",children:e.jsxs(Be,{value:i,onValueChange:d=>o(d),children:[e.jsx($e,{"aria-label":"Select week start",size:Ge,className:xs,children:e.jsx(We,{children:c})}),e.jsx(Ke,{children:bo.map(d=>e.jsx(ke,{value:d.id,children:d.label},d.id))})]})})]})}),Dm=({showPwaInstallNameSetting:t,pwaInstallName:s,setPwaInstallName:n,onApplyPwaInstallName:a,showPwaOrientationSetting:r,pwaOrientation:i,selectedPwaOrientationLabel:c,onApplyPwaOrientation:o,showMobileKeyboardModeSetting:d,mobileKeyboardMode:m,selectedMobileKeyboardModeLabel:p,onSetMobileKeyboardMode:h})=>e.jsxs(q,{title:"App install",divider:!1,className:"pb-0",contentClassName:gt,children:[t&&e.jsxs(Ee,{label:"Install app name",info:"Used by PWA installation process.",settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:us,children:[e.jsx(ee,{value:s,onChange:u=>n(u.target.value),onBlur:()=>{a(s)},onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),a(s))},className:"min-w-0 flex-1",maxLength:64,"aria-label":"PWA install app name"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{n(Ts),a("")},className:tt,"aria-label":"Reset install app name",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]}),r&&e.jsxs(Ee,{label:"Install orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:us,children:[e.jsxs(Be,{value:i,onValueChange:u=>{const g=xa(u);o(g)},children:[e.jsx($e,{"aria-label":"PWA install orientation",size:Ge,className:ar,children:e.jsx(We,{placeholder:"Select orientation",children:c})}),e.jsx(Ke,{children:go.map(u=>e.jsx(ke,{value:u.id,children:u.label},u.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{o("system")},disabled:i==="system",className:tt,"aria-label":"Reset install orientation",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]}),d&&e.jsxs(Ee,{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:us,children:[e.jsxs(Be,{value:m,onValueChange:u=>{const g=Xr(u);h(g)},children:[e.jsx($e,{"aria-label":"Mobile keyboard behavior",size:Ge,className:ar,children:e.jsx(We,{placeholder:"Select keyboard behavior",children:p})}),e.jsx(Ke,{children:xo.map(u=>e.jsx(ke,{value:u.id,children:u.label},u.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{h("native")},disabled:m==="native",className:tt,"aria-label":"Reset mobile keyboard behavior",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})]});function Rr(t,s,n){return Math.min(n,Math.max(s,t))}function _m(t){if(!Number.isFinite(t))return 0;const s=String(t);if(s.includes("e-")){const[,a]=s.split("e-");return Number(a)||0}const n=s.split(".");return n.length===2?n[1].length:0}function Dr(t,s){const n=_m(s);return n<=0?t:Number(t.toFixed(n))}const Ct=D.forwardRef(({value:t,onValueChange:s,min:n=-1/0,max:a=1/0,step:r=1,className:i,containerClassName:c,onBlur:o,disabled:d,fallbackValue:m,onClear:p,emptyLabel:h="—",...u},g)=>{const[v,x]=D.useState(()=>t==null?"":String(t)),{isMobile:b}=lt(),j=D.useRef(!1),k=D.useRef(null),P=D.useCallback(()=>{if(typeof document>"u"||typeof window>"u")return;k.current?.();const _=H=>{H.preventDefault(),H.stopPropagation(),H.stopImmediatePropagation?.(),k.current?.()},z=window.setTimeout(()=>{k.current?.()},700),K=()=>{window.clearTimeout(z),document.removeEventListener("click",_,!0),k.current=null};k.current=K,document.addEventListener("click",_,!0)},[]);D.useEffect(()=>()=>{k.current?.()},[]),D.useEffect(()=>{x(t==null?"":String(t))},[t]);const E=D.useMemo(()=>t!==void 0?t:m!==void 0?m:Number.isFinite(n)?n:0,[m,n,t]),y=D.useRef(E);D.useEffect(()=>{y.current=E},[E]);const f=D.useCallback(_=>{const z=Rr(_,n,a),K=Dr(z,r);y.current=K,s(K)},[a,n,s,r]),N=D.useCallback(_=>{const z=_.target.value;if(x(z),z.trim()===""){p?.();return}const K=Number(z);Number.isFinite(K)&&f(K)},[f,p]),C=D.useCallback(_=>{if(v.trim()===""){p||x(t==null?"":String(t)),o?.(_);return}const z=Number(v);if(!Number.isFinite(z))x(t==null?"":String(t));else{const K=Rr(z,n,a),H=Dr(K,r);H!==t?f(z):y.current=H,x(String(H))}o?.(_)},[f,v,a,n,o,p,r,t]),w=!!(d||E>=a),L=!!(d||E<=n),I=()=>{L||f(y.current-r)},T=()=>{w||f(y.current+r)},A=_=>z=>{z.preventDefault(),z.stopPropagation(),j.current=!0,P(),_()},F=_=>z=>{if(j.current){j.current=!1,z.preventDefault(),z.stopPropagation();return}_()};return b?e.jsxs("div",{className:U("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",c),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:L,onTouchStart:A(I),onClick:F(I),className:U("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",!L&&"active:bg-interactive-hover"),children:e.jsx(M,{name:"subtract",className:"block h-4 w-4"})}),e.jsx("div",{className:U("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]",i),"aria-live":"polite",children:t==null?h:v}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:w,onTouchStart:A(T),onClick:F(T),className:U("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",!w&&"active:bg-interactive-hover"),children:e.jsx(M,{name:"add",className:"block h-4 w-4"})})]}):e.jsxs("div",{className:U("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",c),children:[e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:L,onClick:()=>f(y.current-r),className:U("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(M,{name:"subtract",className:"block h-3.5 w-3.5"})}),e.jsx("input",{...u,ref:g,type:"text",inputMode:u.inputMode??"numeric",value:v,onChange:N,onBlur:C,disabled:d,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:U("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",i)}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:w,onClick:()=>f(y.current+r),className:U("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(M,{name:"add",className:"block h-3.5 w-3.5"})})]})});Ct.displayName="NumberInput";const Om=({shouldShow:t,uiFont:s,setUiFont:n,monoFont:a,setMonoFont:r,fontSize:i,setFontSize:c,terminalFontSize:o,setTerminalFontSize:d,editorFontSize:m,setEditorFontSize:p,padding:h,setPadding:u,inputBarOffset:g,setInputBarOffset:v,isMobile:x})=>e.jsxs(q,{title:"Density & type",contentClassName:gt,children:[t("fontSize")||t("terminalFontSize")?e.jsxs(Jt,{children:[t("fontSize")&&e.jsxs(Me,{label:"Interface font",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[e.jsxs(Be,{value:s,onValueChange:b=>n(b),children:[e.jsx($e,{"aria-label":"Select interface font",size:Ge,className:xs,children:e.jsx(We,{children:Ha.find(b=>b.id===s)?.label})}),e.jsx(Ke,{children:Ha.map(b=>e.jsx(ke,{value:b.id,children:e.jsx("span",{style:{fontFamily:b.stack},children:b.label})},b.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>n(Va),disabled:s===Va,className:tt,"aria-label":"Reset interface font",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]}),t("terminalFontSize")&&e.jsxs(Me,{label:"Code font",controlClassName:"w-full",children:[e.jsxs(Be,{value:a,onValueChange:b=>r(b),children:[e.jsx($e,{"aria-label":"Select code font",size:Ge,className:xs,children:e.jsx(We,{children:Ga.find(b=>b.id===a)?.label})}),e.jsx(Ke,{children:Ga.map(b=>e.jsx(ke,{value:b.id,children:e.jsx("span",{style:{fontFamily:b.stack},children:b.label})},b.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>r(qa),disabled:a===qa,className:tt,"aria-label":"Reset code font",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,t("fontSize")||t("terminalFontSize")||t("editorFontSize")?e.jsxs(Jt,{children:[t("fontSize")&&e.jsx(Me,{label:"Interface font size",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:i,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx("span",{className:Dt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>c(100),disabled:i===100,className:tt,"aria-label":"Reset font size",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("terminalFontSize")&&e.jsx(Me,{label:"Terminal font size",settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:o,onValueChange:d,min:9,max:52,step:1}),e.jsx("span",{className:Dt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>d(13),disabled:o===13,className:tt,"aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("editorFontSize")&&e.jsx(Me,{label:"Editor font size",settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:m,onValueChange:p,min:9,max:32,step:1}),e.jsx("span",{className:Dt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>p(13),disabled:m===13,className:tt,"aria-label":"Reset editor font size",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,t("spacing")||t("inputBarOffset")&&x?e.jsxs(Jt,{children:[t("spacing")&&e.jsx(Me,{label:"Spacing density",settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:h,onValueChange:u,min:50,max:200,step:5}),e.jsx("span",{className:Dt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>u(100),disabled:h===100,className:tt,"aria-label":"Reset spacing",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("inputBarOffset")&&x&&e.jsx(Me,{label:"Input bar offset",info:"Raise input bar to avoid OS-level screen obstructions like home bars.",settingsItem:"appearance.input-bar-offset",controlClassName:"w-full",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:g,onValueChange:v,min:0,max:100,step:5}),e.jsx("span",{className:Dt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>v(0),disabled:g===0,className:tt,"aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(M,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),vn=({width:t,tone:s="bg-foreground/60",className:n})=>e.jsx("div",{className:U("h-[3px] rounded-full",s,t,n)}),os=({width:t,selected:s=!1,chevron:n=!1})=>e.jsxs("div",{className:U("flex items-center gap-[4px] rounded-[3px] px-[3px] py-[2px]",s&&"bg-interactive-selection"),children:[e.jsx("div",{className:"h-[5px] w-[6px] shrink-0 rounded-[1.5px] bg-foreground/35"}),e.jsx(vn,{tone:"bg-foreground/60",width:t}),n&&e.jsx("div",{className:"ml-auto h-[3px] w-[3px] shrink-0 rounded-full bg-foreground/20"})]}),Bt=({title:t,details:s,selected:n=!1,quiet:a=!1})=>e.jsxs("div",{className:U("flex flex-col gap-[3px] rounded-[3px] px-[3px] py-[3px]",n&&"bg-interactive-selection"),children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(vn,{tone:a?"bg-foreground/35":"bg-foreground/60",width:t}),e.jsx("div",{className:"ml-auto h-[3px] w-[5px] shrink-0 rounded-full bg-foreground/20"})]}),e.jsx(vn,{tone:"bg-foreground/20",width:s})]}),na=({width:t,selected:s=!1})=>e.jsx("div",{className:U("flex items-center rounded-[3px] py-[2px] pl-[13px] pr-[3px]",s&&"bg-interactive-selection"),children:e.jsx(vn,{tone:s?"bg-foreground/60":"bg-foreground/35",width:t})}),zm=({width:t})=>e.jsxs("div",{className:"mx-[3px] flex shrink-0 items-center gap-[3px]",children:[e.jsx("div",{className:U("h-[2px] rounded-full bg-foreground/35",t)}),e.jsx("div",{className:"h-[2px] w-[3px] rounded-full bg-foreground/20"})]}),Um=({mode:t})=>e.jsxs("div",{"data-sidebar-view-preview":t,className:"flex h-full w-full bg-background",children:[e.jsxs("div",{className:"flex w-[58%] shrink-0 flex-col gap-[4px] overflow-hidden border-r border-border bg-sidebar p-[6px]",children:[t==="workspace"&&e.jsxs(e.Fragment,{children:[e.jsx(os,{width:"w-[55%]",selected:!0}),e.jsx(os,{width:"w-[70%]"}),e.jsx(os,{width:"w-[45%]"}),e.jsx("div",{className:"h-px shrink-0 bg-border"}),e.jsx(Bt,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx(Bt,{title:"w-[60%]",details:"w-[40%]"})]}),t==="folder"&&e.jsxs(e.Fragment,{children:[e.jsx(os,{width:"w-[60%]",chevron:!0}),e.jsx(na,{width:"w-[70%]",selected:!0}),e.jsx(na,{width:"w-[55%]"}),e.jsx(os,{width:"w-[45%]",chevron:!0}),e.jsx(na,{width:"w-[65%]"}),e.jsx(os,{width:"w-[55%]",chevron:!0})]}),t==="timeline"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-[3px] h-[2px] w-[28%] shrink-0 rounded-full bg-foreground/35"}),e.jsx(Bt,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx(Bt,{title:"w-[60%]",details:"w-[45%]"}),e.jsx("div",{className:"mx-[3px] h-[2px] w-[36%] shrink-0 rounded-full bg-foreground/35"}),e.jsx(Bt,{title:"w-[70%]",details:"w-[40%]"})]}),t==="threads"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-[3px] h-[2px] w-[30%] shrink-0 rounded-full bg-foreground/35"}),e.jsx(Bt,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx(Bt,{title:"w-[60%]",details:"w-[45%]"}),e.jsx("div",{className:"mt-auto h-px shrink-0 bg-border"}),e.jsx(zm,{width:"w-[34%]"})]})]}),e.jsxs("div",{className:"flex min-w-[0px] flex-1 flex-col gap-[4px] p-[6px]",children:[e.jsx("div",{className:"h-[3px] w-[80%] rounded-full bg-foreground/10"}),e.jsx("div",{className:"h-[3px] w-[55%] rounded-full bg-foreground/10"}),e.jsx("div",{className:"mt-auto h-[10px] rounded-[3px] border border-border"})]})]}),_r="grid max-w-[40rem] grid-cols-2 gap-2 @xl:grid-cols-4 @xl:gap-3",Fm=({shouldShow:t,sidebarViewMode:s,onSidebarViewModeChange:n,fileEditorKeymap:a,setFileEditorKeymap:r,autoSaveEnabled:i,setAutoSaveEnabled:c,expandedEditorToolbar:o,onExpandedEditorToolbarChange:d,wrapLinesByDefault:m,onWrapLinesByDefaultChange:p,showTerminalQuickKeysOnDesktop:h,setShowTerminalQuickKeysOnDesktop:u,showTerminalShellSetting:g,terminalShell:v,setTerminalShell:x,terminalShellOptions:b,terminalShellSupportsLogin:j,terminalLoginShellEnabled:k,setTerminalLoginShellEnabled:P})=>{const E=y=>e.jsx(hi,{selected:s===y.id,onSelect:()=>n(y.id),label:y.label,ariaLabel:y.label,preview:e.jsx(Um,{mode:y.id}),description:mm[y.id]},y.id);return e.jsxs(q,{title:"Navigation",contentClassName:"space-y-4",children:[t("sidebarViewMode")&&e.jsx(at,{title:"Sidebar view",info:"Applies to every device connected to this server.",settingsItem:"appearance.sidebar-view",children:e.jsxs(_t,{"aria-label":"Sidebar view",className:"space-y-0",children:[e.jsx("div",{className:_r,children:pm.map(E)}),e.jsx(Nn,{label:"Legacy views",divider:!1,className:"pt-4 pb-0",defaultOpen:Lr.some(y=>y.id===s),children:e.jsx("div",{className:_r,children:Lr.map(E)})})]})}),t("fileEditorKeymap")&&e.jsx(at,{title:"File editor keymap",settingsItem:"appearance.file-editor-keymap",children:e.jsx(_t,{"aria-label":"File editor keymap",children:["default","vim"].map(y=>e.jsx(fs,{selected:a===y,onSelect:()=>r(y),label:y==="default"?"Default":"Vim",ariaLabel:y==="default"?"Default":"Vim"},y))})}),e.jsxs("div",{className:vt,children:[t("autoSaveEnabled")&&e.jsx(ve,{checked:i,onChange:c,label:"Auto-save files",ariaLabel:"Auto-save files",info:"Automatically save file edits after you stop typing. Disable to require manual save.",settingsItem:"appearance.auto-save-enabled"}),t("expandedEditorToolbar")&&e.jsx(ve,{checked:o,onChange:d,label:"Always show editor toolbar (docked under the file tabs)",ariaLabel:"Always show editor toolbar",settingsItem:"appearance.expanded-editor-toolbar"}),t("wrapLinesByDefault")&&e.jsx(ve,{checked:m,onChange:p,label:"Wrap long lines in files and diffs",ariaLabel:"Wrap long lines in files and diffs",info:"Applies to the file viewer and diffs. The wrap toggle in each view overrides it until reload.",settingsItem:"appearance.wrap-lines-by-default"}),t("terminalQuickKeys")&&e.jsx(ve,{checked:h,onChange:u,label:"Terminal quick keys",ariaLabel:"Terminal quick keys",settingsItem:"appearance.terminal-quick-keys",info:"Show Esc, Ctrl, Arrows in terminal view"}),g&&e.jsx(Me,{label:"Terminal shell",info:"Restart the terminal to apply this change to the current session.",settingsItem:"appearance.terminal-shell",className:"pt-2",children:e.jsxs(Be,{value:v,onValueChange:y=>{ll(y)&&x(y)},children:[e.jsx($e,{"aria-label":"Select terminal shell",size:Ge,className:xs,children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"auto",children:"Auto"}),b.map(y=>e.jsx(ke,{value:y.id,children:y.name},y.id))]})]})}),g&&j&&e.jsx(ve,{checked:k,onChange:P,label:"Start as login shell",ariaLabel:"Start as login shell",settingsItem:"appearance.terminal-login-shell"})]})]})},Bm=({hasBehaviorSettings:t,showBehaviorMessageOptions:s,behaviorSectionDivider:n,shouldShow:a,diffLayoutPreference:r,setDiffLayoutPreference:i,followUpBehavior:c,setFollowUpBehavior:o,draftStartersVisible:d,onDraftStartersVisibleChange:m})=>t?e.jsxs(e.Fragment,{children:[s&&e.jsx(q,{title:"Message options",divider:n,children:e.jsxs(Jt,{className:"lg:gap-y-6",children:[a("diffLayout")&&e.jsx(at,{title:"Diff layout",children:e.jsx(_t,{"aria-label":"Diff layout",children:cm.map(p=>e.jsx(fs,{selected:r===p.id,onSelect:()=>i(p.id),label:p.label,ariaLabel:`Diff layout: ${p.label}`},p.id))})}),a("followUpBehavior")&&e.jsx(at,{title:"Follow-up behavior",info:"Follow-up waits until the agent finishes, then sends. Steering is delivered at the next supported tool or turn boundary. Follow-ups stay on this device.",settingsItem:"chat.follow-up-behavior",children:e.jsx(_t,{"aria-label":"Follow-up behavior",children:hm.map(p=>e.jsx(fs,{selected:c===p.id,onSelect:()=>o(p.id),label:p.label,ariaLabel:`Follow-up behavior: ${p.label}`},p.id))})})]})}),e.jsx(q,{title:"Features",contentClassName:vt,children:e.jsx(ve,{checked:d,onChange:m,label:"Show starters on new session screen",ariaLabel:"Show starters on the new session screen",settingsItem:"chat.draft-starters-visible"})})]}):null,$m=({perfHudEnabled:t,onPerfHudEnabledChange:s,processRecordingSupported:n,processRecordingEnabled:a,processRecordingActive:r,processRecordingSaving:i,processRecordingError:c,onProcessRecordingEnabledChange:o})=>e.jsxs(q,{title:"Diagnostics",contentClassName:vt,children:[e.jsx(ve,{checked:t,onChange:s,label:"Performance overlay",info:"Shows live frame time, long tasks, and render counters. Adds overhead. Stays on this device only, and is not a substitute for profile:idle or profile:session.",ariaLabel:"Performance overlay",settingsItem:"general.performance-overlay"}),n?e.jsx(ve,{checked:a,onChange:o,disabled:i,label:"Record Electron process performance",info:"Samples CPU and memory for Electron processes every 10 seconds and writes a local diagnostics file. Recording continues after restart until disabled.",description:c??(a&&!r?"Recording could not start. Disable it and try again.":void 0),ariaLabel:"Record Electron process performance",settingsItem:"general.process-performance-recording"}):null]}),Tn=({visibleSettings:t})=>{const{isMobile:s}=lt(),{terminal:n}=kn(),{browserTab:a}=lm(),r=V(R=>R.expandedEditorToolbar),i=V(R=>R.setExpandedEditorToolbar),c=V(R=>R.wrapLinesByDefault),o=V(R=>R.setWrapLinesByDefault),d=V(R=>R.autoSaveEnabled),m=V(R=>R.setAutoSaveEnabled),p=V(R=>R.fontSize),h=V(R=>R.setFontSize),u=V(R=>R.terminalFontSize),g=V(R=>R.setTerminalFontSize),v=V(R=>R.terminalShell),x=V(R=>R.setTerminalShell),b=V(R=>R.terminalLoginShells),j=V(R=>R.setTerminalLoginShells),k=V(R=>R.editorFontSize),P=V(R=>R.setEditorFontSize),E=V(R=>R.uiFont),y=V(R=>R.setUiFont),f=V(R=>R.monoFont),N=V(R=>R.setMonoFont),C=V(R=>R.padding),w=V(R=>R.setPadding),L=V(R=>R.inputBarOffset),I=V(R=>R.setInputBarOffset),T=V(R=>R.mobileKeyboardMode),A=V(R=>R.setMobileKeyboardMode),F=V(R=>R.diffLayoutPreference),_=V(R=>R.setDiffLayoutPreference),z=V(R=>R.showTerminalQuickKeysOnDesktop),K=V(R=>R.setShowTerminalQuickKeysOnDesktop),H=V(R=>R.fileEditorKeymap),ne=V(R=>R.setFileEditorKeymap),Z=Qa(R=>R.followUpBehavior),ye=Qa(R=>R.setFollowUpBehavior),oe=V(R=>R.timeFormatPreference),we=V(R=>R.setTimeFormatPreference),le=V(R=>R.weekStartPreference),ae=V(R=>R.setWeekStartPreference),pe=V(R=>R.sidebarViewMode),ce=V(R=>R.setSidebarViewMode),Q=V(R=>R.draftStartersVisible),G=V(R=>R.setDraftStartersVisible),{currentTheme:Pe,availableThemes:re,themeMode:Ne,setThemeMode:ge,setThemeFamily:Ce,customThemesLoading:W,reloadCustomThemes:de}=ci(),[O,J]=l.useState(!1),te=l.useMemo(()=>Oe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),Ze=V(R=>R.dockBadgeEnabled),$=V(R=>R.setDockBadgeEnabled),Y=l.useSyncExternalStore(cl,dl,()=>!1),ie=Oe(),[X,be]=l.useState(!1),[ze,it]=l.useState(!1),[Ye,st]=l.useState(!1),[It,Gs]=l.useState(!1),[In,Ft]=l.useState(null),En=l.useCallback(R=>{G(R),Ie({draftStartersVisible:R})},[G]),An=l.useCallback(R=>{i(R),Ie({expandedEditorToolbar:R})},[i]),Ln=l.useCallback(R=>{o(R),Ie({wrapLinesByDefault:R})},[o]),Et=l.useCallback(R=>{we(R),Ie({timeFormatPreference:R})},[we]),Mn=l.useCallback(R=>{ae(R),Ie({weekStartPreference:R})},[ae]),Rn=l.useCallback(R=>{ce(R),Ie({sidebarViewMode:R})},[ce]),ue=R=>t?t.includes(R):!0,ns=ue("perfHud");l.useEffect(()=>{if(!ns||!ie){be(!1),it(!1),st(!1),Ft(null);return}let R=!1;return Ja().then(fe=>{R||(be(fe?.supported===!0),it(fe?.enabled===!0),st(fe?.active===!0),Ft(fe?.enabled===!0&&fe.active!==!0?"Recording could not start. Disable it and try again.":null))}),()=>{R=!0}},[ie,ns]),l.useEffect(()=>{if(!ns||!ie||!ze)return;let R=!1;const fe=window.setInterval(()=>{Ja().then(nt=>{R||!nt?.supported||(st(nt.active),nt.active||Ft("Recording stopped after a file write failure. Disable it and try again."))})},1e4);return()=>{R=!0,window.clearInterval(fe)}},[ie,ze,ns]);const Dn=l.useCallback(async R=>{if(!X||It)return;const fe=ze,nt=Ye;it(R),Gs(!0),Ft(null);try{const Xe=await ul(R);if(!Xe?.supported||Xe.enabled!==R||R&&!Xe.active)throw new Error("Failed to update process performance recording");it(Xe.enabled),st(Xe.active)}catch{it(fe),st(nt),Ft("Failed to update process performance recording.")}finally{Gs(!1)}},[Ye,ze,It,X]),ws=ue("theme"),_n=ue("theme")||ue("timeFormat")||ue("weekStart"),qs=s&&Ht()&&!Oe(),as=ue("theme")||qs||ue("pwaInstallName")||ue("pwaOrientation")||ue("timeFormat")||ue("weekStart"),js=ue("fontSize")||ue("terminalFontSize")||ue("editorFontSize")||ue("spacing")||ue("inputBarOffset")&&s,ks=ue("sidebarViewMode")||ue("terminalQuickKeys")||ue("terminalShell")||ue("terminalLoginShell")||ue("fileEditorKeymap")||ue("autoSaveEnabled")||ue("expandedEditorToolbar")||ue("wrapLinesByDefault"),On=ue("diffLayout")||ue("followUpBehavior"),zn=ue("diffLayout")||ue("followUpBehavior"),Un=as||js||ks,At=ue("pwaInstallName")&&Ht()&&a&&!Oe(),se=ue("pwaOrientation")&&Ht()&&!Oe(),je=ue("mobileKeyboardMode")&&Ht()&&!Oe()&&pl(),Qe=ue("terminalShell")||ue("terminalLoginShell"),[me,ct]=l.useState([]),[ut,Se]=l.useState(0);l.useEffect(()=>yn(()=>{ct([]),Se(R=>R+1)}),[]),l.useEffect(()=>{let R=!1;if(!(!Qe||!n.listShells))return n.listShells().then(fe=>{R||ct(fe)}).catch(()=>{R||ct([])}),()=>{R=!0}},[Qe,n,ut]);const pt=l.useMemo(()=>{const R=me.filter(fe=>fe.id!=="auto");return v==="auto"||R.some(fe=>fe.id===v)?R:[{id:v,name:v,supportsLogin:!1},...R]},[me,v]),Qs=me.find(R=>R.id===v)?.supportsLogin===!0,Fn=b.includes(v),Bn=R=>{j(R?[...b.filter(fe=>fe!==v),v]:b.filter(fe=>fe!==v))},[Ns,Js]=l.useState(()=>Mc()),[$n,Lt]=l.useState(""),[rs,Nt]=l.useState("system"),Ys=l.useMemo(()=>vo.find(fe=>fe.id===oe)?.label??"Auto",[oe]),Wn=l.useMemo(()=>bo.find(fe=>fe.id===le)?.label??"Auto",[le]),Ao=l.useMemo(()=>{const R=go.find(fe=>fe.id===rs);return R?R.label:void 0},[rs]),Lo=l.useMemo(()=>{const R=xo.find(fe=>fe.id===T);return R?R.label:void 0},[T]),Mo=l.useCallback(R=>{R!==Ns&&(Js(R),Rc(R),window.location.reload())},[Ns]),Ro=l.useCallback(async R=>{if(typeof window>"u")return;const fe=window,Xe=R.trim().replace(/\s+/g," ").slice(0,64);if(await Ie({pwaAppName:Xe}),typeof fe.__PICHAMBER_SET_PWA_INSTALL_NAME__=="function"){const Ka=fe.__PICHAMBER_SET_PWA_INSTALL_NAME__(Xe);Lt(Ka);return}Lt(Xe||Ts),fe.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Do=l.useCallback(async R=>{if(typeof window>"u")return;const fe=window,nt=xa(R);if(await Ie({pwaOrientation:nt}),typeof fe.__PICHAMBER_SET_PWA_ORIENTATION__=="function"){const Xe=fe.__PICHAMBER_SET_PWA_ORIENTATION__(nt);Nt(Xe);return}Nt(nt),fe.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return l.useEffect(()=>{if(typeof window>"u"||!At&&!se&&!je)return;let R=!1;return(async()=>{try{const nt=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!nt.ok){R||Lt(Ts);return}const Xe=await nt.json().catch(()=>({})),_o=(typeof Xe?.pwaAppName=="string"?Xe.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),Oo=xa(Xe?.pwaOrientation),zo=Xr(Xe?.mobileKeyboardMode);R||(At&&Lt(_o||Ts),se&&Nt(Oo),je&&A(zo))}catch{R||(At&&Lt(Ts),se&&Nt("system"),je&&A("native"))}})(),()=>{R=!0}},[A,je,At,se]),e.jsxs(e.Fragment,{children:[as&&ws&&e.jsx(Mm,{themes:re,currentTheme:Pe,themeMode:Ne,onThemeModeChange:ge,onSelectFamily:R=>Ce(R.light?.metadata.id,R.dark?.metadata.id),showMobileLayoutSetting:qs,mobileLayoutPreference:Ns,onMobileLayoutPreferenceChange:Mo,customThemesLoading:W,themesReloading:O,setThemesReloading:J,reloadCustomThemes:de,dockBadgeSupported:te,dockBadgeEnabled:Ze,setDockBadgeEnabled:$}),ks&&e.jsx(Fm,{shouldShow:ue,sidebarViewMode:pe,onSidebarViewModeChange:Rn,fileEditorKeymap:H,setFileEditorKeymap:ne,autoSaveEnabled:d,setAutoSaveEnabled:m,expandedEditorToolbar:r,onExpandedEditorToolbarChange:An,wrapLinesByDefault:c,onWrapLinesByDefaultChange:Ln,showTerminalQuickKeysOnDesktop:z,setShowTerminalQuickKeysOnDesktop:K,showTerminalShellSetting:Qe,terminalShell:v,setTerminalShell:x,terminalShellOptions:pt,terminalShellSupportsLogin:Qs,terminalLoginShellEnabled:Fn,setTerminalLoginShellEnabled:Bn}),as&&_n&&e.jsx(Rm,{shouldShowTimeFormat:ue("timeFormat"),shouldShowWeekStart:ue("weekStart"),timeFormatPreference:oe,selectedTimeFormatLabel:Ys,onTimeFormatPreferenceChange:Et,weekStartPreference:le,selectedWeekStartLabel:Wn,onWeekStartPreferenceChange:Mn}),js&&e.jsx(Om,{shouldShow:ue,uiFont:E,setUiFont:y,monoFont:f,setMonoFont:N,fontSize:p,setFontSize:h,terminalFontSize:u,setTerminalFontSize:g,editorFontSize:k,setEditorFontSize:P,padding:C,setPadding:w,inputBarOffset:L,setInputBarOffset:I,isMobile:s}),e.jsx(Bm,{hasBehaviorSettings:On,showBehaviorMessageOptions:zn,behaviorSectionDivider:Un,shouldShow:ue,diffLayoutPreference:F,setDiffLayoutPreference:_,followUpBehavior:Z,setFollowUpBehavior:ye,draftStartersVisible:Q,onDraftStartersVisibleChange:En}),ue("perfHud")&&e.jsx($m,{perfHudEnabled:Y,onPerfHudEnabledChange:ml,processRecordingSupported:X,processRecordingEnabled:ze,processRecordingActive:Ye,processRecordingSaving:It,processRecordingError:In,onProcessRecordingEnabledChange:Dn}),as&&(At||se||je)&&e.jsx(Nn,{label:"Show legacy options",children:e.jsx(Dm,{showPwaInstallNameSetting:At,pwaInstallName:$n,setPwaInstallName:Lt,onApplyPwaInstallName:Ro,showPwaOrientationSetting:se,pwaOrientation:rs,selectedPwaOrientationLabel:Ao,onApplyPwaOrientation:Do,showMobileKeyboardModeSetting:je,mobileKeyboardMode:T,selectedMobileKeyboardModeLabel:Lo,onSetMobileKeyboardMode:R=>{A(R),Ie({mobileKeyboardMode:R})}})})]})},Wm=[{value:"system",label:"System browser"},{value:"pichamber",label:"PiChamber browser"}],Km=()=>{const t=V(o=>o.chatLinkTarget),s=V(o=>o.setChatLinkTarget),[n,a]=l.useState(!1),[r,i]=l.useState(!1),c=async()=>{i(!0);try{await Sc(),B.success("Browsing data cleared"),a(!1)}catch(o){B.error(o instanceof Error?o.message:"Could not clear browsing data")}finally{i(!1)}};return e.jsx(q,{title:"Web browser",children:e.jsxs("div",{className:gt,children:[e.jsx(Ee,{settingsItem:"general.chat-link-target",label:"Open chat links in",info:"Applies to a plain click. Cmd-click, Ctrl-click, and middle-click still use the system browser.",children:e.jsx(Os,{value:t,onChange:s,options:Wm})}),e.jsx(Ee,{settingsItem:"general.browser-data",label:"Browsing data",info:"Pages loaded through the server keep their cookies and sign-ins on the server, shared by every device.",children:n?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:`${he} max-w-sm [text-wrap:pretty]`,children:"This signs you out of every site in the server browser. Pages open on any device reload, signed out."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(S,{type:"button",size:"sm",variant:"destructive",disabled:r,onClick:()=>{c()},children:"Clear browsing data"}),e.jsx(S,{type:"button",size:"sm",variant:"ghost",disabled:r,onClick:()=>a(!1),children:"Cancel"})]})]}):e.jsx(S,{type:"button",size:"sm",variant:"outline",onClick:()=>a(!0),children:"Clear"})})]})})},Or=1,zr=365,tn=7,Ur=30,Fr=t=>t===1?"day":"days",Hm=({archiveAfterDays:t,deleteAfterDays:s,onArchiveAfterDaysChange:n,onDeleteAfterDaysChange:a})=>{const r=t===0,i=s===0,c=!r&&!i,o=c?t:tn,d=c?s:Ur,m=`Only archived sessions are deleted, counted from the day each one was archived. ${c?"With these settings":`With archiving at ${o} days and deleting at ${d}`}, a session is deleted ${o+d} days after you last used it.`;return e.jsxs(e.Fragment,{children:[e.jsx(Ee,{settingsItem:"sessions.auto-archive",label:"Archive idle sessions after",info:"Pinned, running, and snoozed sessions, sessions waiting on you, and the open session are never archived automatically. Leave empty to archive only by hand.",description:r?`Suggested: ${tn} days, so the sidebar shows what you're working on.`:void 0,children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:r?void 0:t,fallbackValue:tn,onValueChange:n,onClear:()=>n(0),emptyLabel:"Off",placeholder:"Off",min:Or,max:zr,step:1,"aria-label":"Days before an idle session is archived",className:"w-20 tabular-nums"}),e.jsx("span",{className:Dt,children:Fr(t)}),r?e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"ml-1 !font-normal",onClick:()=>n(tn),children:"Turn on"}):null]})}),e.jsx(Ee,{settingsItem:"sessions.auto-delete",label:"Delete archived sessions",info:m,description:i?void 0:"Deleted sessions can't be restored.",children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:i?void 0:s,fallbackValue:Ur,onValueChange:a,onClear:()=>a(0),emptyLabel:"Off",placeholder:"Off",min:Or,max:zr,step:1,"aria-label":"Days after archiving before a session is deleted",className:"w-20 tabular-nums"}),e.jsx("span",{className:Dt,children:`${Fr(s)} after archiving`})]})})]})},No=()=>{const t=V(h=>h.sessionAutoArchiveAfterDays),s=V(h=>h.sessionAutoDeleteAfterDays),n=V(h=>h.setSessionAutoArchiveAfterDays),a=V(h=>h.setSessionAutoDeleteAfterDays),r=l.useCallback(h=>{n(h),Ie({sessionAutoArchiveAfterDays:h})},[n]),i=l.useCallback(h=>{a(h),Ie({sessionAutoDeleteAfterDays:h})},[a]),{archiveCandidates:c,deleteCandidates:o,isRunning:d,runCleanup:m}=hc({autoRun:!1}),p=l.useCallback(async()=>{const h=await m(),u=h.archive.completedIds.length,g=h.delete.completedIds.length,v=h.archive.failedIds.length,x=h.delete.failedIds.length;if(h.skippedReason==="running"){B.message("Archive and delete is already running. Try again in a moment.");return}if(h.skippedReason==="disabled"){B.message("Archiving and deleting are both off");return}if(u+g+v+x===0){B.message(h.skippedReason==="partial"||h.skippedReason==="stale"?"Could not check every folder. Try again later.":"No sessions to archive or delete");return}u>0&&B.success(`Archived ${Xs(u)}`),g>0&&B.success(`Deleted ${Xs(g)}`),v>0&&B.error(`Could not archive ${Xs(v)}`),x>0&&B.error(`Could not delete ${Xs(x)}`)},[m]);return e.jsxs(q,{title:"Archive and delete",contentClassName:"space-y-4",info:"Archived sessions move to the Archived section at the bottom of the sidebar. Search and Timeline show them in place, and sending a message brings one back.",children:[e.jsx(Hm,{archiveAfterDays:t,deleteAfterDays:s,onArchiveAfterDaysChange:r,onDeleteAfterDaysChange:i}),e.jsx(Ee,{settingsItem:"sessions.auto-cleanup",label:"Run now",description:`Ready to archive: ${c.length}. Ready to delete: ${o.length}.`,children:e.jsx(S,{type:"button",variant:"outline",size:"xs",onClick:p,disabled:d,className:"!font-normal",children:d?"Running...":"Archive and delete now"})})]})},Vm=t=>{if(!t)return;const s=t.providerId.trim(),n=t.modelId.trim();if(!(!s||!n))return`${s}/${n}`},aa=t=>{const s=fc(t??void 0);return s?{providerId:s.providerId,modelId:s.modelId}:null},Gm=(t,s={})=>{if(!t)return{};const n={};if(!s.defaultModel){const a=aa(typeof t.defaultModel=="string"?t.defaultModel:void 0);a&&(n.defaultModel=a)}if(!s.smallModel&&t.smallModelUseDefault===!1){const a=aa(typeof t.smallModelOverride=="string"?t.smallModelOverride:void 0);a&&(n.smallModel=a)}if(!s.walkthroughModel){const a=aa(typeof t.walkthroughModelOverride=="string"?t.walkthroughModelOverride:void 0);a&&(n.walkthroughModel=a)}return n},qm=t=>!!(t.defaultModel||t.smallModel||t.walkthroughModel),ra=()=>({runtimeKey:qe()}),sn="__pi_fallback__",ia={terminal:"Terminal UI",dialogs:"Standard dialogs"},Qm=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},Co=()=>{const t=He(w=>w.providers),s=He(w=>w.modelsMetadata),n=He(w=>w.loadProviders),a=He(w=>w.setProvider),r=He(w=>w.setModel),i=He(w=>w.setSettingsDefaultModel),c=He(w=>w.setSettingsDefaultThinking),o=He(w=>w.setSettingsDefaultThinkingByModel),d=V(w=>w.showDeletionDialog),m=V(w=>w.setShowDeletionDialog),[p,h]=l.useState(null),[u,g]=l.useState("loading"),v=l.useCallback(w=>{h(w),i(Vm(w.defaultModel)),c(w.defaultThinking),o(w.defaultThinkingByModel??{})},[i,c,o]);l.useEffect(()=>{n({source:"sessionsDefaults"}),He.getState().ensureModelMetadata()},[n]),l.useEffect(()=>{let w=!0;return(async()=>{try{const I=await _e.getSettings(ra());if(!w)return;let T=I.pichamber;if(!T.defaultModel&&!T.smallModel&&!T.walkthroughModel){const A=ja()?.settings;if(A)try{const F=await A.load(),_=Gm(F?.settings,T);if(qm(_)){const z=await _e.setPiChamberDefaults(_,ra());if(!w)return;T=z.pichamber,await Ie({defaultModel:"",smallModelOverride:"",walkthroughModelOverride:""})}}catch{}}if(!w)return;v(T),g("ready")}catch{w&&g("failed")}})(),()=>{w=!1}},[v]);const x=l.useCallback(async w=>{Te("saving");try{const L=await _e.setPiChamberDefaults(w,ra());v(L.pichamber),Te("saved")}catch{Te("error")}},[v]),b=l.useCallback((w,L)=>{const I=t.find(A=>A.id===w);return(Array.isArray(I?.models)?I.models:[]).find(A=>A.id===L)},[t]),j=l.useCallback(w=>{w&&t.find(I=>I.id===w.providerId)&&(a(w.providerId),r(w.modelId)),x({defaultModel:w})},[x,t,r,a]),k=l.useCallback((w,L)=>{const I=pn(w);I&&x({defaultThinkingByModel:{[I]:L}})},[x]),P=l.useCallback((w,L)=>s.get(`${w}/${L}`)?.structured_output!==!1,[s]);if(u==="loading")return null;if(u==="failed"&&!p)return e.jsx(q,{title:"Session defaults",divider:!1,children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Session defaults are unavailable."})});const E=pn(p?.defaultModel),y=p?.defaultModel?b(p.defaultModel.providerId,p.defaultModel.modelId):void 0,f=ii(y),N=!!(p?.defaultModel&&oi(f)),C=E?p?.defaultThinkingByModel?.[E]:void 0;return e.jsx(q,{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:gt,children:[e.jsx(Ee,{settingsItem:"sessions.default-model",label:"Default model",info:"The model new sessions start with. Unset keeps Pi's default.",children:e.jsx(Gn,{value:p?.defaultModel??null,noneLabel:"Default",ariaLabel:"Default model",onChange:j})}),N&&p?.defaultModel?e.jsx(Ee,{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(Be,{value:C??sn,onValueChange:w=>{k(p.defaultModel,w===sn?null:w)},children:[e.jsx($e,{size:Ge,className:hs,"aria-label":"Default thinking",children:e.jsx(We,{children:w=>w===sn?"Default":w?un[w]??w:""})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:sn,children:"Default"}),Qm(f,C).map(w=>e.jsx(ke,{value:w,children:un[w]},w))]})]})}):null,e.jsx(Ee,{settingsItem:"sessions.small-model",label:"Small model",info:"A cheap model for quick utility tasks like short recaps and summaries.",children:e.jsx(Gn,{value:p?.smallModel??null,noneLabel:"Use default small model",ariaLabel:"Small model",onChange:w=>{x({smallModel:w})}})}),e.jsx(Ee,{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(Gn,{value:p?.walkthroughModel??null,noneLabel:"Small model",ariaLabel:"Changes walkthrough model",isModelAllowed:P,onChange:w=>{x({walkthroughModel:w})}})}),e.jsx(Ee,{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:us,children:e.jsxs("div",{className:Rt,children:[e.jsx(Ct,{value:p?.defaultRetryLimit??3,min:0,max:10,step:1,"aria-label":"Default retry limit",onValueChange:w=>{if(!Number.isFinite(w))return;const L=Math.max(0,Math.min(10,Math.round(w)));x({defaultRetryLimit:L})}}),e.jsx("span",{className:Dt,children:"retries"})]})})}),e.jsx(Ee,{settingsItem:"sessions.extension-interface",label:"Extension interface",info:"Pi extensions can draw their own terminal UI, the way they look in Pi's terminal, where you answer with the keys they show. Standard dialogs tells extensions there is no terminal. Each extension decides what to do then: some ask with Pi's clickable dialogs, some show less or skip their screen. Applies to sessions started after you change it.",children:e.jsxs(Be,{value:p?.extensionUi??"terminal",onValueChange:w=>{x({extensionUi:w})},children:[e.jsx($e,{size:Ge,className:hs,"aria-label":"Extension interface",children:e.jsx(We,{children:w=>ia[w]??""})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"terminal",children:ia.terminal}),e.jsx(ke,{value:"dialogs",children:ia.dialogs})]})]})}),e.jsx(Es,{className:vt,children:e.jsx(ve,{settingsItem:"sessions.deletion-dialog",checked:d,onChange:m,label:"Show deletion dialog",ariaLabel:"Show deletion dialog"})})]})})},Jm=()=>{const t=l.useMemo(()=>Oe(),[]),s=l.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),n=!t&&!s,a=V(k=>k.nativeNotificationsEnabled),r=V(k=>k.setNativeNotificationsEnabled),i=V(k=>k.notificationMode),c=V(k=>k.setNotificationMode),o=V(k=>k.notifyOnCompletion),d=V(k=>k.setNotifyOnCompletion),m=V(k=>k.notifyOnError),p=V(k=>k.setNotifyOnError),h=V(k=>k.notifyOnInputNeeded),u=V(k=>k.setNotifyOnInputNeeded),[g,v]=l.useState("default");l.useEffect(()=>{n&&typeof Notification<"u"&&v(Notification.permission)},[n]);const x=async k=>{if(t){r(k);return}if(!n){r(k);return}if(k&&typeof Notification<"u"&&Notification.permission==="default")try{const P=await Notification.requestPermission();v(P),P==="granted"?r(!0):B.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(P){console.error("Failed to request notification permission:",P),B.error("Failed to request notification permission")}else r(!!(k&&g==="granted"))},b=t||s||n&&typeof Notification<"u"&&Notification.permission==="granted",j=async()=>{const k=ja();if(!k?.notifications){B.error("Notifications API not available");return}try{await k.notifications.notify({title:"Test notification",body:"Notifications are working.",tag:"pichamber-test"})?B.success("Test notification sent successfully"):B.error("Failed to send test notification")}catch(P){console.error("Test notification failed:",P),B.error("Failed to send test notification")}};return e.jsxs(e.Fragment,{children:[e.jsxs(q,{settingsItem:"notifications.delivery",title:"Notification delivery",divider:!1,children:[e.jsxs("div",{className:vt,children:[e.jsx(ve,{checked:a&&b,onChange:k=>{x(k)},label:"Enable notifications",info:n?"Your browser may ask for permission the first time.":void 0,ariaLabel:"Enable notifications"}),a&&b&&!s&&e.jsxs(e.Fragment,{children:[e.jsx(ve,{checked:i==="always",onChange:k=>c(k?"always":"hidden-only"),label:"Notify while app is focused",ariaLabel:"Notify while app is focused"}),e.jsx("div",{className:"py-2",children:e.jsx(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{j()},children:"Send test notification"})})]})]}),n&&e.jsxs("div",{className:"mt-1",children:[g==="denied"&&e.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:"Notification permission denied. Enable it in your browser settings."}),g==="granted"&&!a&&e.jsx("p",{className:"typography-meta text-subtle-foreground mt-1",children:"Permission granted, but notifications are disabled."})]})]}),a&&b&&e.jsx(e.Fragment,{children:e.jsx(q,{settingsItem:"notifications.events",title:"Notification events",children:e.jsxs("div",{className:vt,children:[e.jsx(ve,{checked:o,onChange:d,label:"Work completed",ariaLabel:"Notify when work is completed"}),e.jsx(ve,{checked:m,onChange:p,label:"Errors",ariaLabel:"Notify when work fails"}),e.jsx(ve,{checked:h,onChange:u,label:"Input needed",ariaLabel:"Notify when an extension is waiting for your answer",info:"When an extension is waiting for your answer."})]})})})]})},rn=[{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}],on=[{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}],Ym="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",Xm="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",ba=[{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."}],Zm=[".yml",".yaml",".json"],eh="Config file must use .yml, .yaml, or .json extension.",Is=t=>{const s=t.trim().toLowerCase();return Zm.some(n=>s.endsWith(n))},th=()=>"cloudflared",So=()=>{if(typeof window<"u"&&typeof window.__PICHAMBER_PLATFORM__=="string"){const s=window.__PICHAMBER_PLATFORM__;if(s==="win32"||s==="darwin"||s==="linux")return s}const t=typeof navigator<"u"?`${navigator.platform||""} ${navigator.userAgent||""}`.toLowerCase():"";return t.includes("win")?"win32":t.includes("mac")?"darwin":"linux"},sh=(t=So())=>t==="win32"?"winget install --id Cloudflare.cloudflared":t==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",oa=(t,s)=>{const n=typeof s?.provider=="string"&&s.provider.trim().length>0?s.provider.trim().toLowerCase():t,a=typeof s?.dependency=="string"&&s.dependency.trim().length>0?s.dependency.trim():th(),r=typeof s?.platform=="string"&&s.platform.trim().length>0?s.platform.trim():So(),i=typeof s?.installCommand=="string"&&s.installCommand.trim().length>0?s.installCommand.trim():sh(r);return{provider:n,dependency:a,installCommand:i}},nh=t=>t==="cloudflare"?"Cloudflare":t,$t=t=>t==="managed-local"?"managed-local":"managed-remote",ya=(t,s,n)=>t.find(r=>r.ms===s)?.value||n,Br=(t,s,n)=>{const a=ya(t,s,n);return t.find(r=>r.value===a)?.label||a},Po=t=>{const s=Math.max(0,t),n=Math.floor(s/1e3),a=Math.floor(n/3600),r=Math.floor(n%3600/60),i=n%60;return a>0?`${a}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`},ah=(t,s)=>gc(t,s,{hour:"2-digit",precision:"second"}),bn=t=>{const s=t.trim();if(!s)return"";try{return(s.includes("://")?new URL(s):new URL(`https://${s}`)).hostname.trim().toLowerCase()}catch{return s.toLowerCase()}},rh=t=>{if(!Array.isArray(t))return[];const s=new Set,n=new Set,a=[];for(const r of t){if(!r||typeof r!="object")continue;const i=r,c=typeof i.id=="string"?i.id.trim():"",o=typeof i.name=="string"?i.name.trim():"",d=bn(typeof i.hostname=="string"?i.hostname:"");!c||!o||!d||s.has(c)||n.has(d)||(s.add(c),n.add(d),a.push({id:c,name:o,hostname:d}))}return a},ih=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,oh=({provider:t})=>{const s=nh(t),n=t==="cloudflare";return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(M,{name:"cloud",className:U("size-4 shrink-0",n?"text-[var(--status-warning)]":"text-muted-foreground")}),e.jsx("span",{children:s})]})},lh=({records:t,timeFormatPreference:s})=>t.length===0?null:e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)]/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(M,{name:"information",className:"size-4 text-[var(--status-info)]"}),e.jsx("p",{className:fi,children:"Redeemed access links"})]}),e.jsx("div",{className:"space-y-1",children:t.map(n=>{const a=n.mode==="managed-remote",r=a?"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)]",i=n.isActive?a?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-subtle-foreground",c=a?"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(M,{name:"checkbox-blank-circle-fill",className:U("size-2.5 shrink-0",i)}),e.jsx("span",{className:U("typography-micro rounded border px-1.5 py-0.5 uppercase",r),children:c}),e.jsx("span",{className:"typography-meta text-subtle-foreground",children:`Redeemed ${ah(n.createdAt,s)}`}),e.jsx("span",{className:"typography-meta text-foreground",children:n.isActive?`Expires in ${n.remainingTextForSession}`:n.inactiveLabel==="Inactive"?"Inactive":`Inactive (${n.inactiveLabel})`})]},n.sessionId)})})]})}),ch=({installInfo:t})=>e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning)]/30 bg-[var(--status-warning)]/5 p-3",children:[e.jsx(M,{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:fi,children:`${t.dependency} was not found.`}),e.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Install it to enable remote tunnel access:"}),e.jsx("code",{className:"typography-code block rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.installCommand})]})]})}),dh=({bootstrapTtlMs:t,sessionTtlMs:s,disabled:n,onBootstrapTtlChange:a,onSessionTtlChange:r})=>e.jsxs("div",{"data-settings-item":"tunnel.ttl",className:"mt-2 grid grid-cols-1 gap-2 py-1.5 md:grid-cols-[14rem_auto] md:gap-x-8 md:gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:U(Le,"shrink-0"),children:"Connect link TTL"}),e.jsxs(Be,{value:ya(rn,t,"1800000"),onValueChange:a,disabled:n,children:[e.jsx($e,{size:Ge,className:"max-w-[11rem] min-w-0",children:e.jsx(We,{className:"truncate",children:Br(rn,t,"1800000")})}),e.jsx(Ke,{children:rn.map(i=>e.jsx(ke,{value:i.value,children:i.label},i.value))})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:U(Le,"shrink-0"),children:"Tunnel session TTL"}),e.jsxs(Be,{value:ya(on,s,"28800000"),onValueChange:r,disabled:n,children:[e.jsx($e,{size:Ge,className:"max-w-[11rem] min-w-0",children:e.jsx(We,{className:"truncate",children:Br(on,s,"28800000")})}),e.jsx(Ke,{children:on.map(i=>e.jsx(ke,{value:i.value,children:i.label},i.value))})]})]})]}),uh=({suggestedConnectorPort:t,managedRemoteTunnelPresets:s,expandedManagedRemoteTunnels:n,sessionTokensByPresetId:a,savedTokenPresetIds:r,disabled:i,isAddingPreset:c,newPresetName:o,newPresetHostname:d,newPresetToken:m,managedRemoteValidationError:p,selectedPreset:h,onToggleAddPreset:u,onCancelAddPreset:g,onNewPresetNameChange:v,onNewPresetHostnameChange:x,onNewPresetTokenChange:b,onSaveNewPreset:j,onTogglePresetCollapse:k,onRemovePreset:P,onPresetTokenChange:E,onPersistToken:y})=>e.jsxs("div",{"data-settings-item":"tunnel.managed-remote",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[typeof t=="number"&&e.jsx("div",{className:"rounded-md border border-[var(--status-info-border)] bg-[var(--status-info-background)]/35 px-2 py-1.5",children:e.jsxs("p",{className:"typography-meta text-[var(--status-info)]",children:["Cloudflare connector target:"," ",e.jsxs("code",{children:["http://localhost:",t]})]})}),e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[e.jsx(mi,{children:"Saved managed remote tunnels"}),e.jsxs(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:u,disabled:i,children:[e.jsx(M,{name:"add",className:"h-3.5 w-3.5"}),"Create"]})]}),s.length>0?e.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:s.map((f,N)=>{const C=a[f.id]||"",w=r.has(f.id),L=n[f.id]??!1;return e.jsx("div",{className:U(N<s.length-1&&"border-b border-[var(--surface-subtle)]"),children:e.jsxs(Dc,{open:L,onOpenChange:I=>k(f.id,I),className:"py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3",children:[e.jsxs(_c,{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:i,children:[L?e.jsx(M,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):e.jsx(M,{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:f.name})]}),e.jsx(S,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":`Remove ${f.name}`,onClick:()=>P(f.id),disabled:i,children:e.jsx(M,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsx(Oc,{className:"pt-1.5",children:e.jsxs("div",{className:"space-y-1 px-3 pb-2",children:[e.jsxs("p",{className:"typography-meta text-subtle-foreground",children:["Hostname:"," ",e.jsx("code",{children:f.hostname})]}),e.jsx(ee,{type:"password",value:C,onChange:I=>E(f.id,I.target.value),onBlur:I=>{const T=I.currentTarget.value.trim();T&&y({presetId:f.id,presetName:f.name,hostname:f.hostname,token:T})},placeholder:w?"Saved token available (optional to replace)":"Paste token for this tunnel",className:"h-7",disabled:i}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",disabled:i||C.trim().length===0,onClick:()=>{y({presetId:f.id,presetName:f.name,hostname:f.hostname,token:C})},children:"Save token"})})]})})]})},f.id)})}):e.jsx("p",{className:"typography-meta text-subtle-foreground",children:"No managed remote tunnels saved yet."}),c&&e.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[e.jsx(ee,{value:o,onChange:f=>v(f.target.value),placeholder:"Tunnel name (e.g. Production)",className:"h-7",disabled:i}),e.jsx(ee,{value:d,onChange:f=>x(f.target.value),placeholder:"Hostname (e.g. oc.example.com)",className:"h-7",disabled:i}),e.jsx(ee,{type:"password",value:m,onChange:f=>b(f.target.value),placeholder:"Token",className:"h-7",disabled:i}),typeof t=="number"&&e.jsxs("p",{className:"typography-meta text-subtle-foreground",children:["For Cloudflare connector target, use"," ",e.jsxs("code",{children:["http://localhost:",t]}),"."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:j,disabled:i,children:"Save changes"}),e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:g,disabled:i,children:"Cancel"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Tokens are saved per tunnel and reused from disk."}),e.jsx(gs,{children:"Tokens are saved in ~/.config/pichamber/cloudflare-managed-remote-tunnels.json."})]}),!h&&p&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:p})]}),ph=({managedLocalConfigPath:t,isManagedLocalConfigPathInvalid:s,managedLocalConfigExtensionError:n,disabled:a,fileInputRef:r,onInputChange:i,onInputBlur:c,onBrowse:o,onClear:d,onFileSelected:m})=>e.jsx("div",{"data-settings-item":"tunnel.managed-local-config",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:Le,children:"Configuration file"}),e.jsx("input",{ref:r,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:m}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{value:t||"",onChange:p=>i(p.target.value),onBlur:c,placeholder:"Using default cloudflared config",className:"h-7",disabled:a}),e.jsx(S,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":"Browse config file",onClick:o,disabled:a,children:e.jsx(M,{name:"folder",className:"size-3.5"})}),t&&e.jsx(S,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":"Clear config file",onClick:d,disabled:a,children:e.jsx(M,{name:"close",className:"size-3.5"})})]}),e.jsx("p",{className:"typography-meta text-subtle-foreground",children:t?"Custom config file will be used when starting the tunnel.":"When empty, cloudflared uses its default config (~/.cloudflared/config.yml)."}),s&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:n})]})}),mh=({tunnelMode:t,selectedPresetId:s,managedRemoteTunnelPresets:n,selectedPreset:a,willReplaceActiveTunnel:r,state:i,isSavingMode:c,isManagedLocalConfigPathInvalid:o,primaryCtaClass:d,onSelectPreset:m,onStart:p,onOpenDocUrl:h})=>e.jsxs("div",{"data-settings-item":"tunnel.start",className:"space-y-6",children:[e.jsx("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)] p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(M,{name:"information",className:"mt-0.5 size-4 shrink-0 text-[var(--status-info)]"}),e.jsxs("div",{className:"space-y-1",children:[t==="managed-remote"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed remote tunnels require a purchased domain in your Cloudflare account."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{h(Ym)},children:["Check documentation on how to configure a managed remote tunnel",e.jsx(M,{name:"external-link",className:"size-3.5"})]})]}),t==="managed-local"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed local tunnels use your local cloudflared configuration file."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{h(Xm)},children:["Check documentation on managed local tunnel configuration",e.jsx(M,{name:"external-link",className:"size-3.5"})]})]}),e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:`Start a ${ba.find(u=>u.value===t)?.label??"Managed remote"} tunnel and generate a one-time connect link. Do not close the app while this tunnel is in use.`})]})]})}),t==="managed-remote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:Le,children:"Managed remote tunnel to connect"}),e.jsxs(Be,{value:s||(n[0]?.id??""),onValueChange:m,disabled:c||i==="starting"||i==="stopping"||n.length<=1,children:[e.jsx($e,{size:Ge,children:e.jsx(We,{placeholder:"Select saved tunnel",children:a?.name})}),e.jsx(Ke,{fitContent:!0,children:n.map(u=>e.jsx(ke,{value:u.id,children:u.name},u.id))})]})]}),r&&e.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(M,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:"Starting this tunnel replaces the active tunnel and revokes existing connect links and remote sessions."})]})}),e.jsx(S,{size:"sm",variant:"outline",onClick:p,disabled:i==="starting"||c||t==="managed-remote"&&!a||t==="managed-local"&&o,className:U(d,i==="starting"&&"opacity-70"),children:i==="starting"?e.jsxs(e.Fragment,{children:[e.jsx(M,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Starting tunnel..."]}):"Start tunnel"})]}),hh=({tunnelInfo:t,isConnectLinkLive:s,copied:n,onCopyUrl:a,remainingText:r,qrDataUrl:i,onNewConnectLink:c,onStop:o,stopping:d,isSavingMode:m,isManagedLocalConfigPathInvalid:p,tunnelMode:h,primaryCtaClass:u})=>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-subtle-foreground",children:"Public URL (not accessible without a token)"}),e.jsx("code",{className:"typography-code block truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.url})]}),s&&t.connectUrl&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("p",{className:"typography-meta mb-1 text-subtle-foreground",children:"Connect link"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"typography-code flex-1 truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:t.connectUrl}),e.jsxs(S,{size:"sm",variant:"ghost",onClick:a,className:"shrink-0 gap-1.5",children:[n?e.jsx(M,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):e.jsx(M,{name:"file-copy",className:"size-3.5"}),n?"Copied":"Copy all"]})]}),e.jsxs("p",{className:"typography-meta mt-1 text-subtle-foreground",children:["Expires",": ",t.bootstrapExpiresAt?r:"Never"]})]}),e.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border border-border/50 bg-[var(--surface-elevated)] p-4",children:[i?e.jsx("img",{src:i,alt:"Tunnel connect QR code",className:"size-48"}):e.jsx("div",{className:"size-48 rounded bg-muted/30"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Scan with your phone to connect."})]})]})]}),e.jsx("div",{className:"pt-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(S,{size:"sm",variant:"outline",onClick:c,disabled:d||m||h==="managed-local"&&p,className:u,children:[e.jsx(M,{name:"restart",className:"size-3.5"}),"New connect link"]}),e.jsx(S,{size:"sm",variant:"ghost",onClick:o,disabled:d||m,className:"gap-2 text-[var(--status-error)]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(M,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Stopping..."]}):"Stop tunnel"})]})})]});function fh({saveTunnelSettings:t,setManagedRemoteValidationError:s}){const[n,a]=l.useState([]),[r,i]=l.useState({}),[c,o]=l.useState(""),[d,m]=l.useState({}),[p,h]=l.useState(new Set),[u,g]=l.useState(!1),[v,x]=l.useState(""),[b,j]=l.useState(""),[k,P]=l.useState(""),E=l.useMemo(()=>n.find(L=>L.id===c)||n[0]||null,[n,c]),y=l.useCallback(async L=>{const I=L.token.trim();if(I)try{const T={...d,[L.presetId]:I};await Ie({managedRemoteTunnelPresetTokens:T}),h(A=>{const F=new Set(A);return F.add(L.presetId),F})}catch{B.error("Failed to save managed remote tunnel token")}},[d]),f=l.useCallback(async(L,I)=>{try{await Ie({managedRemoteTunnelPresets:I})}catch{B.error("Failed to save selected managed remote tunnel")}},[]),N=l.useCallback(L=>{const I=n.find(T=>T.id===L);I&&(o(I.id),s(null),f(I,n))},[n,f,s]),C=l.useCallback(async()=>{const L=v.trim(),I=bn(b),T=k.trim();if(!L){B.error("Tunnel name is required");return}if(!I){B.error("Managed remote tunnel hostname is required");return}if(!T){B.error("Managed remote tunnel token is required");return}if(n.some(_=>_.hostname===I)){B.error("This hostname already exists");return}const A={id:ih(),name:L,hostname:I},F=[...n,A];a(F),o(A.id),i(_=>({..._,[A.id]:!0})),m(_=>({..._,[A.id]:T})),s(null),g(!1),x(""),j(""),P(""),await t({tunnelMode:"managed-remote",managedRemoteTunnelPresets:F,managedRemoteTunnelPresetTokens:{...d,[A.id]:T}}),await y({presetId:A.id,presetName:A.name,hostname:A.hostname,token:T}),B.success("Managed remote tunnel saved")},[n,b,v,k,y,t,d,s]),w=l.useCallback(async L=>{const I=n.find(z=>z.id===L);if(!I)return;const T=n.filter(z=>z.id!==I.id),A=T[0]?.id||"",F=c===I.id?A:c,_=Object.fromEntries(Object.entries(d).filter(([z,K])=>z!==I.id&&K.trim().length>0));a(T),o(F),i(z=>{const K={...z};return delete K[I.id],K}),m(z=>{const K={...z};return delete K[I.id],K}),h(z=>{const K=new Set(z);return K.delete(I.id),K}),s(null),await t({managedRemoteTunnelPresets:T,managedRemoteTunnelPresetTokens:_}),B.success("Managed remote tunnel removed")},[n,t,c,d,s]);return{managedRemoteTunnelPresets:n,setManagedRemoteTunnelPresets:a,expandedManagedRemoteTunnels:r,setExpandedManagedRemoteTunnels:i,selectedPresetId:c,setSelectedPresetId:o,sessionTokensByPresetId:d,setSessionTokensByPresetId:m,savedTokenPresetIds:p,setSavedTokenPresetIds:h,isAddingPreset:u,setIsAddingPreset:g,newPresetName:v,setNewPresetName:x,newPresetHostname:b,setNewPresetHostname:j,newPresetToken:k,setNewPresetToken:P,selectedPreset:E,persistManagedRemoteTunnelToken:y,handleSelectPreset:N,handleSaveNewPreset:C,handleRemovePreset:w}}function gh({saveTunnelSettings:t}){const[s,n]=l.useState(null),a=eh,r=l.useRef(null),i=l.useMemo(()=>s?!Is(s):!1,[s]),c=l.useCallback(async()=>{const h=await hl({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(h.success&&typeof h.path=="string"&&h.path.trim().length>0){const u=h.path.trim();if(!Is(u)){B.error(a);return}n(u),await t({managedLocalTunnelConfigPath:u});return}r.current?.click()},[a,t]),o=l.useCallback(h=>{const u=h.trim();n(u.length>0?u:null)},[]),d=l.useCallback(async()=>{if(s&&!Is(s)){B.error(a);return}await t({managedLocalTunnelConfigPath:s})},[a,s,t]),m=l.useCallback(async()=>{n(null),await t({managedLocalTunnelConfigPath:null})},[t]),p=l.useCallback(async h=>{const u=h.target.files?.[0];if(!u)return;const g=u.name.trim();if(g.length!==0){if(!Is(g)){B.error(a);return}n(g),await t({managedLocalTunnelConfigPath:g}),h.target.value=""}},[a,t]);return{managedLocalConfigPath:s,setManagedLocalConfigPath:n,managedLocalConfigExtensionError:a,managedLocalConfigFileInputRef:r,isManagedLocalConfigPathInvalid:i,handleBrowseManagedLocalConfig:c,handleManagedLocalConfigInputChange:o,handleManagedLocalConfigInputBlur:d,handleManagedLocalConfigClear:m,handleManagedLocalConfigFileSelected:p}}function xh(){const[t,s]=l.useState(18e5),[n,a]=l.useState(480*60*1e3),[r,i]=l.useState(!1),c=l.useCallback(async(m,p)=>{i(!0);try{await Ie({tunnelBootstrapTtlMs:m,tunnelSessionTtlMs:p})}catch{B.error("Failed to save tunnel TTL settings")}finally{i(!1)}},[]),o=l.useCallback(async m=>{const p=rn.find(h=>h.value===m);p&&(s(p.ms),await c(p.ms,n))},[c,n]),d=l.useCallback(async m=>{const p=on.find(h=>h.value===m);!p||p.ms===null||(a(p.ms),await c(t,p.ms))},[t,c]);return{bootstrapTtlMs:t,setBootstrapTtlMs:s,sessionTtlMs:n,setSessionTtlMs:a,isSavingTtl:r,saveTtlSettings:c,handleBootstrapTtlChange:o,handleSessionTtlChange:d}}function vh({tunnelInfo:t,state:s,setSessionRecords:n,setSavedTokenPresetIds:a,setLocalPort:r}){const[i,c]=l.useState(null),[o,d]=l.useState(""),[m,p]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t?.connectUrl){c(null);return}let h=!1;return gi.toDataURL(t.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(u=>{h||c(u)}).catch(()=>{h||c(null)}),()=>{h=!0}},[t?.connectUrl]),l.useEffect(()=>{if(!t?.bootstrapExpiresAt){d("No expiry");return}let h=null,u=Date.now();const g=()=>{const b=t.bootstrapExpiresAt?t.bootstrapExpiresAt-Date.now():0;b<=0?d("Expired"):d(Po(b))},v=()=>{const b=Date.now();b-u>=1e3&&(g(),u=b),h=requestAnimationFrame(v)};g(),(typeof document>"u"||document.visibilityState==="visible")&&(h=requestAnimationFrame(v));const x=()=>{document.visibilityState==="visible"&&h===null?h=requestAnimationFrame(v):document.visibilityState!=="visible"&&h!==null&&(cancelAnimationFrame(h),h=null)};return document.addEventListener("visibilitychange",x),()=>{document.removeEventListener("visibilitychange",x),h!==null&&cancelAnimationFrame(h)}},[t?.bootstrapExpiresAt]),l.useEffect(()=>{let h=null,u=Date.now();const g=()=>{const x=Date.now();x-u>=1e3&&(p(x),u=x),h=requestAnimationFrame(g)};(typeof document>"u"||document.visibilityState==="visible")&&(h=requestAnimationFrame(g));const v=()=>{document.visibilityState==="visible"&&h===null?h=requestAnimationFrame(g):document.visibilityState!=="visible"&&h!==null&&(cancelAnimationFrame(h),h=null)};return document.addEventListener("visibilitychange",v),()=>{document.removeEventListener("visibilitychange",v),h!==null&&cancelAnimationFrame(h)}},[]),l.useEffect(()=>{if(s==="starting"||s==="stopping"||s==="checking")return;let h=!1;const u=async()=>{try{const v=await Ae("/api/pichamber/tunnel/status");if(!v.ok||h)return;const x=await v.json();if(h)return;n(Array.isArray(x.activeSessions)?x.activeSessions:[]),a(()=>new Set(Array.isArray(x.managedRemoteTunnelTokenPresetIds)?x.managedRemoteTunnelTokenPresetIds:[])),r(typeof x.localPort=="number"?x.localPort:null)}catch{}},g=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||u()},5e3);return()=>{h=!0,window.clearInterval(g)}},[r,a,n,s]),{qrDataUrl:i,remainingText:o,nowTs:m}}function bh(){const t=V(se=>se.timeFormatPreference),[s,n]=l.useState("checking"),[a,r]=l.useState(null),[i,c]=l.useState(null),[o,d]=l.useState(null),[m,p]=l.useState(null),[h,u]=l.useState(!1),[g,v]=l.useState(!1),[x,b]=l.useState("cloudflare"),[j,k]=l.useState(()=>oa("cloudflare")),[P,E]=l.useState([]),[y,f]=l.useState("managed-remote"),[N,C]=l.useState([]),[w,L]=l.useState(null),{bootstrapTtlMs:I,setBootstrapTtlMs:T,sessionTtlMs:A,setSessionTtlMs:F,isSavingTtl:_,handleBootstrapTtlChange:z,handleSessionTtlChange:K}=xh(),H=l.useCallback(async se=>{v(!0);try{await Ie(se),Object.prototype.hasOwnProperty.call(se,"tunnelMode")&&se.tunnelMode&&f(se.tunnelMode),Object.prototype.hasOwnProperty.call(se,"tunnelProvider")&&typeof se.tunnelProvider=="string"&&b(se.tunnelProvider)}catch{B.error("Failed to save tunnel settings")}finally{v(!1)}},[]),ne=fh({saveTunnelSettings:H,setManagedRemoteValidationError:p}),{managedRemoteTunnelPresets:Z,setManagedRemoteTunnelPresets:ye,expandedManagedRemoteTunnels:oe,setExpandedManagedRemoteTunnels:we,selectedPresetId:le,setSelectedPresetId:ae,sessionTokensByPresetId:pe,setSessionTokensByPresetId:ce,savedTokenPresetIds:Q,setSavedTokenPresetIds:G,isAddingPreset:Pe,setIsAddingPreset:re,newPresetName:Ne,setNewPresetName:ge,newPresetHostname:Ce,setNewPresetHostname:W,newPresetToken:de,setNewPresetToken:O,selectedPreset:J,persistManagedRemoteTunnelToken:te,handleSelectPreset:Ze,handleSaveNewPreset:$,handleRemovePreset:Y}=ne,ie=gh({saveTunnelSettings:H}),{managedLocalConfigPath:X,setManagedLocalConfigPath:be,managedLocalConfigExtensionError:ze,managedLocalConfigFileInputRef:it,isManagedLocalConfigPathInvalid:Ye,handleBrowseManagedLocalConfig:st,handleManagedLocalConfigInputChange:It,handleManagedLocalConfigInputBlur:Gs,handleManagedLocalConfigClear:In,handleManagedLocalConfigFileSelected:Ft}=ie,En=l.useCallback(se=>{G(se)},[G]),{qrDataUrl:An,remainingText:Ln,nowTs:Et}=vh({tunnelInfo:a,state:s,setSessionRecords:C,setSavedTokenPresetIds:En,setLocalPort:L}),Mn=l.useMemo(()=>N.map(se=>{const je=se.expiresAt<=Et,Qe=se.status==="active"&&!je,me=Qe?Po(se.expiresAt-Et):se.inactiveReason==="expired"||je?"expired":"inactive",ct=me==="expired"?"Expired":se.inactiveReason==="tunnel-revoked"?"Revoked":"Inactive",ut=$t(se.mode);return{...se,isActive:Qe,mode:ut,remainingTextForSession:me,inactiveLabel:ct}}),[Et,N]),Rn=l.useMemo(()=>a?.connectUrl?a.bootstrapExpiresAt===null?!0:a.bootstrapExpiresAt>Et:!1,[Et,a?.bootstrapExpiresAt,a?.connectUrl]),ue=l.useMemo(()=>!a||s!=="active"&&s!=="stopping"?!1:i===y,[i,s,a,y]),ns=l.useMemo(()=>!a||s!=="active"||!i?!1:i!==y,[i,s,a,y]),Dn=l.useMemo(()=>{if(typeof w=="number"&&Number.isFinite(w)&&w>0)return w;if(typeof window>"u")return null;const je=xt()||window.location.href;let Qe=0;try{Qe=Number(new URL(je).port)}catch{Qe=Number(window.location.port)}return Number.isFinite(Qe)&&Qe>0?Qe:null},[w]),ws=l.useMemo(()=>P.find(se=>se.provider===x)??null,[P,x]),_n=l.useMemo(()=>{const se=new Set(ws?.modes?.map(je=>je.key).filter(je=>je==="managed-remote"||je==="managed-local"));return se.size===0?ba:ba.filter(je=>se.has(je.value))},[ws]),qs=l.useMemo(()=>j.provider===x?j:oa(x),[j,x]),as=l.useCallback(async se=>{await ds(se)},[]),js=l.useCallback((se,je)=>(k(oa(je,se)),se.available===!0),[]),ks=l.useCallback(async se=>{try{const[je,Qe,me,ct]=await Promise.all([Ae("/api/pichamber/tunnel/check",{signal:se}),Ae("/api/pichamber/tunnel/status",{signal:se}),Ae("/api/pi/ui-settings",{signal:se,headers:{Accept:"application/json"}}),Ae("/api/pichamber/tunnel/providers",{signal:se})]),ut=await je.json(),Se=await Qe.json(),pt=me.ok?await me.json():{},Qs=ct.ok?await ct.json():{},Fn=Se.ttlConfig?.bootstrapTtlMs??(pt?.tunnelBootstrapTtlMs===null?null:typeof pt?.tunnelBootstrapTtlMs=="number"?pt.tunnelBootstrapTtlMs:1800*1e3),Bn=typeof Se.ttlConfig?.sessionTtlMs=="number"?Se.ttlConfig.sessionTtlMs:typeof pt?.tunnelSessionTtlMs=="number"?pt.tunnelSessionTtlMs:480*60*1e3,Ns=$t(Se.mode??pt?.tunnelMode),Js="cloudflare",$n=typeof pt?.managedLocalTunnelConfigPath=="string"&&pt.managedLocalTunnelConfigPath.trim()||null,Lt=js(ut,Js),rs=rh(Se?.managedRemoteTunnelPresets),Nt=typeof Se.managedRemoteTunnelHostname=="string"?Se.managedRemoteTunnelHostname:"",Ys=rs.length>0?rs:Nt?[{id:`legacy-${bn(Nt)}`,name:Nt,hostname:bn(Nt)}]:[],Wn=Ys[0]?.id||"";if(T(Fn),F(Bn),b(Js),E(Array.isArray(Qs?.providers)?Qs.providers:[]),f(Ns),be($n),ye(Ys),ae(Wn),C(Array.isArray(Se.activeSessions)?Se.activeSessions:[]),c(Se.activeTunnelMode?$t(Se.activeTunnelMode):Se.active&&Se.mode?$t(Se.mode):null),G(new Set(Array.isArray(Se.managedRemoteTunnelTokenPresetIds)?Se.managedRemoteTunnelTokenPresetIds:[])),L(typeof Se.localPort=="number"?Se.localPort:null),Se.active&&Se.url){r({url:Se.url,connectUrl:null,bootstrapExpiresAt:typeof Se.bootstrapExpiresAt=="number"?Se.bootstrapExpiresAt:null}),n("active");return}n(Lt?"idle":"not-available")}catch{se.aborted||(n("error"),d("Failed to check tunnel availability"))}},[js,T,be,ye,G,ae,F]);l.useEffect(()=>{const se=new AbortController;return ks(se.signal),()=>se.abort()},[ks]);const On=l.useCallback(async()=>{if(d(null),p(null),y==="managed-local"&&X&&!Is(X)){d(ze),B.error(ze);return}n("starting");try{let se="",je="";if(y==="managed-remote"){if(!J){n("idle"),p("Select or add a managed remote tunnel first"),B.error("Select or add a managed remote tunnel first");return}se=J.hostname,je=(pe[J.id]||"").trim(),await H({tunnelMode:"managed-remote",managedRemoteTunnelPresets:Z})}const Qe=await Ae("/api/pichamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:x,mode:y,...y==="managed-remote"&&J?{managedRemoteTunnelPresetId:J.id,managedRemoteTunnelPresetName:J.name}:{},...y==="managed-remote"&&se?{managedRemoteTunnelHostname:se}:{},...y==="managed-remote"&&je?{managedRemoteTunnelToken:je}:{},...y==="managed-local"&&X?{configPath:X}:{}})}),me=await Qe.json();if(!Qe.ok||!me.ok){if(y==="managed-remote"&&typeof me.error=="string"&&me.error.includes("Managed remote tunnel token is required")){n("idle"),p("Managed remote tunnel token is required before starting"),B.error("Add a managed remote tunnel token before starting");return}n("error"),d(me.error||"Failed to start tunnel"),B.error(me.error||"Failed to start tunnel");return}const ct=typeof me.url=="string"?me.url:"";if(!ct){n("error"),d("Tunnel started but no public URL was returned"),B.error("Tunnel started but no public URL was returned");return}if(r({url:ct,connectUrl:typeof me.connectUrl=="string"?me.connectUrl:null,bootstrapExpiresAt:typeof me.bootstrapExpiresAt=="number"?me.bootstrapExpiresAt:null}),c(me.activeTunnelMode?$t(me.activeTunnelMode):me.mode?$t(me.mode):y),C(Array.isArray(me.activeSessions)?me.activeSessions:[]),Array.isArray(me.managedRemoteTunnelTokenPresetIds)&&G(new Set(me.managedRemoteTunnelTokenPresetIds)),typeof me.localPort=="number"&&L(me.localPort),typeof me.mode=="string"&&f($t(me.mode)),n("active"),me.replacedTunnel){const ut=typeof me.revokedBootstrapCount=="number"?me.revokedBootstrapCount:0,Se=typeof me.invalidatedSessionCount=="number"?me.invalidatedSessionCount:0;ut===1&&Se===1?B.warning("Replaced previous tunnel: revoked 1 link, invalidated 1 session."):ut===1?B.warning(`Replaced previous tunnel: revoked 1 link, invalidated ${Se} sessions.`):Se===1?B.warning(`Replaced previous tunnel: revoked ${ut} links, invalidated 1 session.`):B.warning(`Replaced previous tunnel: revoked ${ut} links, invalidated ${Se} sessions.`)}else B.success("Tunnel link ready")}catch{n("error"),d("Failed to start tunnel"),B.error("Failed to start tunnel")}},[ze,X,Z,H,J,pe,p,G,y,x]),zn=l.useCallback(async()=>{n("stopping");try{await Ae("/api/pichamber/tunnel/stop",{method:"POST"});const se=await Ae("/api/pichamber/tunnel/status");if(se.ok){const je=await se.json();C(Array.isArray(je.activeSessions)?je.activeSessions:[]),G(new Set(Array.isArray(je.managedRemoteTunnelTokenPresetIds)?je.managedRemoteTunnelTokenPresetIds:[])),L(typeof je.localPort=="number"?je.localPort:null)}r(null),c(null),n("idle"),B.success("Tunnel stopped")}catch{n("error"),d("Failed to stop tunnel"),B.error("Failed to stop tunnel")}},[G]),Un=l.useCallback(async()=>{if(a?.connectUrl)try{await navigator.clipboard.writeText(a.connectUrl),u(!0),B.success("Connect link copied"),setTimeout(()=>u(!1),2e3)}catch{B.error("Failed to copy URL")}},[a?.connectUrl]),At=l.useCallback(async se=>{p(null),d(null),s!=="active"&&s!=="stopping"&&s!=="starting"&&n("idle"),await H({tunnelMode:se,managedRemoteTunnelPresets:Z})},[Z,H,p,s]);return{timeFormatPreference:t,state:s,tunnelInfo:a,activeTunnelMode:i,qrDataUrl:An,errorMessage:o,managedRemoteValidationError:m,setManagedRemoteValidationError:p,copied:h,isSavingTtl:_,isSavingMode:g,tunnelProvider:x,dependencyInstallInfo:j,providerCapabilities:P,tunnelMode:y,managedLocalConfigPath:X,managedRemoteTunnelPresets:Z,expandedManagedRemoteTunnels:oe,setExpandedManagedRemoteTunnels:we,selectedPresetId:le,sessionTokensByPresetId:pe,setSessionTokensByPresetId:ce,savedTokenPresetIds:Q,isAddingPreset:Pe,setIsAddingPreset:re,newPresetName:Ne,setNewPresetName:ge,newPresetHostname:Ce,setNewPresetHostname:W,newPresetToken:de,setNewPresetToken:O,bootstrapTtlMs:I,sessionTtlMs:A,remainingText:Ln,sessionRecords:N,nowTs:Et,localPort:w,managedLocalConfigExtensionError:ze,managedLocalConfigFileInputRef:it,isManagedLocalConfigPathInvalid:Ye,selectedPreset:J,renderedSessionRecords:Mn,isConnectLinkLive:Rn,isSelectedModeTunnelReady:ue,willReplaceActiveTunnel:ns,suggestedConnectorPort:Dn,selectedProviderCapability:ws,tunnelModeOptions:_n,displayedDependencyInstallInfo:qs,openExternal:as,handleBrowseManagedLocalConfig:st,handleManagedLocalConfigInputChange:It,handleManagedLocalConfigInputBlur:Gs,handleManagedLocalConfigClear:In,handleManagedLocalConfigFileSelected:Ft,handleStart:On,handleStop:zn,handleCopyUrl:Un,handleBootstrapTtlChange:z,handleSessionTtlChange:K,handleModeChange:At,handleSelectPreset:Ze,handleSaveNewPreset:$,handleRemovePreset:Y,persistManagedRemoteTunnelToken:te}}const yh=()=>{const{timeFormatPreference:t,state:s,tunnelInfo:n,qrDataUrl:a,errorMessage:r,managedRemoteValidationError:i,setManagedRemoteValidationError:c,copied:o,isSavingTtl:d,isSavingMode:m,tunnelMode:p,managedLocalConfigPath:h,managedRemoteTunnelPresets:u,expandedManagedRemoteTunnels:g,setExpandedManagedRemoteTunnels:v,selectedPresetId:x,sessionTokensByPresetId:b,setSessionTokensByPresetId:j,savedTokenPresetIds:k,isAddingPreset:P,setIsAddingPreset:E,newPresetName:y,setNewPresetName:f,newPresetHostname:N,setNewPresetHostname:C,newPresetToken:w,setNewPresetToken:L,bootstrapTtlMs:I,sessionTtlMs:T,remainingText:A,managedLocalConfigExtensionError:F,managedLocalConfigFileInputRef:_,isManagedLocalConfigPathInvalid:z,selectedPreset:K,renderedSessionRecords:H,isConnectLinkLive:ne,isSelectedModeTunnelReady:Z,willReplaceActiveTunnel:ye,suggestedConnectorPort:oe,tunnelModeOptions:we,displayedDependencyInstallInfo:le,openExternal:ae,handleBrowseManagedLocalConfig:pe,handleManagedLocalConfigInputChange:ce,handleManagedLocalConfigInputBlur:Q,handleManagedLocalConfigClear:G,handleManagedLocalConfigFileSelected:Pe,handleStart:re,handleStop:Ne,handleCopyUrl:ge,handleBootstrapTtlChange:Ce,handleSessionTtlChange:W,handleModeChange:de,handleSelectPreset:O,handleSaveNewPreset:J,handleRemovePreset:te,persistManagedRemoteTunnelToken:Ze}=bh(),$="gap-2 border-[var(--primary-base)] bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)] hover:text-[var(--primary-foreground)]";return s==="checking"?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-busy-pulse","aria-label":"Loading"})}):e.jsx(q,{title:"External tunnel",info:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{children:"Configure secure remote access with your own managed Cloudflare tunnel."}),e.jsx("p",{children:"Secure tunnel access is enforced server-side."}),e.jsx("p",{children:"Connect links are one-time and are revoked when tunnel stops or connect-link TTL expires."})]}),divider:!1,children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(lh,{records:H,timeFormatPreference:t}),s==="not-available"&&e.jsx(ch,{installInfo:le}),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:Le,children:"Provider"}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-foreground",children:e.jsx(oh,{provider:"cloudflare"})})]}),e.jsxs("div",{"data-settings-item":"tunnel.type",className:"space-y-1.5",children:[e.jsx("p",{className:Le,children:"Tunnel type"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1",children:we.map(Y=>e.jsxs(di,{children:[e.jsx(ui,{asChild:!0,children:e.jsx(S,{variant:"chip",size:"xs","aria-pressed":p===Y.value,className:"!font-normal",onClick:()=>{de(Y.value)},disabled:m||s==="starting"||s==="stopping",children:Y.label})}),e.jsx(xc,{sideOffset:8,className:"max-w-xs",children:Y.tooltip})]},Y.value))})]})]}),e.jsx(dh,{bootstrapTtlMs:I,sessionTtlMs:T,disabled:d||m||s==="starting"||s==="stopping",onBootstrapTtlChange:Y=>{Ce(Y)},onSessionTtlChange:Y=>{W(Y)}}),p==="managed-remote"&&e.jsx(uh,{suggestedConnectorPort:oe,managedRemoteTunnelPresets:u,expandedManagedRemoteTunnels:g,sessionTokensByPresetId:b,savedTokenPresetIds:k,disabled:s==="starting"||s==="stopping"||m,isAddingPreset:P,newPresetName:y,newPresetHostname:N,newPresetToken:w,managedRemoteValidationError:i,selectedPreset:K,onToggleAddPreset:()=>E(Y=>!Y),onCancelAddPreset:()=>{E(!1),f(""),C(""),L("")},onNewPresetNameChange:f,onNewPresetHostnameChange:C,onNewPresetTokenChange:L,onSaveNewPreset:()=>{J()},onTogglePresetCollapse:(Y,ie)=>{v(X=>({...X,[Y]:ie})),ie&&O(Y)},onRemovePreset:Y=>{te(Y)},onPresetTokenChange:(Y,ie)=>{c(null),j(X=>({...X,[Y]:ie}))},onPersistToken:Y=>{Ze(Y)}}),p==="managed-local"&&e.jsx(ph,{managedLocalConfigPath:h,isManagedLocalConfigPathInvalid:z,managedLocalConfigExtensionError:F,disabled:s==="starting"||s==="stopping"||m,fileInputRef:_,onInputChange:ce,onInputBlur:()=>{Q()},onBrowse:()=>{pe()},onClear:()=>{G()},onFileSelected:Y=>{Pe(Y)}}),!Z&&e.jsx(mh,{tunnelMode:p,selectedPresetId:x,managedRemoteTunnelPresets:u,selectedPreset:K,willReplaceActiveTunnel:ye,state:s,isSavingMode:m,isManagedLocalConfigPathInvalid:z,primaryCtaClass:$,onSelectPreset:Y=>{O(Y)},onStart:re,onOpenDocUrl:Y=>{ae(Y)}})]}),Z&&n&&e.jsx(hh,{tunnelInfo:n,isConnectLinkLive:ne,copied:o,onCopyUrl:ge,remainingText:A,qrDataUrl:a,onNewConnectLink:re,onStop:Ne,stopping:s==="stopping",isSavingMode:m,isManagedLocalConfigPathInvalid:z,tunnelMode:p,primaryCtaClass:$}),s==="error"&&r&&e.jsxs("section",{className:"space-y-3 px-2 pb-2 pt-0",children:[e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:r}),e.jsx(S,{size:"sm",variant:"ghost",onClick:re,children:"Retry"})]})]})})},To=()=>{const t=Oe(),s=t&&ts(),n=s&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[a,r]=D.useState(!0),[i,c]=D.useState(!1),[o,d]=D.useState(!1),[m,p]=D.useState(!1),[h,u]=D.useState(!1),[g,v]=D.useState(!1),[x,b]=D.useState(!1),[j,k]=D.useState(!1),[P,E]=D.useState(!1),[y,f]=D.useState(!0),[N,C]=D.useState(!1),[w,L]=D.useState(!0),[I,T]=D.useState(!0),[A,F]=D.useState(!1),[_,z]=D.useState(!1),[K,H]=D.useState(!1),[ne,Z]=D.useState(null);D.useEffect(()=>{if(!s){r(!1);return}let Q=!1;return(async()=>{try{const G=await Ae("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!G.ok)throw new Error("Failed to load desktop settings");const Pe=await G.json().catch(()=>null);if(Q)return;const re=Pe?.desktopMacMenuBarEnabled!==!1;L(re),T(re),Z(null)}catch(G){Q||Z(G instanceof Error?G.message:"Failed to load desktop settings")}finally{Q||r(!1)}})(),()=>{Q=!0}},[s]),D.useEffect(()=>{if(!t){d(!1);return}let Q=!1;return(async()=>{const G=await fl();Q||(d(G?.supported===!0),p(G?.enabled===!0))})(),()=>{Q=!0}},[t]),D.useEffect(()=>{if(!t){v(!1);return}let Q=!1;return(async()=>{const G=await gl();Q||(v(G?.supported===!0),b(G?.enabled===!0))})(),()=>{Q=!0}},[t]),D.useEffect(()=>{if(!t){E(!1);return}let Q=!1;return(async()=>{const G=await xl();Q||(E(G?.supported===!0),f(G?.enabled===!0))})(),()=>{Q=!0}},[t]),D.useEffect(()=>{if(!t){F(!1);return}let Q=!1;return(async()=>{const G=await vl();Q||(F(G?.supported===!0),z(G?.enabled===!0))})(),()=>{Q=!0}},[t]);const ye=I!==w,oe=a||i||!ye,we=D.useCallback(async()=>{if(!o||h)return;const Q=!m;p(Q),u(!0),Z(null);try{const G=await bl(Q);if(!G?.supported)throw new Error("Launch at login is not supported on this system");p(G.enabled)}catch(G){p(!Q),Z(G instanceof Error?G.message:"Failed to update launch at login setting")}finally{u(!1)}},[h,m,o]),le=D.useCallback(async()=>{if(!g||j)return;const Q=!x;b(Q),k(!0),Z(null);try{const G=await yl(Q);if(!G)throw new Error("Failed to update system tray setting");if(!G.supported)throw new Error("System tray background mode is not supported on this system");b(G.enabled)}catch(G){b(!Q),Z(G instanceof Error?G.message:"Failed to update system tray setting")}finally{k(!1)}},[j,x,g]),ae=D.useCallback(async()=>{if(!P||N)return;const Q=!y;f(Q),C(!0),Z(null);try{const G=await wl(Q);if(!G)throw new Error("Failed to update close behavior");if(!G.supported)throw new Error("Closing to the system tray is not supported on this system");f(G.enabled)}catch(G){f(!Q),Z(G instanceof Error?G.message:"Failed to update close behavior")}finally{C(!1)}},[y,P,N]),pe=D.useCallback(async()=>{if(!A||K)return;const Q=!_;z(Q),H(!0),Z(null);try{const G=await jl(Q);if(!G?.supported)throw new Error("Preventing sleep is not supported on this system");z(G.enabled)}catch(G){z(!Q),Z(G instanceof Error?G.message:"Failed to update keep awake setting")}finally{H(!1)}},[K,_,A]),ce=D.useCallback(async()=>{if(ye){c(!0),Z(null);try{if(!(await Ae("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopMacMenuBarEnabled:I})})).ok)throw new Error("Failed to save desktop settings");if(L(I),!await Yr())throw new Error("Saved, but failed to restart app")}catch(Q){Z(Q instanceof Error?Q.message:"Failed to save desktop settings"),c(!1)}}},[I,ye]);return t?e.jsx(q,{title:"Desktop",children:e.jsxs("div",{className:"space-y-3",children:[o||n||g||P||A?e.jsxs("div",{className:vt,children:[o?e.jsx(ve,{settingsItem:"sessions.desktop-launch-at-login",checked:m,onChange:Q=>{Q!==m&&we()},disabled:h,label:"Start PiChamber when you log in",info:"Starts the app in the background without opening a window. Use the desktop status icon to open it.",ariaLabel:"Start PiChamber at login"}):null,n?e.jsx(ve,{settingsItem:"sessions.desktop-mac-menu-bar",checked:I,onChange:T,disabled:a||i,label:"Show PiChamber in the menu bar",info:"Requires an app restart. When off, PiChamber does not create the menu bar item or run its session, approval, and usage updates.",ariaLabel:"Show PiChamber in the macOS menu bar"}):null,g?e.jsx(ve,{settingsItem:"sessions.desktop-minimize-to-tray",checked:x,onChange:Q=>{Q!==x&&le()},disabled:j,label:"Minimize to the system tray",info:"Hides PiChamber in the system tray instead of leaving it in the taskbar when you minimize the window.",ariaLabel:"Minimize PiChamber to the system tray"}):null,P?e.jsx(ve,{settingsItem:"sessions.desktop-close-to-tray",checked:y,onChange:Q=>{Q!==y&&ae()},disabled:N,label:"Close to the system tray",info:"Keeps PiChamber running in the system tray when you close the main window. Turn this off to quit the app when the window closes.",ariaLabel:"Close PiChamber to the system tray"}):null,A?e.jsx(ve,{settingsItem:"sessions.desktop-keep-awake",checked:_,onChange:Q=>{Q!==_&&pe()},disabled:K,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,ne?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:ne}):null,s?e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(S,{type:"button",size:"xs",onClick:ce,disabled:oe,className:"shrink-0 !font-normal",children:i?"Saving...":"Save + Restart"})}):null]})}):null},Io=new Set(["shift","control","alt","meta"]),wh=t=>{if(Io.has(t.key.toLowerCase()))return null;const s=[];(t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt");const n=ka(t.key);return n?(s.push(n),ht(s.join("+"))):null},jh=t=>{const s=[];if((t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt"),Io.has(t.key.toLowerCase()))return s.length>0?ht(s.join("+")):null;const n=ka(t.key);return n?(s.push(n),s.length>0?ht(s.join("+")):null):null},kh={add_selection_to_chat:"Add selection to chat",cycle_agent:"Cycle agent",cycle_draft_folder:"Cycle draft folder",cycle_favorite_model_backward:"Cycle favorite model backward",cycle_favorite_model_forward:"Cycle favorite model forward",cycle_session_folder:"Cycle session folder",cycle_theme:"Cycle theme",focus_input:"Focus input",new_chat:"New session",new_mini_chat:"New Mini Chat window",open_command_palette:"Open command palette",open_help:"Open keyboard shortcuts",open_model_selector:"Open model selector",open_right_sidebar:"Open right sidebar",open_settings:"Open settings",open_timeline_dialog:"Open conversation timeline",switch_context_surface:"Switch context panel surface",toggle_services_menu:"Toggle services menu",toggle_sidebar:"Toggle sidebar",toggle_terminal:"Toggle terminal dock"},Nh=()=>{const t=V(y=>y.shortcutOverrides),s=V(y=>y.setShortcutOverride),n=V(y=>y.clearShortcutOverride),a=V(y=>y.resetAllShortcutOverrides),r=l.useMemo(()=>kl(),[]),i=l.useCallback((y,f)=>kh[y]??f,[]),[c,o]=l.useState(null),[d,m]=l.useState({}),[p,h]=l.useState(""),[u,g]=l.useState(""),[v,x]=l.useState(null),b=l.useCallback(y=>{Ie({shortcutOverrides:y})},[]),j=l.useCallback((y,f)=>{const N=ht(f);for(const C of r){if(C.id===y)continue;const w=Ya(C.id,t);if(ht(w)===N)return C.id}return null},[r,t]),k=l.useCallback((y,f)=>{const N=ht(f),C=j(y,N);if(C){x({actionId:y,combo:N,conflictActionId:C}),h("");return}const w={...t,[y]:N};s(y,N),b(w),x(null),h(""),g(Xa(N)?"This shortcut can conflict with browser defaults. It is still saved.":""),m(L=>{const I={...L};return delete I[y],I})},[j,b,s,t]),P=l.useCallback(()=>{if(!v)return;const y={...t,[v.conflictActionId]:Kn,[v.actionId]:v.combo};s(v.conflictActionId,Kn),s(v.actionId,v.combo),b(y),x(null),h(""),g(Xa(v.combo)?"This shortcut can conflict with browser defaults. It is still saved.":""),m(f=>{const N={...f};return delete N[v.actionId],N})},[v,b,s,t]),E=l.useCallback(y=>{const f={...t};delete f[y],n(y),b(f),m(N=>{const C={...N};return delete C[y],C}),x(null),h(""),g("")},[n,b,t]);return e.jsxs(q,{settingsItem:"shortcuts.keyboard-shortcuts",title:"Keyboard shortcuts",divider:!1,info:"Capture a new key combo, save it, and bindings will update immediately.",headerAction:e.jsx(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{a(),b({}),m({}),x(null),h(""),g("")},children:"Reset all"}),children:[(p||u||v)&&e.jsxs("div",{className:"mb-2 space-y-2",children:[v&&e.jsxs("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 flex flex-col @xl:flex-row @xl:items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-foreground",children:"This combo is already used by another shortcut. Overwrite and clear that other mapping?"}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx(S,{type:"button",size:"xs",className:"!font-normal",onClick:P,children:"Overwrite"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>x(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:r.map((y,f)=>{const N=y.id==="switch_context_surface",C=N?Nl(y.id,t):Ya(y.id,t),w=d[y.id],L=w??C,I=typeof w=="string"&&ht(w)!==ht(C),T=L===""||ht(L)===Kn,A=c===y.id?"Press keys...":N&&!T?`${Za(L)} + 1…0`:Za(L);return e.jsx("div",{className:U("py-1.5",f>0&&"border-t border-border/40"),children:e.jsxs(Ee,{label:i(y.id,y.label),alignEnd:!1,children:[e.jsx(ee,{readOnly:!0,value:A,onFocus:()=>{o(y.id),h("")},onBlur:()=>{c===y.id&&o(null)},onKeyDown:F=>{if(F.preventDefault(),F.stopPropagation(),F.key==="Escape"){o(null);return}const _=N?jh(F):wh(F);_&&(m(z=>({...z,[y.id]:_})),o(null),x(null),h(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),e.jsx(S,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const F=d[y.id];if(!F){h("Capture a shortcut first.");return}k(y.id,F)},disabled:!I,children:"Save changes"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>E(y.id),children:"Reset"})]})},y.id)})})]})},Ch=new Set(["shift","control","alt","meta"]),Sh=t=>{if(Ch.has(t.key.toLowerCase()))return null;const s=[];(t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt");const n=ka(t.key);if(!n)return null;s.push(n);const a=ht(s.join("+"));return s.length>1?a:null},Ph=({trigger:t,index:s,onChange:n,onRemove:a})=>{const r="h-9 w-full bg-transparent text-sm";return e.jsxs("div",{className:"flex flex-col gap-2 @xl:flex-row @xl:items-center",children:[e.jsx(ee,{value:t.label,placeholder:"Label","aria-label":`Trigger ${s+1} label`,onChange:i=>n({...t,label:i.target.value}),className:U(r,"@xl:w-36")}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/"}),e.jsx(ee,{value:t.command,placeholder:"command","aria-label":`Trigger ${s+1} command`,onChange:i=>n({...t,command:i.target.value}),className:U(r,"w-40")})]}),e.jsx(ee,{value:t.args??"",placeholder:"Arguments (optional)","aria-label":`Trigger ${s+1} arguments`,onChange:i=>n({...t,args:i.target.value}),className:U(r,"flex-1")}),e.jsx("input",{value:t.combo?t.combo.replace(/\+/g,"+"):"",placeholder:"Keybinding","aria-label":`Trigger ${s+1} keybinding`,readOnly:!0,onKeyDown:i=>{const c=Sh(i);c&&(i.preventDefault(),n({...t,combo:c}))},className:U(r,"w-32 rounded-md border")}),e.jsx(S,{variant:"ghost",size:"icon",onClick:a,"aria-label":`Remove trigger ${t.label}`,children:e.jsx(M,{name:"close",className:"size-4"})})]})},Th=()=>{const t=V(i=>i.commandTriggers),s=l.useCallback(async i=>{V.setState({commandTriggers:i});try{await Ie({commandTriggers:i})}catch{Te("error")}},[]),n=(i,c)=>{const o=t.map((d,m)=>m===i?c:d);s(Cl(o)??[])},a=i=>{const c=t.filter((o,d)=>d!==i);s(c)},r=()=>{t.length>=er||s([...t,{id:`trigger-${Date.now().toString(36)}`,label:"",command:""}])};return e.jsxs(q,{title:"Command triggers",divider:!1,settingsItem:"shortcuts.command-triggers",children:[e.jsx(Ee,{label:"Quick actions",info:"Buttons above the composer and optional keybindings that run a slash command in the current session. Keybindings must include a modifier and never shadow built-in shortcuts.",children:e.jsx(S,{size:"sm",variant:"outline",onClick:r,disabled:t.length>=er,children:"Add trigger"})}),t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 pb-1",children:t.map((i,c)=>e.jsx(Ph,{trigger:i,index:c,onChange:o=>n(c,o),onRemove:()=>a(c)},i.id))}),t.length===0&&e.jsx("p",{className:"pb-2 text-sm text-muted-foreground",children:"No command triggers yet. Add one to pin a slash command as a button."})]})},Ih=({section:t})=>{const{isMobile:s}=lt(),n=s&&Ht(),a=Oe();if(!t)return e.jsxs(xe,{className:"pichamber-page-body space-y-3 sm:space-y-6",children:[e.jsx(Tn,{}),e.jsx(Co,{}),a&&e.jsx(To,{}),e.jsx(No,{}),n&&e.jsx(Ki,{})]});const r=()=>{switch(t){case"general":return e.jsx(Ah,{});case"visual":return e.jsx(Lh,{});case"chat":return e.jsx(Mh,{});case"sessions":return e.jsx(Rh,{});case"shortcuts":return e.jsx(Eh,{});case"git":return e.jsx(Dh,{});case"github":return e.jsx(_h,{});case"notifications":return e.jsx(Oh,{});case"tunnel":return e.jsx(zh,{});default:return null}},i={general:"General",visual:"Appearance",chat:"Chat",sessions:"Sessions",shortcuts:"Shortcuts",git:"Git",github:"Git",notifications:"Notifications",tunnel:"External tunnel"}[t],c={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(xe,{title:s?void 0:i,description:s?void 0:c,className:"pichamber-page-body",children:r()})},Eh=()=>e.jsxs(e.Fragment,{children:[e.jsx(Nh,{}),e.jsx(Th,{})]}),Ah=()=>{const t=Oe();return e.jsxs(e.Fragment,{children:[t&&e.jsx(To,{}),e.jsx(Tn,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar","terminalQuickKeys","terminalShell","terminalLoginShell","perfHud"]}),e.jsx(Km,{})]})},Lh=()=>e.jsx(Tn,{visibleSettings:["theme","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat","weekStart","sidebarViewMode","fontSize","terminalFontSize","editorFontSize","wrapLinesByDefault","spacing","inputBarOffset"]}),Mh=()=>e.jsx(Tn,{visibleSettings:["diffLayout","followUpBehavior"]}),Rh=()=>e.jsxs(e.Fragment,{children:[e.jsx(Co,{}),e.jsx(No,{})]}),Dh=()=>e.jsx(Wa,{}),_h=()=>e.jsx(Wa,{}),Oh=()=>e.jsx(Jm,{}),zh=()=>e.jsx(yh,{}),Ps="openai-compatible",Uh=t=>`${Math.round(t/1024/1024)} MB`;function Fh(){const[t,s]=l.useState(null),[n,a]=l.useState(null),[r,i]=l.useState(""),[c,o]=l.useState(""),[d,m]=l.useState(""),[p,h]=l.useState(null),[u,g]=l.useState(!1),v=l.useCallback(async P=>{const E=await vc(P);s(E),s(E),a(null);const y=E.config.providers.find(f=>f.id===Ps);y&&(i(y.baseUrl),o(y.model))},[]);l.useEffect(()=>{v().catch(P=>a(P.message))},[v]),l.useEffect(()=>{if(!t?.models.some(E=>E.downloading))return;const P=window.setInterval(()=>{v({fresh:!0}).catch(()=>{})},1500);return()=>window.clearInterval(P)},[v,t?.models]);const x=l.useCallback(async P=>{Te("saving");try{const E=await Ae("/api/stt/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!E.ok)throw new Error((await E.json().catch(()=>null))?.error||"Could not save dictation settings");const y=await E.json();s(f=>f&&{...f,config:y.config}),Te("saved")}catch(E){throw Te("error"),E}},[]),b=async(P,E)=>{h(P);try{const y=E==="POST"?"/download":"",f=await Ae(`/api/stt/models/${encodeURIComponent(P)}${y}`,{method:E});if(!f.ok)throw new Error((await f.json().catch(()=>null))?.error||"Model action failed");await v({fresh:!0})}catch(y){a(y instanceof Error?y.message:String(y))}finally{h(null)}},j=async()=>{g(!0);try{await x({remoteProvider:{id:Ps,label:"OpenAI-compatible",baseUrl:r,model:c,apiKey:d||void 0},providerConfigId:Ps}),m("")}catch(P){a(P instanceof Error?P.message:String(P))}finally{g(!1)}};if(!t)return e.jsx(xe,{title:"Dictation",children:e.jsx("div",{className:"py-8 typography-ui text-muted-foreground",children:n||"Loading dictation settings..."})});const k=t.config.providers.find(P=>P.id===Ps);return e.jsxs(xe,{title:"Dictation",description:"Record speech and insert the final transcript into the composer.",children:[e.jsxs(q,{title:"Recording",divider:!1,settingsItem:"dictation.enabled",contentClassName:"space-y-4",children:[e.jsx(ve,{checked:t.config.enabled,onChange:P=>{x({enabled:P}).catch(E=>a(E.message))},label:"Enable dictation",ariaLabel:"Enable dictation",info:"Audio streams to the active PiChamber server. PiChamber inserts text only after you choose Done and never sends it automatically."}),e.jsx(Ee,{label:"Transcription provider",settingsItem:"dictation.provider",children:e.jsxs(Be,{value:t.config.providerConfigId,onValueChange:P=>{x({providerConfigId:P}).catch(E=>a(E.message))},children:[e.jsx($e,{size:Ge,className:hs,"aria-label":"Transcription provider",children:e.jsx(We,{})}),e.jsxs(Ke,{children:[e.jsx(ke,{value:"local",children:"Local model"}),e.jsx(ke,{value:Ps,disabled:!k,children:"OpenAI-compatible"})]})]})}),e.jsx(Ee,{label:"Language",info:"Optional language code such as en or fr. Leave blank for automatic detection.",settingsItem:"dictation.language",children:e.jsx(ee,{value:t.config.language,onChange:P=>s(E=>E&&{...E,config:{...E.config,language:P.target.value}}),onBlur:()=>{x({language:t.config.language}).catch(P=>a(P.message))},placeholder:"Auto-detect",className:"h-8 w-full max-w-48","aria-label":"Dictation language"})})]}),e.jsx(q,{title:"Local models",info:"Models run only on the active PiChamber server. Downloads use pinned checksums and install atomically.",settingsItem:"dictation.models",contentClassName:"space-y-1",children:t.models.map(P=>e.jsxs("div",{className:"flex min-h-10 items-center gap-3 py-1.5",children:[e.jsx(bc,{checked:t.config.localModelId===P.id,onChange:()=>{x({localModelId:P.id,providerConfigId:"local"}).catch(E=>a(E.message))},ariaLabel:`Use ${P.description}`}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{x({localModelId:P.id,providerConfigId:"local"}).catch(E=>a(E.message))},children:[e.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:P.description}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Uh(P.sizeBytes)})]}),P.downloading?e.jsx("span",{className:"typography-meta tabular-nums text-muted-foreground",children:P.downloadProgress===null?"Downloading...":`Downloading ${P.downloadProgress}%`}):P.installed?e.jsxs(e.Fragment,{children:[e.jsx(M,{name:"check",className:"size-4 text-[var(--status-success)]","aria-label":"Installed"}),e.jsx(S,{className:tt,variant:"ghost",size:"icon",disabled:p===P.id,onClick:()=>{b(P.id,"DELETE")},title:"Delete model","aria-label":`Delete ${P.description}`,children:e.jsx(M,{name:"delete-bin",className:"size-4"})})]}):e.jsx(S,{variant:"outline",size:"sm",disabled:p===P.id,onClick:()=>{b(P.id,"POST")},children:P.corrupt||P.downloadError?"Retry":"Download"})]},P.id))}),e.jsxs(q,{title:"OpenAI-compatible provider",info:"The server stores this configuration. Dictation sockets receive only its ID, never the URL or API key.",settingsItem:"dictation.remote",contentClassName:"space-y-4",children:[e.jsx(Me,{label:"Server URL",children:e.jsx(ee,{value:r,onChange:P=>i(P.target.value),placeholder:"https://api.openai.com/v1",className:"h-8"})}),e.jsx(Me,{label:"Model",children:e.jsx(ee,{value:c,onChange:P=>o(P.target.value),placeholder:"whisper-1",className:"h-8"})}),e.jsx(Me,{label:"API key",info:k?.apiKeyConfigured?"A key is already stored. Leave this blank to keep it.":"Optional for servers that do not require authentication.",children:e.jsx(ee,{type:"password",value:d,onChange:P=>m(P.target.value),placeholder:k?.apiKeyConfigured?"Stored key":"Optional",className:"h-8",autoComplete:"off"})}),e.jsx("div",{className:us,children:e.jsx(S,{onClick:()=>{j()},disabled:u||!r.trim()||!c.trim(),children:u?"Saving...":"Save provider"})})]}),n?e.jsx("p",{role:"alert",className:"pb-6 typography-meta text-[var(--status-error)]",children:n}):null]})}const $r=256,Wr=280,Bh=["general","appearance","chat","dictation","notifications","sessions","shortcuts","about","projects","remote-access","servers","tunnel","git","providers","behavior","snippets","prompt-templates","skills.installed","plugins"];function Eo(t,s){return t.isAvailable?.(s)??!0}function $h(t,s,n=!1){return{isWeb:!t&&Ht(),isDesktop:t,isMobile:s,isCapacitor:n}}function Kr(t,s){const n=new Set(s);let a=t,r=1;for(;n.has(a);)a=`${t}-${r}`,r+=1;return a}function Wh(){return e.jsx("div",{className:"flex h-full items-center justify-center px-6",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("div",{className:Pc,children:"Not available"}),e.jsx("p",{className:"typography-ui text-muted-foreground mt-1",children:"This settings page is not available in this runtime."})]})})}function nn({slug:t,isMobile:s,runtimeCtx:n,openChamberSectionBySlug:a,onActiveConnectionDeleted:r}){const i=As(t);if(i&&!Eo(i,n))return e.jsx(Wh,{});switch(t){case"projects":return e.jsx(Ru,{});case"remote-access":return e.jsx(Tr,{});case"servers":return e.jsx(Cp,{onActiveConnectionDeleted:r});case"remote-instances":return e.jsx(Tr,{});case"behavior":return e.jsx(Ed,{});case"skills.installed":return e.jsx(Md,{});case"plugins":return e.jsx(Nu,{});case"providers":return e.jsx(Xp,{});case"about":return e.jsx(xe,{title:s?void 0:"About",children:e.jsx(Ki,{})});case"snippets":return e.jsx(tm,{});case"prompt-templates":return e.jsx(im,{});case"dictation":return e.jsx(Fh,{});case"git":return e.jsx(xe,{title:s?void 0:"Git",children:e.jsx(Wa,{})});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"tunnel":{const c=a[t]??"visual";return e.jsx(Ih,{section:c})}default:return null}}const Kh=["general","projects","agent"];function Hh({isMobile:t,isMobileSettingsSearchOpen:s,settingsSearchQuery:n,setSettingsSearchQuery:a,handleSettingsSearchKeyDown:r,settingsSearchResults:i,groupedSettingsSearchResults:c,activeSearchResultIndex:o,setActiveSearchResultIndex:d,searchResultRefs:m,keyboardSearchNavigationRef:p,openSearchResult:h,sortedFilteredPages:u,settingsSlug:g,mobileStage:v,openPage:x,getPageTitle:b,activeRemoteLabel:j,mobileAppActions:k}){const P=n.trim().length>0,E=t?s&&P:P;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[t?E?null:e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>{if(k?.openInstances){k.openInstances();return}x("servers")},className:U("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",j?"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:j?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:j}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-[var(--status-success)] animate-pulse","aria-hidden":!0}),e.jsx("span",{className:"text-[var(--status-success)]",children:"Connected"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground truncate",children:"Not connected"}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"text-muted-foreground",children:"Select a server"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]})}),e.jsx(M,{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(M,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{value:n,onChange:y=>a(y.target.value),onKeyDown:r,placeholder:"Search settings","aria-label":"Search settings",className:"typography-ui-label min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-subtle-foreground"}),P&&e.jsx("button",{type:"button",onClick:()=>a(""),"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(M,{name:"close",className:"h-3.5 w-3.5"})})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden",children:e.jsx("div",{className:"flex flex-col gap-0.5 px-3 pt-3 pb-2",children:E?i.length>0?(()=>{let y=0;return c.map(f=>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-subtle-foreground",children:f.pageTitle}),f.results.map(N=>{const C=y;y+=1;const w=C===o,L=!!N.description;return e.jsxs("button",{type:"button",ref:I=>{m.current[C]=I},onMouseMove:()=>{p.current=!1,d(C)},onClick:()=>h(N),className:U("flex w-full flex-col rounded-md px-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",L?"min-h-11 py-1.5":"py-2",w?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.title}),L&&e.jsx("span",{className:"typography-micro text-subtle-foreground line-clamp-2",children:N.description})]},N.id)})]},f.page))})():e.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:"No matching settings"}):(()=>{const y=new Map;for(const N of u){const C=N.group,w=y.get(C);w?w.push(N):y.set(C,[N])}return Kh.map(N=>({group:N,pages:y.get(N)??[]})).filter(N=>N.pages.length>0).map(({group:N,pages:C},w)=>{const L=N==="projects"?"Workspace":N==="agent"?"Agent":null;return e.jsxs("div",{className:"space-y-0.5",children:[L?e.jsx("div",{className:U("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",w===0?"pt-1":"pt-4 sm:pt-3"),children:L}):null,C.map(I=>{const T=g===I.slug&&!(t&&v==="nav"),A=Tc(I.slug);return A?e.jsx(di,{children:e.jsx(ui,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>x(I.slug),"aria-current":T?"page":void 0,className:U("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",T?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[e.jsx(M,{name:A,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:b(I.slug)}),I.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"})]})]})})},I.slug):null})]},N)})})()})})]})}function Vh(t){const[s,n]=l.useState(null);return l.useEffect(()=>{const a=async()=>{try{const{loadMobileConnections:c,isActiveRuntimeConnection:o}=await Yt(async()=>{const{loadMobileConnections:p,isActiveRuntimeConnection:h}=await Promise.resolve().then(()=>ud);return{loadMobileConnections:p,isActiveRuntimeConnection:h}},void 0),m=(await c().catch(()=>[])).find(p=>o(p));if(m){n(m.label);return}}catch{}if(t){n(t);return}try{const{desktopHostsGet:c}=await Yt(async()=>{const{desktopHostsGet:v}=await import("./index-BxKPJ9uG.js").then(x=>x.d0);return{desktopHostsGet:v}},__vite__mapDeps([4,5,1,6,2,7,8,9])),{buildLocalDesktopHost:o,getLocalDesktopOrigin:d,resolveCurrentDesktopHost:m}=await Yt(async()=>{const{buildLocalDesktopHost:v,getLocalDesktopOrigin:x,resolveCurrentDesktopHost:b}=await import("./index-BxKPJ9uG.js").then(j=>j.d1);return{buildLocalDesktopHost:v,getLocalDesktopOrigin:x,resolveCurrentDesktopHost:b}},__vite__mapDeps([4,5,1,6,2,7,8,9])),p=await c().catch(()=>({hosts:[]})),u=[o(d()),...p.hosts],g=m(u);if(g&&g.label&&g.label!=="Instance"){n(g.label);return}}catch{}const r=xt(),i=qe();if(i==="local"){n("Local");return}if(i.startsWith("relay:")){const c=i.split(":")[1]?.split("@")[0];n(c?`Relay ${c.slice(0,8)}`:"Private relay");return}if(i.startsWith("host:")){n(i.replace("host:",""));return}if(r)try{const c=new URL(r);n(c.host);return}catch{n(r);return}n(null)};return a(),yn(()=>{a()})},[t]),s}const Gh=[{id:"appearance.time-format",page:"appearance",title:"Time format",keywords:["clock","12h","24h"]},{id:"appearance.week-start",page:"appearance",title:"Week starts on",keywords:["calendar","monday","sunday"]},{id:"appearance.sidebar-view",page:"appearance",title:"Sidebar view",keywords:["sidebar","sessions","folders","workspace","timeline","threads","layout","group"]},{id:"appearance.color-mode",page:"appearance",title:"Mode",description:"Follow the system, or stay light or dark.",keywords:["color mode","colour mode","light mode","dark mode","system theme","appearance"]},{id:"appearance.theme",page:"appearance",title:"Theme",description:"Pick a theme; it has a light and a dark version, used by the mode.",keywords:["theme","color","colour","palette","light theme","dark theme","custom themes","reload themes"]},{id:"appearance.wallpaper",page:"appearance",title:"Wallpaper",description:"A pattern or your own picture behind the new-session screen.",keywords:["background","dither","ascii","halftone","strands","grain","pattern","new session","texture"]},{id:"appearance.wallpaper-picture",page:"appearance",title:"Wallpaper picture",description:"Upload a picture to show behind the pattern, which takes its colours.",keywords:["image","photo","upload","background","wallpaper","custom","show behind the pattern"]},{id:"appearance.wallpaper-sessions",page:"appearance",title:"Show in open sessions",description:"Also show the wallpaper at the top of open sessions, fainter and still.",keywords:["wallpaper","background","session","chat","picture","everywhere"]},{id:"appearance.wallpaper-motion",page:"appearance",title:"Moving wallpaper",description:"The wallpaper's pattern drifts slowly.",keywords:["animate","animation","motion","wallpaper","dither","ascii","halftone","strands"]},{id:"appearance.dock-badge",page:"appearance",title:"Dock badge",description:"Show a count of chats with unseen activity on the macOS dock icon.",keywords:["dock","badge","unread","unseen","counter","count","notification","macos"],isAvailable:t=>t.isMac},{id:"appearance.pwa-install-name",page:"appearance",title:"Install app name",description:"Used by PWA installation process.",keywords:["pwa","installed app"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.pwa-orientation",page:"appearance",title:"Install orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",keywords:["pwa","portrait","landscape"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.mobile-keyboard-mode",page:"appearance",title:"Mobile keyboard behavior",description:"Default browser behavior is safest. Resize content asks supported browsers to shrink the app when the on-screen keyboard opens.",keywords:["mobile","keyboard","resize"],isAvailable:t=>t.isMobile&&t.isWeb&&!t.isDesktop},{id:"appearance.interface-font-size",page:"appearance",title:"Interface font size",keywords:["font","text size","ui scale"]},{id:"appearance.terminal-font-size",page:"appearance",title:"Terminal font size",keywords:["terminal","font","text size"]},{id:"appearance.terminal-shell",page:"general",title:"Terminal shell",description:"Restart the terminal to apply this change to the current session.",keywords:["terminal","shell","bash","zsh","fish","pwsh","powershell"]},{id:"appearance.editor-font-size",page:"appearance",title:"Editor font size",keywords:["editor","font","text size","code"]},{id:"appearance.spacing-density",page:"appearance",title:"Spacing density",keywords:["density","compact","comfortable","spacing"]},{id:"appearance.input-bar-offset",page:"appearance",title:"Input bar offset",description:"Raise input bar to avoid OS-level screen obstructions like home bars.",keywords:["input","home bar","offset"],isAvailable:t=>t.isMobile},{id:"appearance.auto-save-enabled",page:"general",title:"Auto-save files",description:"Automatically save file edits after you stop typing. Disable to require manual save.",keywords:["editor","autosave","auto-save","files","save"]},{id:"appearance.expanded-editor-toolbar",page:"general",title:"Always show editor toolbar (docked under the file tabs)",keywords:["editor","toolbar","tabs","docked","files"]},{id:"appearance.wrap-lines-by-default",page:"appearance",title:"Wrap long lines in files and diffs",description:"Applies to the file viewer and diffs. The wrap toggle in each view overrides it until reload.",keywords:["word wrap","wrap","line wrap","soft wrap","wrap lines","diff","editor"]},{id:"appearance.file-editor-keymap",page:"general",title:"File editor keymap",keywords:["editor","vim","keymap"]},{id:"appearance.terminal-quick-keys",page:"general",title:"Terminal quick keys",description:"Show Esc, Ctrl, Arrows in terminal view",keywords:["terminal","keyboard","esc","ctrl","arrows"]},{id:"dictation.enabled",page:"dictation",title:"Enable dictation",description:"Record speech and insert the final transcript at the composer caret.",keywords:["voice","speech","microphone","stt"]},{id:"dictation.provider",page:"dictation",title:"Transcription provider",keywords:["local","remote","openai","whisper","parakeet"]},{id:"dictation.language",page:"dictation",title:"Dictation language",keywords:["language","locale","auto-detect"]},{id:"dictation.models",page:"dictation",title:"Local speech models",keywords:["download","delete","whisper","parakeet"]},{id:"dictation.remote",page:"dictation",title:"OpenAI-compatible transcription",keywords:["api key","server url","audio transcriptions"]},{id:"about.desktop-update-channel",page:"about",title:"Desktop app channel",description:"Choose stable desktop releases only, or check stable releases before desktop release candidates. Switching channels does not downgrade the installed app.",keywords:["updates","update channel","release candidate","rc","electron","prerelease"],isAvailable:t=>t.isDesktop},{id:"about.server-update-channel",page:"about",title:"Server channel",description:"Choose stable server releases only, or check stable releases before server release candidates. Switching channels does not downgrade the installed server.",keywords:["updates","update channel","release candidate","rc","server","remote","prerelease"],isAvailable:t=>!(t.isDesktop&&t.isDesktopLocalOrigin)},{id:"about.app-update-channel",page:"about",title:"App channel",description:"Choose stable app releases only, or include release candidates. Switching channels does not downgrade the installed app.",keywords:["updates","update channel","release candidate","rc","android","ios","mobile","prerelease"],isAvailable:t=>t.isCapacitor===!0},{id:"general.chat-link-target",page:"general",title:"Open chat links in",description:"Open web links clicked in chat in the PiChamber browser or the system browser.",keywords:["browser","links","url","web","open","external","system browser"]},{id:"general.browser-data",page:"general",title:"Clear browsing data",description:"Sign out of every site in the server browser by deleting its cookies and site data.",keywords:["browser","cookies","logins","sign in","saved","clear","cache","web"]},{id:"general.performance-overlay",page:"general",title:"Performance overlay",description:"Show a live frame-time overlay for debugging jank. Adds overhead and stays on this device only.",keywords:["fps","performance","hud","diagnostics","debug","jank","frame"]},{id:"general.process-performance-recording",page:"general",title:"Record Electron process performance",description:"Record Electron process CPU and memory samples to a local diagnostics file.",keywords:["performance","diagnostics","memory","cpu","electron","process","recording"],isAvailable:t=>t.isDesktop},{id:"chat.draft-starters-visible",page:"chat",title:"Show starters on new session screen",keywords:["starter","starters","new session","welcome","suggestions"]},{id:"chat.follow-up-behavior",page:"chat",title:"Follow-up behavior",description:"Choose what happens when you send a follow-up while the agent is still responding. Follow-up waits until the agent finishes; Steering is delivered at the next supported tool or turn boundary. Follow-ups stay on this device.",keywords:["follow up","follow-up","queue","steer","steering","send immediately","send now"]},{id:"sessions.default-model",page:"sessions",title:"Default model",keywords:["model","provider","new sessions","picker"]},{id:"sessions.default-thinking",page:"sessions",title:"Default thinking",keywords:["thinking","reasoning","variant","new sessions","per model"]},{id:"sessions.default-retry-limit",page:"sessions",title:"Default retry limit",description:"How many times Pi automatically retries a failed agent turn for new sessions.",keywords:["retry","retries","retry limit","auto retry","max retries","agent run"]},{id:"sessions.extension-interface",page:"sessions",title:"Extension interface",description:"Let extensions draw their terminal UI, or ask them for standard dialogs.",keywords:["extension","extensions","terminal","tui","custom ui","dialogs","permission prompts","keyboard"]},{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-archive",page:"sessions",title:"Archive idle sessions after",description:"Archives sessions after this many days without activity. Sending a message brings one back.",keywords:["archive","auto-archive","idle","settle","retention","cleanup","inactive","days"]},{id:"sessions.auto-delete",page:"sessions",title:"Delete archived sessions",description:"Deletes archived sessions this many days after they were archived.",keywords:["delete","auto-delete","retention","cleanup","expire","days"]},{id:"sessions.auto-cleanup",page:"sessions",title:"Archive and delete now",keywords:["cleanup","retention","archive","delete","run"]},{id:"sessions.desktop-launch-at-login",page:"general",title:"Start PiChamber when you log in",description:"Starts the app in the background without opening a window. Use the desktop status icon to open it.",keywords:["desktop","startup","login","launch","background","autostart"],isAvailable:t=>t.isDesktop},{id:"sessions.desktop-mac-menu-bar",page:"general",title:"Show PiChamber in the menu bar",description:"Requires an app restart. When off, PiChamber does not create the menu bar item or run its session, approval, and usage updates.",keywords:["desktop","menu bar","tray","status item","macos","background"],isAvailable:t=>t.isDesktopLocalOrigin&&t.isMac},{id:"sessions.desktop-minimize-to-tray",page:"general",title:"Minimize to the system tray",description:"Hides PiChamber in the system tray instead of leaving it in the taskbar when you minimize the window.",keywords:["desktop","tray","system tray","minimize","taskbar","background","windows","linux"],isAvailable:t=>t.isDesktop&&(t.isWindows||t.isLinux)},{id:"sessions.desktop-close-to-tray",page:"general",title:"Close to the system tray",description:"Keeps PiChamber running in the system tray when you close the main window. Turn this off to quit the app when the window closes.",keywords:["desktop","tray","system tray","close","quit","exit","background","windows","linux"],isAvailable:t=>t.isDesktop&&(t.isWindows||t.isLinux)},{id:"sessions.desktop-keep-awake",page:"general",title:"Keep computer awake while PiChamber is running",description:"Prevents system sleep so phones can keep reaching this app. The screen can still turn off.",keywords:["desktop","sleep","awake","server","mobile","phone"],isAvailable:t=>t.isDesktop},{id:"sessions.desktop-ui-password",page:"remote-access",title:"Desktop UI password",description:"PiChamber asks after restart, then when the login session expires: after 12 hours, or 7 days with Trust this device. Leave empty to disable login.",keywords:["desktop","password","auth","login","remote access","security"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-lan-access",page:"remote-access",title:"Let other devices on your local network open this app",description:"Restarts the app so phones, tablets, and other computers on your Wi-Fi can open it. On Windows, allow PiChamber through the firewall if a phone still cannot connect.",keywords:["desktop","lan","network","phone","tablet","wifi","firewall","remote access","local network"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"git.github-status",page:"git",title:"GitHub CLI status",description:"Installed version and signed-in hosts.",keywords:["github","gh","cli","version","installed"]},{id:"git.github-account",page:"git",title:"GitHub account",description:"Signed-in account per host from the GitHub CLI (read-only).",keywords:["github","account","login","gh auth","prs","issues"]},{id:"git.github-scopes",page:"git",title:"GitHub token scopes",description:"Missing scopes with the gh auth refresh command.",keywords:["github","scopes","token","permissions","gh auth refresh"]},{id:"git.github-check-again",page:"git",title:"Check GitHub again",keywords:["github","refresh","retry","check again"]},{id:"git.changes-view",page:"git",title:"Changes view",keywords:["changes","flat list","tree view"]},{id:"git.gitignored-files",page:"git",title:"Display gitignored files",keywords:["ignored","files","gitignore"]},{id:"projects.name",page:"projects",title:"Name",keywords:["label","display name","project metadata","project name"]},{id:"projects.default-model",page:"projects",title:"Default model",keywords:["model","provider","new chat","session default","project metadata"]},{id:"projects.worktree",page:"projects",title:"Worktree",keywords:["worktree","branch","repository"]},{id:"projects.worktree.setup.wait",page:"projects",title:"Wait for setup commands before creating or sending a session",keywords:["worktree","setup commands","bootstrap","wait"]},{id:"projects.sandbox",page:"projects",title:"Sandbox",description:"Run a project's sessions inside nono, with allowed hosts, local ports and extra folders.",keywords:["sandbox","nono","isolation","landlock","allowed hosts","ports","extra folders"]},{id:"projects.sandboxing",page:"projects",title:"Sandboxing",description:"Whether nono can run on the server machine, what it cannot enforce there, and the sandbox profile.",keywords:["sandbox","nono","landlock","seatbelt","macos","wsl","wsl2","check again","isolation","profile","policy","custom profile"]},{id:"projects.sandbox-default",page:"projects",title:"Sandbox projects by default",description:"Sandbox every project set to Default, including folders you add later.",keywords:["sandbox","nono","default","all projects","isolation"]},{id:"projects.sandbox-default-hosts",page:"projects",title:"Allowed hosts for all projects",description:"Hosts every sandboxed project's agent may reach, with GitHub and package registry presets.",keywords:["sandbox","nono","allowed hosts","network","github","npm","registry","domains"]},{id:"remote-access.client-auth",page:"remote-access",title:"Add a device",description:"Create a one-time QR code so the PiChamber app on another device can connect to this server.",keywords:["pairing link","pair","qr","device","devices","mobile","phone","remote access","relay","connect from anywhere"]},{id:"remote-access.ways",page:"remote-access",title:"Ways to connect",description:"Local network and Tailscale routes other devices can use to reach this computer.",keywords:["connect","route","routes","remote access","lan","tailscale"]},{id:"remote-access.lan",page:"remote-access",title:"Local network",description:"Phones and computers on your Wi-Fi reach this computer directly.",keywords:["lan","network","wifi","local network","remote access"]},{id:"remote-access.tailscale",page:"remote-access",title:"Tailscale",description:"Private tailnet or public Funnel address for this computer.",keywords:["tailscale","funnel","vpn","tailnet","private","public","remote access","serve"]},{id:"remote-access.tailscale-port",page:"remote-access",title:"Tailscale HTTPS port",description:"HTTPS port for the Tailscale address.",keywords:["port","443","8443","10000","https","conflict"]},{id:"remote-access.devices",page:"remote-access",title:"Devices with access",description:"Paired devices and pending pairings. Revoking removes a device immediately.",keywords:["device","devices","paired","revoke","remove device","remote access"]},{id:"remote-access.security",page:"remote-access",title:"Remote access security",description:"The password protects browser sign-in and is required for Local network and Tailscale access.",keywords:["security","password","passkey","remote access","sign-in","login"]},{id:"remote-access.passkeys",page:"remote-access",title:"Passkeys",description:"Sign in with a passkey instead of the UI password.",keywords:["passkey","passkeys","webauthn","password","remote access","security"],isAvailable:t=>t.isWeb&&!t.isDesktop&&!t.isMobile},{id:"servers.direct-hosts",page:"servers",title:"Saved servers",description:"Servers this app can switch to. Import a pairing link from the other server, or add one by address.",keywords:["server","servers","saved servers","other servers","instance","server url","connection token","import link","host switcher","switch","connect","additional headers","request headers","cloudflare access","service token"],isAvailable:t=>t.isDesktop||t.isMobile&&t.isCapacitor===!0},{id:"behavior.system-prompt",page:"behavior",title:"Global AGENTS.md",description:"Global rules are combined with project rules",keywords:["agents.md","global instructions","system prompt"]},{id:"behavior.response-style",page:"behavior",title:"Response style",description:"When enabled, these instructions guide how the assistant responds in each new conversation. They are sent with your first message and do not change your global AGENTS.md rules.",keywords:["tone","concise","detailed","custom instructions"]},{id:"snippets.create",page:"snippets",title:"Create snippet",keywords:["add","new snippet"]},{id:"snippets.content",page:"snippets",title:"Content",keywords:["markdown","text expansion"]},{id:"prompt-templates.create",page:"prompt-templates",title:"Create prompt template",keywords:["add","new prompt","slash command"]},{id:"prompt-templates.content",page:"prompt-templates",title:"Content",keywords:["markdown","prompt","template","arguments"]},{id:"providers.connect",page:"providers",title:"Connect provider",keywords:["add provider","connect provider","credentials"]},{id:"providers.custom",page:"providers",title:"Custom provider",description:"Add an OpenAI-compatible provider with a base URL, credentials, and model list. Saved to Pi so it is available in chat like any other provider.",keywords:["other","custom","openai-compatible","base url","api key"]},{id:"providers.auth",page:"providers",title:"Authentication",keywords:["api key","oauth","credentials"]},{id:"providers.connection-details",page:"providers",title:"Connection details",keywords:["config","source","disconnect"]},{id:"providers.models",page:"providers",title:"Available models",description:"Hide models you do not want in the composer or session default pickers.",keywords:["models","hide","show"]},{id:"plugins.visuals",page:"plugins",title:"Visuals",description:"Let the agent draw HTML pages in the chat",keywords:["html","render","chart","diagram","page","mockup","plugin"]},{id:"plugins.subagents",page:"plugins",title:"Sub-agents",description:"Let the agent hand tasks to other agents with their own context",keywords:["subagent","sub-agent","agents","delegate","parallel","chain","scout","reviewer","plugin"]},{id:"plugins.browse",page:"plugins",title:"Browse Pi packages",description:"Find and install Pi packages from npm, and see which work with PiChamber",keywords:["marketplace","browse","install","npm","gallery","store","find","search","pi install","update"]},{id:"plugins.extensions",page:"plugins",title:"Pi extensions",description:"Turn Pi's extensions on or off, globally or for this project",keywords:["extension","extensions","pi config","global","project","override","enable","disable","load"]},{id:"plugins.extensions.packages",page:"plugins",title:"Pi packages",description:"See the packages Pi has installed, update one, or remove it",keywords:["package","packages","npm","git","pi list","pi remove","uninstall","remove","installed"]},{id:"plugins.extensions.builtin",page:"plugins",title:"Built into Pi",description:"Extensions that ship with Pi",keywords:["built-in","builtin","mcp","codemode","tool-search","tool search"]},{id:"skills.discovery",page:"skills.installed",title:"Skills",keywords:["skills","agent skills","project resources"]},{id:"shortcuts.keyboard-shortcuts",page:"shortcuts",title:"Keyboard shortcuts",description:"Capture a new key combo, save it, and bindings will update immediately.",keywords:["keyboard","hotkeys","bindings"]},{id:"shortcuts.command-triggers",page:"shortcuts",title:"Command triggers",description:"Quick-action buttons above the composer and optional keybindings that run slash commands.",keywords:["quick actions","slash commands","toolbar buttons","triggers"]},{id:"tunnel.provider",page:"tunnel",title:"Provider",description:"Configure secure remote access with your own managed Cloudflare tunnel.",keywords:["managed remote","managed local","cloudflare"]},{id:"tunnel.type",page:"tunnel",title:"Tunnel type",keywords:["managed remote","managed local"]},{id:"tunnel.ttl",page:"tunnel",title:"Connect link TTL",description:"Tunnel session TTL",keywords:["expiry","expiration","session ttl","connect link ttl"]},{id:"tunnel.managed-remote",page:"tunnel",title:"Saved managed remote tunnels",keywords:["cloudflare","hostname","token","managed remote"]},{id:"tunnel.managed-local-config",page:"tunnel",title:"Configuration file",description:"Managed local tunnels use your local cloudflared configuration file.",keywords:["cloudflared","config","yaml","json","managed local"]},{id:"tunnel.start",page:"tunnel",title:"Start tunnel",description:"Connect links are one-time and are revoked when tunnel stops or connect-link TTL expires.",keywords:["connect link","qr code","public url","remote access"]},{id:"notifications.delivery",page:"notifications",title:"Notification delivery",keywords:["desktop notifications","mobile notifications","system notifications"]},{id:"notifications.events",page:"notifications",title:"Notification events",keywords:["completion","finished","errors","failed","input needed","approval","waiting","extension"]}];function Hr(t){return t.trim().toLocaleLowerCase()}function qh({query:t,runtimeCtx:s,visiblePageSlugs:n,getPageTitle:a}){const r=Hr(t);if(!r)return[];const i=n?new Set(n):null,c=r.split(/\s+/).filter(Boolean);return Gh.flatMap(o=>{if(i&&!i.has(o.page))return[];const d=As(o.page);if(!d||d.isAvailable&&!d.isAvailable(s)||o.isAvailable&&!o.isAvailable(s))return[];const m=o.title,p=o.description??null,h=Hr([m,p,a(o.page),...o.keywords??[]].filter(Boolean).join(" "));return c.every(u=>h.includes(u))?[{...o,title:m,description:p,pageTitle:a(o.page)}]:[]})}function Qh({runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n,openPage:a,isMobile:r,setMobileStage:i,containerRef:c,settingsSlug:o}){const[d,m]=l.useState(""),[p,h]=l.useState(!1),u=l.useRef(null),[g,v]=l.useState(null),[x,b]=l.useState(0),j=l.useRef([]),k=l.useRef(0),P=l.useRef(!1),E=l.useMemo(()=>qh({query:d,runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n}),[n,t,d,s]),y=l.useCallback(w=>{if(w.id.startsWith("snippets.")){const L=ot.getState(),I=Kr("new-snippet",L.snippets.map(T=>T.name));return L.setSnippetDraft({name:I,scope:"global"}),L.setSelectedSnippet(null),w.id==="snippets.create"?"snippets.content":w.id}if(w.id.startsWith("prompt-templates.")){const L=dt.getState(),I=Kr("new-prompt",L.prompts.map(T=>T.name));return L.setPromptDraft({name:I,location:"global"}),L.setSelectedPrompt(null),w.id==="prompt-templates.create"?"prompt-templates.content":w.id}return w.id==="providers.connect"&&ga.getState().setSelectedProviderId(null),w.id},[]),f=l.useMemo(()=>{const w=[],L=new Map;for(const I of E){let T=L.get(I.page);T||(T={page:I.page,pageTitle:I.pageTitle,results:[]},L.set(I.page,T),w.push(T)),T.results.push(I)}return w},[E]);l.useEffect(()=>{b(0),k.current=0,P.current=!1},[d]),l.useEffect(()=>{k.current=x},[x]),l.useEffect(()=>{j.current[x]?.scrollIntoView({block:"nearest"})},[x]),l.useEffect(()=>{x>=E.length&&b(Math.max(0,E.length-1)),j.current.length=E.length},[x,E.length]);const N=l.useCallback(w=>{const L=y(w);v(L),a(w.page),r&&i("page-content")},[r,a,y,i]),C=l.useCallback(w=>{if(w.key==="Escape"){if(w.preventDefault(),d.trim()){m("");return}r&&p&&h(!1);return}if(d.trim()&&E.length!==0){if(w.key==="ArrowDown"){w.preventDefault(),P.current=!0,b(L=>(L+1)%E.length);return}if(w.key==="ArrowUp"){w.preventDefault(),P.current=!0,b(L=>(L-1+E.length)%E.length);return}if(w.key==="Enter"){w.preventDefault();const L=(k.current%E.length+E.length)%E.length,I=E[L]??E[0];I&&N(I)}}},[r,p,N,d,E]);return l.useEffect(()=>{const w=g;if(!w)return;let L=!1;const I=window.requestAnimationFrame(()=>{if(L)return;const T=typeof CSS<"u"&&CSS.escape?CSS.escape(w):w.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),A=c.current?.querySelector(`[data-settings-item="${T}"]`);if(A){v(null);for(let F=A.closest("details");F;F=F.parentElement?.closest("details")??null)F.open=!0;A.scrollIntoView({block:"center",behavior:"smooth"}),A.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{A.removeAttribute("data-settings-search-highlight")},1600)}});return()=>{L=!0,window.cancelAnimationFrame(I)}},[c,g,o]),{settingsSearchQuery:d,setSettingsSearchQuery:m,isMobileSettingsSearchOpen:p,setIsMobileSettingsSearchOpen:h,mobileSettingsSearchInputRef:u,activeSearchResultIndex:x,setActiveSearchResultIndex:b,searchResultRefs:j,keyboardSearchNavigationRef:P,settingsSearchResults:E,groupedSettingsSearchResults:f,openSearchResult:N,handleSettingsSearchKeyDown:C}}const Jh=({mobileStage:t,activePageMeta:s,getPageTitle:n,showBackButton:a,mobileBackButtonLabel:r,onBack:i,showOpenPageSidebarButton:c,onOpenPageSidebar:o,isMobileSettingsSearchOpen:d,setIsMobileSettingsSearchOpen:m,mobileSettingsSearchInputRef:p,settingsSearchQuery:h,setSettingsSearchQuery:u,handleSettingsSearchKeyDown:g,onClose:v,shortcutKey:x})=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:U("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",t!=="nav"&&"border-b","bg-background"),style:t!=="nav"?{borderColor:"var(--interactive-border)"}:void 0,children:[a?e.jsx("button",{type:"button",onClick:i,"aria-label":r,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(M,{name:"arrow-left-s",className:"h-5 w-5"})}):null,e.jsx("div",{className:"min-w-0 flex-1 px-2 typography-ui-label font-medium text-foreground truncate",children:t==="nav"?"Settings":s?n(s.slug):"Settings"}),c&&e.jsx("button",{type:"button",onClick:o,"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(M,{name:"list-unordered",className:"h-5 w-5"})}),t==="nav"?e.jsx("button",{type:"button",onClick:()=>{const b=!d;m(b),b?window.setTimeout(()=>p.current?.focus(),0):u("")},"aria-label":d?"Close search":"Search settings","aria-expanded":d,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(M,{name:d?"close":"search",className:"h-5 w-5"})}):null,v&&e.jsx("button",{type:"button",onClick:v,"aria-label":"Close settings",title:`Close Settings (${x}+,)`,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(M,{name:"close",className:"h-5 w-5"})})]}),t==="nav"&&d?e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b bg-background px-3 py-2",style:{borderColor:"var(--interactive-border)"},children:e.jsxs("div",{className:"flex h-10 min-w-0 flex-1 items-center gap-1.5 rounded-md border border-border bg-transparent px-2 text-muted-foreground focus-within:ring-2 focus-within:ring-primary/40",children:[e.jsx(M,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{ref:p,value:h,onChange:b=>u(b.target.value),onKeyDown:g,placeholder:"Search settings","aria-label":"Search settings",className:"typography-ui-label min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-subtle-foreground"}),h.trim().length>0?e.jsx("button",{type:"button",onClick:()=>u(""),"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(M,{name:"close",className:"h-3.5 w-3.5"})}):null]})}):null]}),Yh=({onClose:t,forceMobile:s,isWindowed:n,visiblePageSlugs:a,initialMobileStage:r="nav",onActiveConnectionDeleted:i})=>{const c=lt(),o=s??c.isMobile,d=yc(),m=Vh(d?.instanceLabel),p=V(X=>X.settingsPage),h=V(X=>X.isSettingsDialogOpen),u=V(X=>X.setSettingsPage),g=Ic(p),[v,x]=l.useState(r),b=l.useRef(r==="nav"?g:null);l.useEffect(()=>{!o&&g==="home"&&u("general")},[o,u,g]);const j=l.useRef(null),[k,P]=l.useState(0);l.useEffect(()=>yn(()=>{P(X=>X+1)}),[]);const E=l.useMemo(()=>Oe(),[]),y=l.useMemo(()=>Oe()&&ts(),[k]),f=l.useMemo(()=>Oe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),N=l.useMemo(()=>Oe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="win32",[]),C=l.useMemo(()=>Oe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="linux",[]),w=l.useMemo(()=>Sl(),[]),L=l.useMemo(()=>Re(),[]),I=l.useMemo(()=>$h(E,o,L),[E,o,L]),T=l.useMemo(()=>{const X=a?new Set(a):null;return Ec.filter(be=>be.slug!=="home").filter(be=>!X||X.has(be.slug)).filter(be=>Eo(be,I)).filter(be=>!(o&&(be.slug==="remote-access"||be.slug==="remote-instances"||be.slug==="servers"&&!L)))},[L,o,I,a]),A=l.useMemo(()=>{const X=new Map(Bh.map((be,ze)=>[be,ze]));return T.slice().sort((be,ze)=>(X.get(be.slug)??999)-(X.get(ze.slug)??999))},[T]),F=dn(X=>X.activeProjectId);l.useEffect(()=>{!h&&!n||g==="skills.installed"&&Wt.getState().loadSkills()},[F,h,n,g]);const _=l.useCallback(X=>{if(u(X),b.current=X,!o)return;const be=As(X);if(!be||be.slug==="home"){x("nav");return}x(be.kind==="split"?"page-sidebar":"page-content")},[o,u]),z=l.useMemo(()=>As(g),[g]),K=l.useMemo(()=>({general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",tunnel:"tunnel"}),[]),H=l.useCallback(X=>{switch(X){case"general":return"General";case"projects":return"Projects";case"remote-access":return"Remote access";case"servers":return"Servers";case"remote-instances":return"Remote access";case"providers":return"Providers";case"behavior":return"Behavior";case"skills.installed":return"Skills";case"plugins":return"Extensions & Plugins";case"git":return"Git";case"appearance":return"Appearance";case"chat":return"Chat";case"dictation":return"Dictation";case"shortcuts":return"Shortcuts";case"sessions":return"Sessions";case"snippets":return"Snippets";case"prompt-templates":return"Prompt templates";case"notifications":return"Notifications";case"tunnel":return"External tunnel";case"about":return"About";default:return"Settings"}},[]),ne=l.useMemo(()=>({...I,isDesktopLocalOrigin:y,isMac:f,isWindows:N,isLinux:C,isWindowsArm64:w}),[y,C,f,N,w,I]),{settingsSearchQuery:Z,setSettingsSearchQuery:ye,isMobileSettingsSearchOpen:oe,setIsMobileSettingsSearchOpen:we,mobileSettingsSearchInputRef:le,activeSearchResultIndex:ae,setActiveSearchResultIndex:pe,searchResultRefs:ce,keyboardSearchNavigationRef:Q,settingsSearchResults:G,groupedSettingsSearchResults:Pe,openSearchResult:re,handleSettingsSearchKeyDown:Ne}=Qh({runtimeCtx:ne,visiblePageSlugs:a,getPageTitle:H,openPage:_,isMobile:o,setMobileStage:x,containerRef:j,settingsSlug:g});l.useEffect(()=>{if(!o||v!=="nav"||g==="home"||b.current===g)return;const X=As(g);!X||X.slug==="home"||(b.current=g,x(X.kind==="split"?"page-sidebar":"page-content"))},[o,v,g]);const ge=o&&v!=="nav",Ce=v==="page-content"&&z?.kind==="split",W=ge?"Back to settings":"Close settings",de=Pl(),O=l.useCallback(()=>{x("page-content")},[]),J=l.useCallback(()=>{x("nav")},[]),te=l.useCallback(()=>{x("page-sidebar")},[]);l.useEffect(()=>{(!o||v!=="nav")&&we(!1)},[o,v,we]);const Ze=l.useCallback((X,be)=>null,[]),$=()=>e.jsx(Hh,{isMobile:o,isMobileSettingsSearchOpen:oe,settingsSearchQuery:Z,setSettingsSearchQuery:ye,handleSettingsSearchKeyDown:Ne,settingsSearchResults:G,groupedSettingsSearchResults:Pe,activeSearchResultIndex:ae,setActiveSearchResultIndex:pe,searchResultRefs:ce,keyboardSearchNavigationRef:Q,openSearchResult:re,sortedFilteredPages:A,settingsSlug:g,mobileStage:v,openPage:_,getPageTitle:H,activeRemoteLabel:m,mobileAppActions:d}),Y=()=>{if(v==="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(Mt,{children:$()})})});if(!z)return e.jsx("div",{className:"flex-1 bg-background"});if(v==="page-sidebar"){if(z.kind!=="split"){const X=e.jsx(nn,{slug:g,isMobile:o,runtimeCtx:I,openChamberSectionBySlug:K,onActiveConnectionDeleted:i});return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(Mt,{children:X})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(Mt,{children:Ze(g,{onItemSelect:O})})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(Mt,{children:e.jsx(nn,{slug:g,isMobile:o,runtimeCtx:I,openChamberSectionBySlug:K,onActiveConnectionDeleted:i})})})},ie=()=>!z||g==="home"?null:z.kind==="split"?e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[e.jsx("div",{className:U("border-r","bg-sidebar"),style:{width:Wr,minWidth:Wr,borderColor:"var(--interactive-border)"},children:e.jsx(Mt,{children:Ze(g,{})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(Mt,{children:e.jsx(nn,{slug:g,isMobile:o,runtimeCtx:I,openChamberSectionBySlug:K,onActiveConnectionDeleted:i})})})]}):e.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(Mt,{children:e.jsx(nn,{slug:g,isMobile:o,runtimeCtx:I,openChamberSectionBySlug:K,onActiveConnectionDeleted:i})})});return e.jsxs("div",{ref:j,"data-settings-view":"true",className:U("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),children:[o?e.jsx(Jh,{mobileStage:v,activePageMeta:z,getPageTitle:H,showBackButton:ge,mobileBackButtonLabel:W,onBack:J,showOpenPageSidebarButton:!!Ce,onOpenPageSidebar:te,isMobileSettingsSearchOpen:oe,setIsMobileSettingsSearchOpen:we,mobileSettingsSearchInputRef:le,settingsSearchQuery:Z,setSettingsSearchQuery:ye,handleSettingsSearchKeyDown:Ne,onClose:t,shortcutKey:de}):e.jsx(e.Fragment,{children:ge&&e.jsx("div",{className:U("absolute left-3 z-50",n?"top-2":"top-3"),children:e.jsx("button",{type:"button",onClick:J,"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(M,{name:"arrow-left-s",className:"h-5 w-5"})})})}),e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:o?Y():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:U("relative flex h-full min-h-0 flex-col overflow-hidden border-r","bg-sidebar"),style:{width:`${$r}px`,minWidth:`${$r}px`,borderColor:"var(--interactive-border)"},children:e.jsx(Mt,{children:$()})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:ie()})]})})]})},df=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:Yh},Symbol.toStringTag,{value:"Module"}));export{Ki as A,bd as M,Yh as S,yd as a,vd as b,Xt as c,Jn as d,kp as e,id as f,rd as g,df as h,hd as i,xd as m,Ui as p,Mi as r,fd as s,_i as u};