@pi-chamber/web 1.0.8-rc.2 → 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.
- package/dist/assets/{AgentsSurface-CcWBqAWV.js → AgentsSurface-wsW9VCRp.js} +1 -1
- package/dist/assets/{ChoicesArtifact-Kk-qvrSB.js → ChoicesArtifact-EwCf4Yxu.js} +1 -1
- package/dist/assets/{DiagramView-DZUBo1uP.js → DiagramView-BX6N99cQ.js} +1 -1
- package/dist/assets/{DiffView-CiZy4jFA.js → DiffView-CI0eSnPP.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-DZ9NDwOO.js → FileSaveConflictDialog-GLj2W7VE.js} +1 -1
- package/dist/assets/{FilesView-DqiZ9kw9.js → FilesView-CI0tfZQL.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-DM2DH7o8.js → GitHubDetailScaffold-B85tZ9m7.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-ChB8NZ1h.js → GitHubLinkPicker-Y6AuNiGl.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-CibDiJGq.js → GitHubListPrimitives-BJHBud6i.js} +1 -1
- package/dist/assets/{GitView--EaZQrBr.js → GitView-DueE69kW.js} +3 -3
- package/dist/assets/{IssuesSurface-CySTpaD1.js → IssuesSurface-Cg-xkdIu.js} +2 -2
- package/dist/assets/{JsonTreeView-_yMHKKQZ.js → JsonTreeView-Cvg6lc40.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-D_-2fQw0.js → MarkdownRendererImpl-DExPx-QM.js} +1 -1
- package/dist/assets/{PatchDiff-bHObDlhD.js → PatchDiff-_c3HZ34I.js} +1 -1
- package/dist/assets/{PierreDiffViewer-UY7Cse-s.js → PierreDiffViewer-CZnaqO-_.js} +1 -1
- package/dist/assets/{PullRequestsSurface-iXy6chwc.js → PullRequestsSurface-C9AYPiwo.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-DJGCa_wN.js → SessionSwitcherContent-DOpnN-8S.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CDOX-5Y2.js → SessionSwitcherDropdown-CmHMPZ69.js} +2 -2
- package/dist/assets/{SessionUnreadDot-Dwc3MdvA.js → SessionUnreadDot-CZCQ4t1J.js} +1 -1
- package/dist/assets/SettingsView-D5PO5M3z.js +11 -0
- package/dist/assets/{SettingsWindow-CUg49Mfh.js → SettingsWindow-DXV5UOE8.js} +1 -1
- package/dist/assets/{SubagentsArtifact-DUZX9tDe.js → SubagentsArtifact-CO1ZiI1x.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BuZZaRw4.js → ToolOutputDialog-GOwNLj-y.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CKncG6i2.js → ToolPartDiffPreview-BoaiZji6.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BGZiLPe_.js → VirtualizedFileDiff-Chq1X8nw.js} +1 -1
- package/dist/assets/VisualFrame-u7aRcX7O.js +22 -0
- package/dist/assets/{VisualsArtifact-Bq0vMO-i.js → VisualsArtifact-D9vPjihW.js} +1 -1
- package/dist/assets/{collapsible-Bro9KrfM.js → collapsible-BjpDEohv.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DJQqK49u.js → computeVirtualFileMetrics-DmPCxbok.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-ByWK3Sru.js → contextFileOpenGuard-CukNcUeY.js} +1 -1
- package/dist/assets/{fileTreeStatus-CyJ3TOYD.js → fileTreeStatus-CDyfNPYO.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BsXrwngT.js → gitStatusPredicates-uI7Y7L5k.js} +1 -1
- package/dist/assets/{githubLink-g2bmC0qi.js → githubLink-B9Mxac4R.js} +1 -1
- package/dist/assets/{index-C9rUUQ_Y.js → index-BWq2ibCw.js} +1 -1
- package/dist/assets/{index-CKKWVoND.js → index-BxKPJ9uG.js} +9 -9
- package/dist/assets/index-C5JgjS20.css +1 -0
- package/dist/assets/{main-DsLMU9CT.js → main-CWfC-9xT.js} +4 -4
- package/dist/assets/{main-DT-4_fhe.js → main-ckQ0ciIN.js} +2 -2
- package/dist/assets/{markdownCore-QmM_aOnZ.js → markdownCore-p2q2Kxwo.js} +1 -1
- package/dist/assets/{miniChat-BqGslD2z.js → miniChat-x2TrwRYA.js} +2 -2
- package/dist/assets/{mobile-C5JOcDIC.js → mobile-B0x2G8h1.js} +2 -2
- package/dist/assets/{nativeFileSave-DSMsJqXM.js → nativeFileSave-D542OJlG.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-Cc_S4zi1.js → pi-session-focus-preference-Q_RZUCnt.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-BXhnIAHg.js → renderDiffWithHighlighter-CSFGSknx.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CiSkecEE.js → renderElectronMiniChatApp-CFIdesZT.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-CK29YZtC.js → renderFileWithHighlighter-C5JE0mRX.js} +1 -1
- package/dist/assets/{renderMobileApp-C4JuoxsZ.js → renderMobileApp-B1ybjcGM.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-Dwj-jCDS.js → runtimeEndpointReset-DyZSKCYM.js} +7 -7
- package/dist/assets/{runtimeSurface-0K7vuUpd.js → runtimeSurface-BR_dhe7_.js} +1 -1
- package/dist/assets/{selection-CnYkEsu_.js → selection-CfOpW4rA.js} +1 -1
- package/dist/assets/{useAppFontEffects-CV5UyTRw.js → useAppFontEffects-COMvkffC.js} +97 -97
- package/dist/assets/{useGitHubRemoteSearch-CgP-zEBj.js → useGitHubRemoteSearch-M1AE2YuX.js} +1 -1
- package/dist/assets/{useSwitcherItems-C8G5F0hs.js → useSwitcherItems-D0i2BYYP.js} +1 -1
- package/dist/assets/{web-components-BpncHjnV.js → web-components-wOQkOurQ.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/plugins/visuals/extension.js +2 -2
- package/server/index.js +4 -0
- package/server/lib/pi/ui-settings-store.js +2 -1
- package/server/lib/wallpaper/DOCUMENTATION.md +25 -0
- package/server/lib/wallpaper/routes.js +63 -0
- package/server/lib/wallpaper/routes.test.js +109 -0
- package/server/lib/wallpaper/store.js +87 -0
- package/dist/assets/SettingsView-DA-U9lsj.js +0 -11
- package/dist/assets/VisualFrame-DBZkHFnG.js +0 -22
- package/dist/assets/index-B_L9GVYw.css +0 -1
|
@@ -1,11 +0,0 @@
|
|
|
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-DSMsJqXM.js","assets/index-CKKWVoND.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-B_L9GVYw.css","assets/useAppFontEffects-CV5UyTRw.js","assets/runtimeSurface-0K7vuUpd.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{C as Oo,b1 as Hr,j as e,bh as Uo}from"./vendor-boot-D-KEJjsM.js";import{R as l,a as D}from"./vendor-react-Bz1tRBxM.js";import{ac as ln,e as Me,ad as Ls,b as qe,I as ht,J as ja,H as Gr,ae as Fo,af as ms,ag as Wr,r as Ee,ah as Bo,ai as $o,c as F,s as yn,aj as Ke,f as Fe,B as ss,ak as Ko,al as Vo,am as qr,an as Ho,ao as Go,ap as Wo,aq as Qr,ar as qo,o as Qo,p as Ue,as as Te,k as Jo,at as Yo,u as W,au as Xo,av as Jr,aw as Zo,ax as el,ay as tl,a6 as Gt,az as sl,aA as nl,W as al,aB as rl,l as wa,aC as Yr,aD as Ha,aE as Ga,aF as Wa,aG as qa,aH as il,aI as Qa,aJ as ol,aK as ll,aL as Ja,aM as cl,aN as dl,aO as ul,aP as Ys,aQ as pl,aR as ml,aS as hl,aT as fl,aU as gl,aV as xl,aW as vl,aX as bl,aY as yl,aZ as jl,a_ as ut,w as Ya,a$ as Xa,b0 as Hn,a3 as wl,a7 as Za,b1 as ka,b2 as er,b3 as kl,b4 as Nl,U as Cl}from"./index-CKKWVoND.js";import{d7 as Sl,d8 as tr,d9 as Pl,bX as Xr,B as S,I as R,bY as Zr,af as us,bv as Re,bw as De,bx as _e,da as cn,by as ze,bz as je,bV as Ms,db as Tl,dc as Il,t as B,m as gt,n as xt,o as vt,p as bt,q as yt,U as vs,dd as jn,de as Qt,df as wn,dg as Jt,aj as El,ag as Na,ai as lt,dh as Vt,f as ee,di as ca,_ as Rs,dj as Al,aZ as Ca,dk as Ll,dl as Ml,g as ei,d5 as ti,cA as Rl,dm as Oe,dn as Dl,dp as _l,dq as zl,dr as os,ds as sr,dt as Ol,a as dn,bS as Ul,du as Fl,dv as Bl,dw as $l,dx as Gn,dy as nr,dz as Kl,dA as Vl,dB as Hl,dC as Gl,cK as Wl,a2 as $s,j as kn,dD as ql,dE as si,cb as Ql,bW as Jl,dF as Yl,bZ as ni,dG as Xl,dH as Zl,an as ec,dI as ai,dJ as ri,dK as ii,dL as oi,dM as un,ak as He,dN as pn,dO as it,dP as ct,dQ as tc,dR as sc,dS as nc,$ as ac,dT as rc,dU as ic,dV as oc,ap as li,aq as ci,ar as lc,dW as cc,dX as dc,dY as uc,aE as At}from"./useAppFontEffects-CV5UyTRw.js";import{aN as Be,aO as hs,aP as pc,aQ as q,aR as Ie,aS as Le,aT as mc,aU as da,aV as Ks,T as Sa,aW as Je,aX as Ct,aY as pt,aZ as Nn,a_ as ot,a$ as he,b0 as rt,b1 as Ge,b2 as Pt,b3 as Zt,b4 as fs,b5 as di,b6 as hc,b7 as ft,b8 as Ce,b9 as Cn,ba as mt,bb as Rt,bc as Ae,bd as fc,be as nt,bf as gc,bg as ui,bh as Ds,bi as Dt,bj as ps,A as Wn,bk as pi,bl as mi,bm as ar,bn as Lt,bo as Mt,bp as xc,bq as qn,br as hi,bs as Is,bt as vc,aM as bc,bu as yc,aL as jc}from"./runtimeEndpointReset-Dwj-jCDS.js";import{_ as Yt}from"./vendor-vite-runtime-DD1OZmLC.js";import{Q as fi}from"./vendor-qrcode-gzL9QFkg.js";import{p as wc}from"./vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js";import{c as kc}from"./vendor-zustand-CXhN0IMY.js";import{g as Nc,s as Cc}from"./runtimeSurface-0K7vuUpd.js";import{C as Sc,a as Pc,b as Tc}from"./collapsible-Bro9KrfM.js";const Ic=["standalone","minimal-ui","fullscreen","window-controls-overlay"],Ec=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Ac=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":Ic.find(n=>Ec(n))??"browser",mn="pichamber.mobile.connections.v1",Lc="pichamber.mobile.",rr="pichamber.mobile.deviceId",gi=12,xi=8e3,Mc=2500,Rc=5e3,vi=2500,gs=15e3,bi=8e3,Dc=1500,_c=5e3,zc=()=>{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:${zc()}`,or=()=>{try{const t=Oo.getPlatform();return t==="ios"||t==="android"?t:void 0}catch{return}},yi=()=>{let t=0;return{begin:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:s=>s===t}},ns=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(/\/+$/,"")},Es=t=>{try{return new URL(t).host}catch{return t}},_t=t=>{try{return ns(t)}catch{return t.trim().replace(/\/+$/g,"")}},Pa=(t,s)=>_t(t)===_t(s),Ta=t=>`relay:${t.serverId}@${t.relayUrl.trim()}`,Oc=t=>`relay://${t.serverId}`,_s=t=>t.candidates.filter(s=>s.kind==="direct"),es=t=>{const s=t.candidates.find(n=>n.kind==="relay");return s&&s.kind==="relay"?s.relay:null},Xt=t=>{const s=_s(t)[0];if(s)return s.url;const n=es(t);return n?Oc(n):""},$e=t=>{const s=es(t);if(s)return Ta(s);const n=_s(t)[0];return n?_t(n.url):""},As=(t,s)=>{const n=t.find(o=>o.kind==="relay"),a=n&&n.kind==="relay"?n.relay.serverId:null,r=new Set(t.filter(o=>o.kind==="direct").map(o=>_t(o.url)));return s.some(o=>o.kind==="relay"?a!==null&&o.relay.serverId===a:r.has(_t(o.url)))},Ia=t=>{const s=(()=>{try{return ns(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}}},Uc=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},Fc=t=>{if(t.mode==="relay"){const s=Ea(t.relay);return s?[{kind:"relay",relay:s}]:[]}return typeof t.url=="string"?Ia(t.url):[]},zs=t=>t.kind==="relay"?{kind:"relay",relay:{relayUrl:t.relay.relayUrl,serverId:t.relay.serverId,hostEncPubJwk:t.relay.hostEncPubJwk}}:{kind:"direct",url:t.url},Ot=()=>{if(typeof window>"u")return[];let t;try{t=JSON.parse(window.localStorage.getItem(mn)||"[]")}catch{return[]}if(!Array.isArray(t))return[];const s=Me();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(Uc).filter(h=>!!h):Fc(a);if(r.length===0)return[];const o=typeof a.clientToken=="string"&&a.clientToken.trim()?a.clientToken:void 0,c=typeof a.label=="string"&&a.label.trim()?a.label:Es(Xt({candidates:r})),i=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,...i?{pinnedServerId:i}:{}};return s?[{...d,hasToken:!!a.hasToken||!!o}]:[{...d,clientToken:o,hasToken:!!o}]}).sort((n,a)=>a.lastUsedAt-n.lastUsedAt)},Aa=t=>{if(typeof window>"u")return;const s=Me(),n=t.slice(0,gi).map(a=>{const r={id:a.id,label:a.label,candidates:a.candidates.map(zs),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(o=>s.id&&o.id===s.id||As(o.candidates,s.candidates)),a=Me(),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(o=>o.id!==r.id&&!As(o.candidates,s.candidates))].slice(0,gi)},La=wc,Bc=0,Os=new Map,Ma=t=>`${Lc}token.${encodeURIComponent(t)}`,wi=async(t,s)=>{let n;const a=new Promise(r=>{n=window.setTimeout(()=>r(s),Rc)});try{return await Promise.race([t.catch(()=>s),a])}finally{n!==void 0&&window.clearTimeout(n)}},ki=async(t,s,n)=>Me()?wi(s().catch(a=>(console.warn(`[mobile-storage] ${t} failed`,a),n)),n):n,$c=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)},Us=async(t,s)=>{const n=s?.bypassCache?void 0:Os.get(t);if(typeof n=="string"&&n)return{status:"present",token:n};if(!Me())return{status:"absent"};const a=await wi(La.internalGetItem({prefixedKey:Ma(t),sync:!1}).then(o=>({kind:"ok",data:o?.data??null})).catch(o=>({kind:"error",error:o})),{kind:"timeout"});if(a.kind==="timeout")return console.warn("[mobile-storage] secure:read timed out"),{status:"failure"};if(a.kind==="error")return $c(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()?(Os.set(t,r),{status:"present",token:r}):{status:"absent"}},Ht=async(t,s)=>{if(!Me())return!1;const n=await ki("secure:write",async()=>(await La.internalSetItem({prefixedKey:Ma(t),data:s,sync:!1,access:Bc}),!0),!1);return n&&s.trim()?Os.set(t,s):Os.delete(t),n},Kc=async t=>{Os.delete(t),await ki("secure:delete",async()=>(await La.internalRemoveItem({prefixedKey:Ma(t),sync:!1}),!0),!1)},Ni=async(t,s)=>{let n=0,a=0;return{records:await Promise.all(t.map(async o=>{if(!o||typeof o!="object")return o;const c=o,i=typeof c.url=="string"?c.url:null,d=typeof c.clientToken=="string"?c.clientToken.trim():"";if(!i||!d)return o;if(!await s(i,d))return a+=1,o;n+=1;const{clientToken:h,...p}=c;return{...p,hasToken:!0}})),migrated:n,failed:a}},Ci=async()=>{if(typeof window>"u"||!Me())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 Ni(t,async(a,r)=>{const o=_t(a);if(!await Ht(o,r))return!1;const c=await Us(o,{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)}},Si=async()=>(await Ci(),Ot()),Fs=async t=>{const s=ji(Ot(),t);return Aa(s),Me()&&t.clientToken&&await Ht($e({candidates:t.candidates}),t.clientToken),s},Pi=async t=>{const s=Ot(),n=s.find(r=>r.id===t)??null,a=s.filter(r=>r.id!==t);return Aa(a),n&&Me()&&await Kc($e(n)),a},Ra=t=>{try{return JSON.stringify(t)}catch{return String(t)}},Ve=(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})},Vc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Hc=t=>{if(typeof t!="string")return t??void 0;try{return JSON.parse(t)}catch{return t}},Gc=async(t,s,n)=>{if(!Me())return null;const a=n?.timeoutMs??xi;try{const{CapacitorHttp:r}=await Yt(async()=>{const{CapacitorHttp:i}=await import("./vendor-boot-D-KEJjsM.js").then(d=>d.cr);return{CapacitorHttp:i}},__vite__mapDeps([0,1,2])),o=Object.fromEntries(new Headers(s?.headers).entries()),c=await r.request({url:t,method:s?.method||"GET",headers:o,data:Hc(s?.body),connectTimeout:a,readTimeout:a});return{ok:c.status>=200&&c.status<300,status:c.status,source:"native-http",json:async()=>Vc(c.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",Ra({url:t,error:r instanceof Error?r.message:String(r)})),null}},Wc=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(o=>{a=window.setTimeout(()=>{n?.(),o(null)},t)});try{return await Promise.race([s,r])}catch{return null}finally{a!==void 0&&window.clearTimeout(a)}},ts=async(t,s,n)=>{const a=n?.totalTimeoutMs??xi,r=Date.now(),o=Math.min(Mc,a),c=await zt(o,Gc(t,s,{timeoutMs:o}));if(c)return c;const i=new AbortController,d=Math.max(500,a-(Date.now()-r));return zt(d,Wc(t,{...s,signal:i.signal}),()=>i.abort())},Sn=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}},qc=async(t,s,n,a=gs,r)=>{if(r?.shouldAbort?.())return{outcome:"unreachable"};const o=Wr({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk}),c=i=>i==="ok"&&r?.keepTunnel?{outcome:i,tunnel:o}:(o.close(),{outcome:i});try{const i=s?{Authorization:`Bearer ${s}`}:void 0,d=await zt(a,o.fetch("/auth/session",{headers:i}).catch(()=>null));if(Ve("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 h=await Sn(d);return h&&h.disabled!==!0&&h.authenticated===!1?c(s?"auth-failed":"needs-login"):c("ok")}catch(i){throw o.close(),i}},Qc=(t,s,n,a,r)=>{const o=typeof window<"u"?window.location.origin:"",c={relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk,...n?{grant:n}:{}};r&&Fo(c,r),ja({apiBaseUrl:o,clientToken:s,runtimeKey:a??Ta(t),relay:c})},Ti=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:vi}:void 0,o=es({candidates:t})?.serverId??null,c=t.find(m=>m.kind==="relay")??null,i=t.filter(m=>m.kind==="direct"),d=typeof n?.pinnedServerId=="string"&&n.pinnedServerId.trim()?n.pinnedServerId.trim():null,h=async()=>{let m=!1,u=null;for(const f of i){if(a?.())return{status:"unreachable"};const v=ns(f.url)||f.url,g=await ts(`${v}/health`,{method:"GET"},r);if(a?.())return{status:"unreachable"};if(!g?.ok)continue;const b=await Ti(g);if(d){if(b&&b!==d){Ve("probe:server-id-mismatch",{url:v}),m=!0;continue}}else b&&!u&&(u=b);if(o&&b&&b!==o){Ve("probe:server-id-mismatch",{url:v});continue}const w=s?{Authorization:`Bearer ${s}`}:void 0,k=await ts(`${v}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:w},r);if(a?.())return{status:"unreachable"};if(k?.status===401)return{status:"needs-login"};if(!k||!k.ok&&k.status!==404)continue;const N=await Sn(k);if(N&&N.disabled!==!0&&N.authenticated===!1)return{status:"needs-login"};const A=N?.disabled===!0;return!s&&Me()&&!A&&N?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:v,...b?{serverId:b}:{}},...u?{serverId:u}:{}}}return m?{status:"unreachable",reason:"wrong-server"}:{status:"unreachable"}},p=async()=>{if(!c)return{status:"unreachable"};if(a?.())return{status:"unreachable"};const{outcome:m,tunnel:u}=await qc(c.relay,s,void 0,n?.fast?bi:void 0,{keepTunnel:!0,...a?{shouldAbort:a}:{}});return a?.()?(u?.close(),{status:"unreachable"}):m==="ok"?{status:"ok",transport:{kind:"relay",relay:c.relay,tunnel:u}}:m==="needs-login"||m==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return c?i.length===0?p():new Promise(m=>{let u=!1,f=!1,v,g=null,b=null;const w=A=>{A?.status==="ok"&&A.transport.kind==="relay"&&A.transport.tunnel?.close()},k=A=>{u||(u=!0,m(A))},N=()=>{f||u||a?.()||(v!==void 0&&(window.clearTimeout(v),v=void 0),p().then(A=>{if(b=A,u||f){w(A);return}if(A.status==="ok"||A.status==="needs-login"){k(A);return}g&&k(g)}))};h().then(A=>{if(g=A,!u){if(A.status==="ok"||A.status==="needs-login"){f=!0,v!==void 0&&window.clearTimeout(v),w(b),k(A);return}if(b){k(b);return}N()}}),v=window.setTimeout(N,Dc)}):h()},Wt=(t,s,n)=>{t.kind==="relay"?Qc(t.relay,s,n?.grant,n?.runtimeKey,t.tunnel):ja({apiBaseUrl:t.url,clientToken:s,runtimeKey:n?.runtimeKey}),Ri()},Jc=()=>{const t=Ot()[0];return t?.label?.trim()?t.label:null},Yc=async()=>{const t=Ls(),s=`${qe()}|${ht()}`,n=()=>Ls()!==t||`${qe()}|${ht()}`!==s;if(await Ci(),n())return{status:"no-candidate"};const a=Ot()[0];if(!a)return{status:"no-candidate"};let r;if(Me()){if(!a.hasToken)return{status:"no-candidate"};const c=await Us($e(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 o=await hn(a.candidates,r,{fast:!0,pinnedServerId:a.pinnedServerId});return n()?(ua(o),{status:"no-candidate"}):o.status==="needs-login"?{status:"needs-login",label:a.label}:o.status!=="ok"?{status:"unreachable",label:a.label}:(await Fs({id:a.id,label:a.label,candidates:a.candidates,...!a.pinnedServerId&&o.serverId?{pinnedServerId:o.serverId}:{}}),n()?(fn(o.transport),{status:"no-candidate"}):(Wt(o.transport,r,{runtimeKey:$e(a)}),{status:"connected"}))},Ii=async(t,s)=>{let n="";try{n=ns(t.url)}catch{return!1}if(!n)return!1;const a=t.clientToken?.trim()||void 0,r=a?{Authorization:`Bearer ${a}`}:void 0,o=s?.fast?{totalTimeoutMs:vi}:void 0;if(!(await ts(`${n}/health`,{method:"GET",headers:r},o))?.ok)return!1;const i=await ts(`${n}/auth/session`,{method:"GET",credentials:a?"omit":"include",headers:r},o);if(!i||!i.ok&&i.status!==404)return!1;const d=await Sn(i);return!(d&&d.disabled!==!0&&d.authenticated===!1)},cr=async(t,s)=>{const n=es({candidates:t})?.serverId??null,a=typeof s=="string"&&s.trim()?s.trim():null;for(const r of t){if(r.kind==="relay"){const d=Wr(r.relay),h=await zt(gs,d.fetch("/health").catch(()=>null));if(Ve("establish:relay:health",{ok:h?.ok===!0,status:h?.status??null}),h?.ok)return{kind:"relay",relay:r.relay,tunnel:d};d.close();continue}const o=ns(r.url)||r.url,c=await ts(`${o}/health`,{method:"GET"});if(Ve("establish:direct:health",{ok:c?.ok===!0,status:c?.status??null}),!c?.ok)continue;const i=await Ti(c);if(a&&i&&i!==a){Ve("establish:server-id-mismatch",{url:o});continue}if(n&&i&&i!==n){Ve("establish:server-id-mismatch",{url:o});continue}return{kind:"direct",url:o,...i?{serverId:i}:{}}}return null},Xc=t=>[...t].sort((s,n)=>{const a=(s.priority??100)-(n.priority??100);if(a!==0)return a;const r=o=>o.type==="relay"?2:o.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)}),Ei=async(t,s)=>{if(!ms())return Ii(t,s);const n=await zt(s?.fast?bi:gs,Ee("/auth/session").then(r=>r).catch(()=>null));if(!n||!n.ok&&n.status!==404)return!1;const a=await Sn(n);return!(a&&a.disabled!==!0&&a.authenticated===!1)},Zc=t=>t.kind==="relay"?ms():!ms()&&Pa(t.url,ht()),Pn=()=>{const t=qe();return t?Ot().find(s=>$e(s)===t)??null:null},an=t=>{const s=qe();return!!s&&$e(t)===s},Da=t=>({generation:Ls(),runtimeKey:qe(),apiBaseUrl:ht(),connectionId:t.id,secureKey:$e(t),candidatesJson:JSON.stringify(t.candidates.map(zs))}),Ai=t=>{if(Ls()!==t.generation||qe()!==t.runtimeKey||ht()!==t.apiBaseUrl)return!0;const s=Pn();if(!s||s.id!==t.connectionId||$e(s)!==t.secureKey)return!0;try{if(JSON.stringify(s.candidates.map(zs))!==t.candidatesJson)return!0}catch{return!0}return!1},fn=t=>{try{t?.kind==="relay"&&t.tunnel?.close()}catch{}},ua=t=>{t.status==="ok"&&fn(t.transport)},ed=t=>t?`${t.generation}|${t.runtimeKey}|${t.apiBaseUrl}|${t.connectionId}|${t.secureKey}|${t.candidatesJson}`:`noselection|${Ls()}|${qe()}`;let qt=null,pa="";const dr=(t,s)=>{const n=s.finally(()=>{qt===n&&(qt=null,pa="")});return qt=n,pa=t,n},Qn=async()=>{const t=await td();return Gr("reprobe",{code:t}),t},Li=()=>{const t=Pn(),s=t?Da(t):null,n=ed(s);if(qt&&pa===n)return qt;if(qt){const r=qt.then(()=>Qn(),()=>Qn());return dr(n,r)}return dr(n,Qn())},td=async()=>{const t=Pn();if(!t)return"no-connection";const s=Da(t),n=()=>Ai(s);let a;if(Me()){if(t.hasToken){const h=await Us($e(t));if(h.status==="present")a=h.token;else return n()?"no-connection":h.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(h=>Zc(h.kind==="relay"?{kind:"relay",relay:h.relay}:{kind:"direct",url:h.url})),o=r>=0?t.candidates.slice(0,r):t.candidates,c=await hn(o,a,{fast:!0,shouldAbort:n,pinnedServerId:t.pinnedServerId});if(n())return ua(c),"no-connection";if(c.status==="ok")return await Fs({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&c.serverId?{pinnedServerId:c.serverId}:{}}),n()?(fn(c.transport),"no-connection"):(Wt(c.transport,a,{runtimeKey:$e(t)}),"switched");if(c.status==="needs-login")return"needs-login";if(r>=0){if(n())return"no-connection";const h=await Ei({url:s.apiBaseUrl,clientToken:a},{fast:!0});if(n())return"no-connection";if(h)return Ri(),"unchanged"}const i=r>=0?t.candidates.slice(r+1):[];if(i.length===0)return"unreachable";const d=await hn(i,a,{fast:!0,shouldAbort:n,pinnedServerId:t.pinnedServerId});return n()?(ua(d),"no-connection"):d.status==="ok"?(await Fs({id:t.id,label:t.label,candidates:t.candidates,...!t.pinnedServerId&&d.serverId?{pinnedServerId:d.serverId}:{}}),n()?(fn(d.transport),"no-connection"):(Wt(d.transport,a,{runtimeKey:$e(t)}),"switched")):d.status==="needs-login"?"needs-login":"unreachable"};let Jn=!1;const Mi=async()=>{if(Jn)return"skipped";const t=Pn();if(!t)return Ve("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const s=es(t);if(!s)return Ve("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const n=Da(t),a=()=>Ai(n);Jn=!0;try{const r=await zt(gs,Ee("/api/client-auth/connection/candidates").then(u=>u).catch(()=>null));if(!r?.ok)return Ve("candidates:refresh-skip",{reason:"fetch-failed",status:r?.status??null}),"skipped";if(a())return Ve("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const o=await r.json().catch(()=>null);if(!o||o.serverId!==s.serverId)return Ve("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const c=Array.isArray(o.candidates)?o.candidates:[],i=[],d=[];for(const u of c){if(!u||typeof u!="object")continue;const f=u;if(!(f.type!=="lan"&&f.type!=="tailscale"||typeof f.url!="string"))try{const v=ns(f.url),g=f.type==="tailscale"?d:i;v&&!g.includes(v)&&g.push(v)}catch{}}if(i.length===0&&d.length===0)return Ve("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const h=_s(t).filter(u=>u.url.startsWith("https://")),p=[...i.map(u=>({kind:"direct",url:u})),...d.filter(u=>!i.includes(u)).map(u=>({kind:"direct",url:u})),...h.filter(u=>![...i,...d].includes(u.url)),{kind:"relay",relay:s}];return JSON.stringify(t.candidates.map(zs))===JSON.stringify(p.map(zs))?"unchanged":a()?(Ve("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(Ve("candidates:refreshed",{lanCount:i.length}),await Fs({id:t.id,label:t.label,candidates:p}),"updated")}finally{Jn=!1}},Ri=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const t=await Mi().catch(()=>"skipped");Ve("candidates:refresh-result",{result:t}),t==="updated"&&ms()&&await Li().catch(()=>null)})()},_c)},Di=t=>{const[s,n]=l.useState(()=>Ot()),[a,r]=l.useState(null),[o,c]=l.useState(null),[i,d]=l.useState(null),h=l.useRef(s),p=l.useRef(null),m=l.useRef(yi()),u=l.useCallback(x=>{h.current=x,n(x)},[]),f=l.useCallback(x=>{p.current=x,r(x)},[]),v=l.useCallback(x=>{p.current===x&&(p.current=null,r(null))},[]);l.useEffect(()=>{let x=!1;return Si().then(P=>{x||u(P)}),()=>{x=!0}},[u]);const g=l.useCallback(x=>{const P=ji(h.current,x);return u(P),Aa(P),P},[u]),b=l.useCallback(async x=>{c(null),f("connect");try{const P=lr(x);if(P.length===0){c("Enter a server URL.");return}const C=x.id?h.current.find(_=>_.id===x.id):h.current.find(_=>As(_.candidates,P)),y=x.label?.trim()||C?.label||Es(Xt({candidates:P})),L=x.relayGrant;let I=x.clientToken?.trim()||void 0;const T=!!I;if(!I)if(Me()){if(C?.hasToken){const _=await Us($e({candidates:P}));if(_.status==="present")I=_.token;else if(_.status==="failure"){c("Could not read saved credentials. Please try again.");return}}}else I=C?.clientToken;Ve("connect:start",{candidates:P.map(_=>_.kind),hasToken:!!I});const E=await hn(P,I,{pinnedServerId:C?.pinnedServerId});if(Ve("connect:probe",{status:E.status}),E.status==="unreachable"){E.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(E.status==="needs-login"){g({id:C?.id,label:y,candidates:P}),d({id:C?.id??ln(),label:y,candidates:P,relay:es({candidates:P})??void 0,relayGrant:L,...C?.pinnedServerId?{pinnedServerId:C.pinnedServerId}:{}});return}const U=!C?.pinnedServerId&&E.serverId?E.serverId:void 0;I&&T&&Me()&&await Ht($e({candidates:P}),I),g({id:C?.id,label:y,candidates:P,clientToken:I,...U?{pinnedServerId:U}:{}}),Wt(E.transport,I??null,{runtimeKey:$e({candidates:P}),grant:L}),t()}catch(P){console.warn("[mobile-connect] connect threw",P),c("That server URL is not valid.")}finally{v("connect")}},[f,v,t,g]),w=l.useCallback(async x=>{if(p.current==="pairing")return;c(null),f("pairing");const P=Xc(x.candidates),C=h.current.find(I=>As(I.candidates,P));let y=null,L=!1;try{if(y=await cr(P,C?.pinnedServerId),!y){c("Could not reach that PiChamber server.");return}const I=JSON.stringify({pairingId:x.pairingId,secret:x.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},E=y.kind==="relay"?await zt(gs,y.tunnel.fetch("/api/client-auth/pairing/redeem",T).catch(()=>null)):await ts(`${y.url}/api/client-auth/pairing/redeem`,T);if(!E?.ok){c("This server needs a password or client token.");return}const U=await E.json().catch(()=>null),_=typeof U?.clientToken=="string"?U.clientToken.trim():"";if(!_){c("This server needs a password or client token.");return}const O=typeof U?.server?.label=="string"?U.server.label:"",V=x.label||O||Es(Xt({candidates:P}));if(Me()&&!await Ht($e({candidates:P}),_)){c("This server needs a password or client token.");return}g({id:C?.id,label:V,candidates:P,clientToken:_,...!C?.pinnedServerId&&y.kind==="direct"&&y.serverId?{pinnedServerId:y.serverId}:{}}),Wt(y.kind==="relay"?{kind:"relay",relay:y.relay,tunnel:y.tunnel}:{kind:"direct",url:y.url},_,{runtimeKey:$e({candidates:P})}),L=y.kind==="relay",t()}catch(I){console.warn("[mobile-connect] pairing threw",I),c("This server needs a password or client token.")}finally{!L&&y?.kind==="relay"&&y.tunnel.close(),v("pairing")}},[f,v,t,g]),k=l.useCallback(async x=>{if(!i||!x.trim()||p.current==="password")return;c(null),f("password");const P=m.current.begin(),C=()=>m.current.isCurrent(P),{id:y,label:L,candidates:I}=i,T=i.pinnedServerId;let E=null,U=!1;try{if(E=await cr(I,T),!C())return;if(!E){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:x,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:or(),dedupeKey:ir()})};Ve("password:start",{transport:E.kind});const O=E.kind==="relay"?await zt(gs,E.tunnel.fetch("/auth/session",_).catch(()=>null)):await ts(`${E.url}/auth/session`,_);if(!C())return;if(Ve("password:done",{ok:O?.ok===!0,status:O?.status??null}),!O?.ok){c("Could not unlock that server. Check the password.");return}const V=await O.json().catch(()=>null);if(!C())return;const H=typeof V?.clientToken=="string"?V.clientToken.trim():"";if(Ve("password:token",{issued:!!H}),!H){if(E.kind==="direct"&&!Me()){g({id:y,label:L,candidates:I}),d(null),Wt({kind:"direct",url:E.url},null,{runtimeKey:$e({candidates:I})}),t();return}c("This server needs a password or client token.");return}if(Me()&&(!C()||(await Ht($e({candidates:I}),H),!C()))||!C()||(g({id:y,label:L,candidates:I,clientToken:H,...!T&&E.kind==="direct"&&E.serverId?{pinnedServerId:E.serverId}:{}}),d(null),Wt(E.kind==="relay"?{kind:"relay",relay:E.relay,tunnel:E.tunnel}:{kind:"direct",url:E.url},H,{runtimeKey:$e({candidates:I})}),U=E.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{!U&&E?.kind==="relay"&&E.tunnel.close(),C()&&v("password")}},[f,v,t,i,g]),N=l.useCallback(()=>{m.current.cancel(),v("password"),d(null),c(null)},[v]),A=l.useCallback(async x=>{c(null);let P=lr(x);const C=x.id?h.current.find(O=>O.id===x.id)??null:null;if(C){const O=P.filter(ne=>ne.kind==="direct"),V=_s(C).filter(ne=>ne.url.startsWith("https://")&&!O.some(X=>Pa(X.url,ne.url))),H=es(C);P=[...O,...V,...H?[{kind:"relay",relay:H}]:[]]}if(P.length===0)return c("Enter a server URL."),null;const y=new Set((C?_s(C):[]).map(O=>_t(O.url))),L=new Set(P.filter(O=>O.kind==="direct").map(O=>_t(O.url))),I=y.size!==L.size||[...L].some(O=>!y.has(O)),T=C&&!I?void 0:null,E=x.clientToken?.trim()||void 0,U=x.label?.trim()||Es(Xt({candidates:P}));if(Me()){const O=$e({candidates:P});if(E)await Ht(O,E);else if(C?.hasToken){const V=$e(C);if(V&&O&&V!==O){const H=await Us(V);H.status==="present"&&await Ht(O,H.token)}}}return g({id:x.id,label:U,candidates:P,clientToken:E,pinnedServerId:T}).find(O=>As(O.candidates,P))??null},[g]),j=l.useCallback(async x=>{const P=h.current.find(y=>y.id===x)??null,C=await Pi(x);return u(C),P},[u]);return{connections:s,isBusy:a!==null,isPasswordBusy:a==="password",error:o,pendingConnection:i,connect:b,redeemPairingConnection:w,submitPassword:k,cancelPassword:N,saveConnection:A,removeConnection:j,setError:c}},sd=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:Yc,connectionDisplayUrl:Xt,createMobilePasswordOperationTracker:yi,deleteMobileConnection:Pi,getAutoConnectTargetLabel:Jc,getConnectionLabel:Es,isActiveRuntimeConnection:an,isSameConnectionUrl:Pa,loadMobileConnections:Si,migrateLegacyInlineTokenRecords:Ni,normalizeConnectionUrl:ns,refreshActiveConnectionCandidates:Mi,relayConnectionRuntimeKey:Ta,reprobeActiveConnection:Li,upsertMobileConnection:Fs,useMobileConnection:Di,validateActiveRuntimeSession:Ei,validateMobileConnectionSession:Ii},Symbol.toStringTag,{value:"Module"})),_i=()=>{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",Oi=t=>{const s=t.trim();if(!s)return null;if(/^pichamber:\/\//i.test(s)){const n=Bo(s);return n?{pairing:n}:null}return/^https?:\/\//i.test(s)?{url:s}:null},Ui=(t,s)=>{const n=Oi(t);if(!n&&s?.pairingStringFallback){const a=$o(t);if(a)return{status:"pairing",pairing:a}}return n?"pairing"in n?{status:"pairing",...n}:{status:"ok",...n}:{status:"invalid"}},nd=async(t,s)=>{if(!t.startScan||!t.stopScan||!t.addListener)return{status:"unsupported"};if(s?.aborted)return{status:"cancelled"};let n,a,r=!1,o=()=>{};const c=new Promise(h=>{o=h}),i=h=>{r||(r=!0,o(h))},d=()=>i({status:"cancelled"});s?.addEventListener("abort",d,{once:!0});try{return(await Promise.allSettled([Promise.resolve(t.addListener("barcodesScanned",({barcodes:p})=>{const m=p?.[0],u=(m?.rawValue??m?.displayValue??"").trim();u&&i(Ui(u,{pairingStringFallback:!0}))})).then(p=>{n=p}),Promise.resolve(t.addListener("scanError",()=>i({status:"failed"}))).then(p=>{a=p})])).some(({status:p})=>p==="rejected")?i({status:"failed"}):r||t.startScan({formats:["QR_CODE"]}).catch(()=>i({status:"failed"})),await c}finally{s?.removeEventListener("abort",d),await Promise.allSettled([Promise.resolve(n?.remove()),Promise.resolve(a?.remove()),t.stopScan()]),await Fi()}},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}`},ad=()=>typeof window>"u"||typeof window.getComputedStyle!="function"?null:ur(window.getComputedStyle(document.documentElement).backgroundColor)??(document.body?ur(window.getComputedStyle(document.body).backgroundColor):null),Fi=async()=>{if(!zi())return;const t=ad();if(!t)return;const{setNativeWebViewBackground:s}=await Yt(()=>import("./nativeFileSave-DSMsJqXM.js"),__vite__mapDeps([3,0,1,2,4,5,6,7,8,9])).catch(()=>({setNativeWebViewBackground:void 0}));await s?.(t)},rd=()=>_i()!==null,id=async t=>{const s=_i();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 nd(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?Ui(r):{status:"cancelled"}}catch{return{status:"failed"}}},od=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}},ld=(t,s)=>{const n=od(s.status),a=Sl(n,s.probing===!0),r=[];for(const i of t.candidates){if(i.kind==="relay"){r.some(h=>h.kind==="relay")||r.push({kind:"relay",label:tr.relay,address:null});continue}const d=Pl(i.url);r.some(h=>h.kind===d)||r.push({kind:d,label:tr[d],address:i.url})}let o=null;s.isCurrent&&s.status.kind==="connected"&&(o=s.status.transport==="relay"?r.find(i=>i.kind==="relay")??null:r.find(i=>i.kind!=="relay")??null);const c=r.some(i=>i.kind!=="relay");return{id:t.id,label:t.label,isCurrent:s.isCurrent,isDefault:!1,isLocal:!1,routes:r,activeRoute:o,status:a.status,latencyMs:s.status.kind==="connected"?s.status.latencyMs??null:a.latencyMs,canEdit:c,canRemove:!0,canOpenInNewWindow:!1}},Yn={autoComplete:"off",autoCorrect:"off",spellCheck:!1},cd="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",dd=({onCancel:t})=>{const s=l.useRef(null);return Xr(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,o=i=>{!(i instanceof HTMLElement)||i===s.current||r.has(i)||(r.set(i,{opacity:i.style.opacity,pointerEvents:i.style.pointerEvents}),i.style.setProperty("opacity","0"),i.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(o);const c=new MutationObserver(i=>{i.forEach(d=>d.addedNodes.forEach(o))});return c.observe(document.body,{childList:!0}),()=>{c.disconnect(),r.forEach((i,d)=>{d.style.opacity=i.opacity,d.style.pointerEvents=i.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"),Fi()}},[]),l.useEffect(()=>{const n=()=>{document.visibilityState==="hidden"&&t()};return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[t]),Hr.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(R,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},ud=()=>Hr.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(Zr,{width:96,height:96,isAnimated:!0}),e.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[e.jsx(R,{name:"loader-4",className:"size-[18px] animate-spin"}),e.jsx("span",{children:"Connecting..."})]})]}),document.body),pd=({className:t})=>{const[s,n]=l.useState(null);l.useEffect(()=>{let r=!1;const o=typeof AbortController<"u"?new AbortController:void 0;return(async()=>{try{const i=await Ee("/api/system/info",{signal:o?.signal,headers:{Accept:"application/json"}});if(!i.ok)return;const d=await i.json().catch(()=>null);if(!d||r)return;const h=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:h,tunnelUrl:p})}catch{}})(),()=>{r=!0,o?.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:F("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:()=>{us(r.url)},children:[e.jsx(R,{name:"external-link",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"max-w-64 truncate font-mono typography-micro",children:r.url})]},r.key))})},Xn={stable:"Stable",rc:"Release candidate"},pr=({channel:t,disabled:s,label:n,onChange:a,className:r})=>e.jsxs(Re,{value:t,onValueChange:a,disabled:s,children:[e.jsx(De,{size:Be,className:F(hs,r),"aria-label":n,children:e.jsx(_e,{children:o=>Xn[cn(o)]})}),e.jsxs(ze,{children:[e.jsx(je,{value:"stable",children:Xn.stable}),e.jsx(je,{value:"rc",children:Xn.rc})]})]}),md=t=>{const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,c]=l.useState("stable"),[i,d]=l.useState(!1),[h,p]=l.useState(t),[m,u]=l.useState(!1),[f,v]=l.useState(null),g=l.useRef(0);l.useEffect(()=>yn(()=>{g.current+=1,n(k=>k+1)}),[]),l.useEffect(()=>{const k=++g.current;if(!t){p(!1),v(null);return}d(!1),p(!0),u(!1),(async()=>{try{const N=await Ee("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!N.ok)throw new Error("Unable to load the server update channel.");const A=await N.json().catch(()=>null);if(!A)throw new Error("Unable to load the server update channel.");g.current===k&&(c(cn(A.serverUpdateChannel)),d(!0),v(null))}catch(N){g.current===k&&v(N instanceof Error?N.message:"Unable to load the server update channel.")}finally{g.current===k&&p(!1)}})()},[t,s,a]);const b=l.useCallback(()=>r(k=>k+1),[]),w=l.useCallback(k=>{const N=cn(k),A=o,j=++g.current;c(N),u(!0),v(null),(async()=>{try{await Ke({serverUpdateChannel:N},{immediate:!0});const x=await Ee("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!x.ok)throw new Error("Unable to save the server update channel.");if((await x.json().catch(()=>null))?.serverUpdateChannel!==N)throw new Error("Unable to save the server update channel.");g.current===j&&(pc(),Ms.getState().checkForUpdates())}catch(x){g.current===j&&(c(A),v(x instanceof Error?x.message:"Unable to save the server update channel."))}finally{g.current===j&&u(!1)}})()},[o]);return{channel:o,loaded:i,loading:h,saving:m,error:f,change:w,retry:b,runtimeEpoch:s}},hd="1.0.8-rc.2",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=ht().trim();return t?Qr(t):null},fd={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:Vo,save:Ko},gd={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()=>Il(hd),save:async t=>Tl(t)},xd=()=>{const t=Fe(),s=t&&ss(),n=l.useMemo(()=>t?fd:Me()?gd:null,[t]),a=!s,r=md(a),o=r.runtimeEpoch,[c,i]=l.useState(fr),[d,h]=l.useState("stable"),[p,m]=l.useState(n!==null),[u,f]=l.useState(!1),[v,g]=l.useState(null);if(l.useEffect(()=>{if(!a)return;const k=fr();if(i(k),!t)return;let N=!1;return qr().then(A=>{if(N)return;const j=qo(),x=Ho([Go(j),...A.hosts]),P=x.id===Wo||x.id==="custom"?"":x.label.trim();i(P?Qr(P):k)}).catch(()=>{N||i(k)}),()=>{N=!0}},[t,a,o]),l.useEffect(()=>{if(!n)return;let k=!1;return m(!0),n.load().then(N=>{k||(h(N),g(null))}).catch(N=>{k||g(N instanceof Error?N.message:`Unable to load the ${n.ariaLabel.toLowerCase()}.`)}).finally(()=>{k||m(!1)}),()=>{k=!0}},[n]),!n&&!a)return null;const b=k=>{if(!n)return;const N=cn(k),A=d;h(N),f(!0),g(null),n.save(N).then(j=>{h(j),Ms.getState().reset(),Ms.getState().checkForUpdates()}).catch(j=>{h(A),g(j instanceof Error?j.message:`Unable to save the ${n.ariaLabel.toLowerCase()}.`)}).finally(()=>f(!1))},w=c?`Server update channel (${c})`:"Server update channel";return e.jsxs(q,{title:"Updates",children:[n?e.jsx(Ie,{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(Ie,{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:w,onChange:r.change})}):null]})},Bi="https://github.com/RyderAsKing/PiChamber",$i="https://pi.dev/",vd=800,Ki=({initialUpdateDialogOpen:t=!1})=>{const[s,n]=l.useState(t?"client":null),[a,r]=l.useState(!1),[o,c]=l.useState(null),i=Ms(Uo(x=>({info:x.info,serverInfo:x.serverInfo,checking:x.checking,available:x.available,error:x.error,lastChecked:x.lastChecked,downloading:x.downloading,downloaded:x.downloaded,progress:x.progress,runtimeType:x.runtimeType,checkForUpdates:x.checkForUpdates,downloadUpdate:x.downloadUpdate,restartToUpdate:x.restartToUpdate}))),d=Qo()&&!ss(),h=l.useMemo(()=>Me(),[]),p=d||h,m=o||i.info?.currentVersion||"unknown",u=i.info?.currentVersion||"1.0.8-rc.2",f=i.serverInfo?.currentVersion||o||"unknown",v=i.available,g=p&&(i.serverInfo?.available??!1),b=v||g,w=s==="server"?i.serverInfo:i.info,k=s==="server"?"web":i.runtimeType;l.useEffect(()=>{let x=!1;return(async()=>{try{const C=await Ee("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!C.ok)return;const y=await C.json().catch(()=>null),L=typeof y?.pichamberVersion=="string"&&y.pichamberVersion.trim().length>0?y.pichamberVersion.trim():null;x||c(L)}catch{x||c(null)}})(),()=>{x=!0}},[]);const N=l.useRef(!1);l.useEffect(()=>{if(i.checking)r(!0),N.current=!0;else if(a){const x=setTimeout(()=>{if(r(!1),N.current){const{info:P,serverInfo:C}=Ms.getState(),y=P!==null&&(!p||C!==null);!b&&!i.error&&y&&B.success("You are on the latest version"),N.current=!1}},vd);return()=>clearTimeout(x)}},[i.checking,a,b,i.error,p]);const A=i.checking||a;let j=null;return A?j=e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(R,{name:"loader",className:"size-3.5 animate-spin","aria-hidden":"true"}),"Checking..."]}):p&&b?j=e.jsx("span",{className:"text-[var(--primary-base)]",children:"Updates available"}):b||(i.info!==null&&(!p||i.serverInfo!==null)&&!i.error?j=e.jsx("span",{children:"Up to date"}):(i.error||i.lastChecked!==null)&&(j=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:i.info,onOpen:()=>n("client")}),e.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"·"}),e.jsx(gr,{label:"Server",version:f,updateInfo:i.serverInfo,onOpen:()=>n("server")})]}):e.jsx("span",{className:"font-mono",children:m}),j?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"·"}),j]}):null]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-2 @xl:flex-row @xl:items-center",children:[!A&&!p&&i.available&&e.jsxs(S,{size:"sm",variant:"default",onClick:()=>n("client"),children:[e.jsx(R,{name:"download",className:"h-4 w-4 mr-1"}),`Update to ${i.info?.version||""}`]}),e.jsx(S,{size:"sm",variant:"outline",onClick:()=>i.checkForUpdates(),disabled:A,children:"Check for updates"})]})]}),i.error&&e.jsx("div",{className:"px-3 py-2 border-b border-border/40",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:i.error})}),e.jsxs("div",{className:"flex flex-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(pd,{className:"min-w-0 justify-end"})]}),e.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[e.jsxs("a",{href:Bi,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground typography-meta transition-colors",children:[e.jsx(R,{name:"github-fill",className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:$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(R,{name:"information",className:"h-4 w-4"}),e.jsx("span",{children:"Pi Agent"})]})]})]}),e.jsx(mc,{open:s!==null,onOpenChange:x=>{x||n(null)},info:w,downloading:s==="client"&&i.downloading,downloaded:s==="client"&&i.downloaded,progress:s==="client"?i.progress:null,error:i.error,onDownload:i.downloadUpdate,onRestart:i.restartToUpdate,runtimeType:k})]}),e.jsx(xd,{}),e.jsx(bd,{})]})},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(R,{name:"arrow-up",className:"size-3.5","aria-hidden":"true"})]})},bd=()=>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:$i,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:Bi,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"})]})})]}),yd=({onResolved:t})=>{const[s,n]=l.useState(!1),[a,r]=l.useState(!1);l.useEffect(()=>{let c=!0;return Ue.getSettings({runtimeKey:qe()}).then(i=>{c&&n(i.pi.project.requiresTrust===!0)}).catch(()=>{}),()=>{c=!1}},[]);const o=async c=>{r(!0);try{const i=await Ue.setPiSettings({scope:"project",trust:c},{runtimeKey:qe()});n(!1),jn(i)&&B.info(Qt("Project trust")),t?.()}catch(i){const d=i instanceof Error&&i.message?i.message:"Failed to update project trust";wn(i)?B.info(Jt("Project trust")):B.error(d)}finally{r(!1)}};return e.jsx(gt,{open:s,onOpenChange:()=>{},children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Trust this project?"}),e.jsx(yt,{children:"This project contains Pi settings, skills, prompts, or extensions. Trusting it allows Pi to load those project resources."})]}),e.jsxs(vs,{children:[e.jsx(S,{variant:"ghost",size:"sm",disabled:a,onClick:()=>{o(!1)},children:"Keep untrusted"}),e.jsx(S,{size:"sm",disabled:a,onClick:()=>{o(!0)},children:"Trust project"})]})]})})},ye=({children:t,className:s,outerClassName:n,title:a,titleAbove:r,titleLeading:o,titleAccessory:c,description:i,headerEnd:d})=>{const h=a!=null||i!=null||d!=null,p=typeof a=="string"||typeof a=="number",m=o!=null||c!=null;return e.jsx(El,{useScrollShadow:!0,scrollShadowSize:16,outerClassName:F("h-full",n),className:"w-full @container",children:e.jsxs("div",{className:F("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:[h&&e.jsxs("div",{className:"mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-3 pb-6",children:[a!=null||i!=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?m?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o,e.jsx("h1",{className:F(da,"min-w-0 truncate"),children:a}),e.jsx("span",{className:"shrink-0",children:c})]}):e.jsx("h1",{className:da,children:a}):a:null,i!=null?typeof i=="string"||typeof i=="number"?e.jsx("p",{className:Ks,children:i}):i: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]})})},Tn=({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:o="Snippet content",settingsItem:c,minHeight:i=220,hideExpandsNote:d=!1,triggerPreview:h,triggerActionLabel:p="Expands as",variableChips:m})=>{const[u,f]=l.useState(()=>n?"preview":a),v=t.trim().length>0;l.useEffect(()=>{n&&u==="write"&&f("preview")},[n,u,v]);const g=u==="write"&&!n,b=l.useRef(null),w=l.useCallback(k=>{const N=b.current?.selectionStart??t.length,A=b.current?.selectionEnd??t.length;s(t.slice(0,N)+k+t.slice(A)),requestAnimationFrame(()=>{const j=b.current;if(!j)return;j.focus();const x=N+k.length;j.setSelectionRange(x,x)})},[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:()=>f("preview"),children:[e.jsx(R,{name:"eye",className:"size-3.5","aria-hidden":!0}),"Preview"]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":u==="write",disabled:n,onClick:()=>f("write"),className:F(n&&"opacity-50"),children:[e.jsx(R,{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]}),g?e.jsxs("div",{className:"p-0",children:[m&&m.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"}),m.map(k=>e.jsx(S,{variant:"chip",size:"xs",onClick:()=>w(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:F("min-h-[220px] w-full bg-transparent px-3 py-3 font-mono typography-meta leading-6","placeholder:text-subtle-foreground"),style:{minHeight:i},"aria-label":o})]}):e.jsx("div",{className:"min-h-[220px] px-4 py-4 @xl:px-6",style:{minHeight:i},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(R,{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&&h?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(R,{name:"information",className:"size-3.5 shrink-0 opacity-60","aria-hidden":!0}),p," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-[11px]",children:h})," in the composer"]}):e.jsx("span",{}),e.jsxs("span",{className:"tabular-nums",children:[t.length," chars"]})]})]})},jd=()=>{const{isMobile:t}=lt(),[s,n]=l.useState(null),[a,r]=l.useState({}),[o,c]=l.useState(null),[i,d]=l.useState(!1),h=l.useCallback(async()=>{const m=await Ue.listResources({runtimeKey:qe()});n(m.agents),r(Object.fromEntries(m.agents.map(u=>[u.id,u.content??""]))),d(!1)},[]);l.useEffect(()=>{h().catch(()=>d(!0))},[h]);const p=async m=>{c(m.id);try{const u=await Ue.updateResource({resourceId:m.id,content:a[m.id]??""},{runtimeKey:qe()});n(u.agents),r(Object.fromEntries(u.agents.map(f=>[f.id,f.content??""]))),jn(u)?B.info(Qt("Behavior")):B.success("Behavior saved successfully")}catch(u){wn(u)?B.info(Jt("Behavior")):B.error("Failed to save behavior")}finally{c(null)}};return e.jsxs(e.Fragment,{children:[e.jsx(yd,{onResolved:()=>{h().catch(()=>d(!0))}}),e.jsxs(ye,{title:t?void 0:"Behavior",description:t?void 0:"Guide how the agent responds.",children:[i?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,(s??[]).map((m,u)=>{const f=a[m.id]??"",v=m.location==="global"?"Global AGENTS.md":`Project ${m.name}`,g=m.editable===!0,b=f!==(m.content??"");return e.jsxs(q,{title:v,divider:u>0,settingsItem:m.location==="global"?"behavior.global-agents":"behavior.project-agents",contentClassName:"space-y-3",info:g?"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(Tn,{value:f,onChange:w=>r(k=>({...k,[m.id]:w})),readOnly:!g,placeholder:g?"Describe how the agent should behave. Use markdown for structure.":void 0,settingsItem:m.location==="global"?"behavior.global-agents":"behavior.project-agents",hideExpandsNote:!0,minHeight:260}),g?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(m)},disabled:o!==null||!b,children:o===m.id?"Saving...":"Save changes"})]}):null]},m.id)})]})]})},wd=({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:F("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:F("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})]})]})},kd=({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))}),Nd=()=>{const{isMobile:t}=lt(),s=Vt(C=>C.selectedSkillName),n=Vt(C=>C.setSelectedSkill),a=Vt(C=>C.skills),r=Vt(C=>C.isLoading),o=Vt(C=>C.loadSkills),[c,i]=l.useState(""),[d,h]=l.useState("all"),[p,m]=l.useState(!1),u=l.useMemo(()=>a.find(C=>C.name===s)??null,[a,s]),f=Vt(C=>C.updateSkillContent),[v,g]=l.useState(!1),[b,w]=l.useState(""),[k,N]=l.useState(!1);l.useEffect(()=>{u&&w(u.content??""),g(!1)},[u?.id,u?.content]);const A=l.useCallback(async()=>{if(!p){m(!0);try{const{invalidateSkillsLoadCache:C}=await Yt(async()=>{const{invalidateSkillsLoadCache:y}=await import("./useAppFontEffects-CV5UyTRw.js").then(L=>L.eX);return{invalidateSkillsLoadCache:y}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));C(),await o()}finally{m(!1)}}},[o,p]);l.useEffect(()=>{o()},[o]);const j=l.useMemo(()=>[...a].sort((C,y)=>{if(C.location!==y.location){if(C.location==="project")return-1;if(y.location==="project")return 1;if(C.location==="global")return-1;if(y.location==="global")return 1}return C.name.localeCompare(y.name,void 0,{sensitivity:"base"})}),[a]),x=l.useMemo(()=>{let C=j;d!=="all"&&(C=C.filter(L=>L.location===d));const y=c.trim().toLowerCase();return y?C.filter(L=>{const I=L.name.toLowerCase(),T=(L.description??"").toLowerCase();return I.includes(y)||T.includes(y)}):C},[j,d,c]),P=l.useMemo(()=>{let C=0,y=0;for(const L of a)L.location==="project"?C+=1:L.location==="global"&&(y+=1);return{all:a.length,project:C,global:y}},[a]);if(u){const C=u.location==="project"?"Project":u.location==="global"?"Global":u.location,y=typeof u.content=="string"&&u.content.trim().length>0,L=u.editable===!0,I=b!==(u.content??""),T=async()=>{if(!L||k)return;N(!0);const U=await f(u.name,b);N(!1),U?(B.success("Skill saved"),g(!1)):B.error("Failed to save skill")},E=()=>{w(u.content??""),g(!1)};return e.jsx(e.Fragment,{children:e.jsxs(ye,{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(R,{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:()=>g(!0),children:[e.jsx(R,{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(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 font-medium text-muted-foreground",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-muted-foreground/60","aria-hidden":!0}),"Read-only"]})]}),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(Tn,{value:b,onChange:w,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:E,disabled:k,children:"Cancel"}),e.jsx(S,{size:"xs",onClick:()=>{T()},disabled:k||!I,children:k?"Saving...":"Save changes"})]})]}):y?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(R,{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:()=>g(!0),className:"mt-2",children:[e.jsx(R,{name:"edit",className:"size-3.5"}),"Add content"]}):null]}),L&&!v&&y?e.jsx("div",{className:"flex justify-end pt-3",children:e.jsxs(S,{variant:"outline",size:"xs",onClick:()=>g(!0),children:[e.jsx(R,{name:"edit",className:"size-3.5"}),"Edit"]})}):null]})]})})}return r&&a.length===0?e.jsx(e.Fragment,{children:e.jsx(ye,{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:()=>{A()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:F("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(kd,{count:6})})})})}):x.length===0&&c.trim()===""&&a.length===0?e.jsx(e.Fragment,{children:e.jsx(ye,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:c,onChange:C=>i(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:()=>i(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{A()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:F("size-4",p&&"animate-spin")})})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"book-open",className:"size-8 text-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(ye,{title:t?void 0:"Skills",description:t?void 0:"Browse skills discovered by Pi. Click a card to read its guide.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:c,onChange:C=>i(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:()=>i(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{A()},disabled:p,"aria-label":"Refresh skills",title:"Refresh skills",children:e.jsx(R,{name:"refresh",className:F("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:()=>h("all"),children:["All ",P.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="project",onClick:()=>h("project"),children:["Project ",P.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":d==="global",onClick:()=>h("global"),children:["Global ",P.global]})]}),x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:c.trim()?`No skills match “${c}”.`:`No ${d} skills.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{i(""),h("all")},children:"Clear filters"})]}):e.jsx("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:x.map(C=>e.jsx(wd,{skill:C,onSelect:n,showLocationPill:d==="all"},C.id))})]})})})},Cd=t=>{if(!t||typeof t!="object")return;const s=t.code;return typeof s=="string"?s:void 0},Sd=(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.`}},Bs=(t,s)=>{if(t.ok){Te("saved"),t.deferred&&B.info(Qt(s));return}if(Te("error"),wn(t.error)){B.info(Jt(s));return}B.error(Sd(Cd(t.error),s))},_a=(t,s,n)=>{if(!t.ok){Bs(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:F("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 Vi(){return e.jsx("span",{"aria-hidden":"true",className:"inline-flex shrink-0",children:e.jsx(Zr,{width:12,height:12})})}function Hi(){return e.jsxs(gn,{title:"Made for PiChamber and comes with it",children:[e.jsx(Vi,{}),"Native"]})}function za(){return e.jsxs(gn,{title:"Enhanced for PiChamber: adds features only PiChamber shows. It works in the terminal too.",children:[e.jsx(Vi,{}),"Enhanced"]})}const Pd=t=>{const s=t.trim();return s.startsWith("npm:")?s.slice(4).trim().match(/^(@?[^@]+(?:\/[^@]+)?)(?:@.+)?$/)?.[1]:void 0},Vs=t=>t.kind==="npm"?Pd(t.source)??t.name:void 0,Td={npm:"npm package",git:"Git package",local:"Local folder"},Gi=t=>[Td[t.kind],t.version?`v${t.version}`:null,t.pinned?"pinned":null].filter(Boolean).join(" · "),Wi=t=>{const s=new Map;for(const{config:n,view:a}of t)for(const r of n?.packages??[]){const o=Vs(r);if(!o)continue;const c=s.get(o);c&&!(r.scope==="project"&&c.pkg.scope!=="project")||s.set(o,{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("-")}},Id=(t,s)=>{const n=t.split("."),a=s.split(".");for(let r=0;r<Math.max(n.length,a.length);r+=1){const o=n[r],c=a[r];if(o===void 0)return-1;if(c===void 0)return 1;if(o===c)continue;const i=/^\d+$/.test(o),d=/^\d+$/.test(c);return i&&d?o.length!==c.length?o.length<c.length?-1:1:o<c?-1:1:i!==d?i?-1:1:o<c?-1:1}return 0},Ed=(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 o=(n.parts[r]??0)-(a.parts[r]??0);if(o!==0)return Math.sign(o)}return n.prerelease===a.prerelease?0:n.prerelease?a.prerelease?Id(n.prerelease,a.prerelease):-1:1},Oa=(t,s)=>{const n=Vs(t);if(!n||t.pinned||!t.installed||!t.version)return;const a=s[n];return a&&Ed(a,t.version)>0?a:void 0},vr=t=>t.toLowerCase().split(/[^a-z0-9]+/).filter(s=>s.length>=3),Ad=(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(o=>r.some(c=>c.startsWith(o)))})},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`,Qi=(t,s,n)=>t?.replaced?.find(a=>a.kind===s&&a.id===n),Ji=t=>t.by?`Not loaded: ${t.by.name} takes its place`:"Not loaded: another extension takes its place",Ld=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`},Md=t=>`Pi loads ${t.by?.name??"another extension"} instead. Both register ${Ld(t)}, and Pi keeps only one.`,Rd=(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},Dd=(t,s)=>{const n=new Map,a=new Map(t.extensions.map(r=>[r.id,r.name]));for(const r of t.replaced??[]){const o=r.kind==="plugin"?s[r.id]&&`the ${s[r.id]} plugin`:a.get(r.id)&&`Pi's ${a.get(r.id)}`;if(!o)continue;r.kind==="builtin"&&n.set(r.id,{text:Ji(r),warning:!0});const c=r.by?.id;c&&a.has(c)&&!n.has(c)&&n.set(c,{text:`Loaded in place of ${o}`,warning:!1})}return n};function xs(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 _d="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.",zd="These ship with Pi. Its llama.cpp provider is built in too, but PiChamber does not load it, so it is not listed.",Od={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"},Yi=(t,s)=>s==="project"?t.project?.enabled??t.global??!1:t.global??!1,Xi=(t,s)=>`${t.filter(n=>Yi(n,s)).length} of ${t.length} on`;function Zn({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:Xi(s,n)}):null]})}function Zi({item:t,view:s,directory:n,readOnly:a,notes:r}){const o=Je(u=>u.setGlobal),c=Je(u=>u.setProjectEnabled),i=Je(u=>u.pending[t.id]===!0),d=Yi(t,s),h=d?r.get(t.id):void 0;let p=null;a?p=e.jsx("span",{className:Pt,children:d?"On":"Off"}):s==="project"&&t.project&&n?p=e.jsx(ca,{checked:t.project.enabled,disabled:i,ariaLabel:`${t.name} in this project`,onChange:u=>{Te("saving"),c(t.id,u,n).then(f=>Bs(f,t.name))}}):s==="global"&&t.global!==void 0&&(p=e.jsx(ca,{checked:t.global,disabled:i,ariaLabel:t.name,onChange:u=>{Te("saving"),o(t.id,u).then(f=>Bs(f,t.name))}}));let m;return h?m=e.jsx("p",{className:F("line-clamp-2 text-pretty typography-meta",h.warning?"text-[var(--status-warning)]":"text-muted-foreground"),children:h.text}):s==="project"&&t.project&&t.scope!=="project"&&t.project.enabled!==t.project.inherited?m=t.project.enabled?"On in this project only":"Off in this project only":t.group==="builtin"?m=Od[t.name]:t.group==="settings"&&(m="Listed in Pi's settings"),e.jsx(Ge,{title:t.name,dimmed:!d,detail:m,trailing:p})}function ea({items:t,...s}){return e.jsx(rt,{children:t.map(n=>e.jsx(Zi,{item:n,...s},n.id))})}function Ud({pkg:t,items:s,onRemove:n,onOpenPackage:a,...r}){const{view:o,readOnly:c,directory:i}=r,d=Je(N=>N.pending[t.id]===!0),h=Je(N=>N.updatePackage),p=Ct(N=>N.latest),m=!c&&t.scope===(o==="project"?"project":"user"),u=m?Oa(t,p):void 0,[f,v]=l.useState(null),g=t.scope==="project"?"This project":o==="project"?"Global":null,b=[Gi(t),g,s.length>0?Xi(s,o):null].filter(Boolean).join(" · "),w=Vs(t),k=()=>{v("update"),Te("saving"),h(t.id,t.scope==="project"?i:null).then(N=>{v(null),_a(N,w??t.source,"update")})};return e.jsxs(rt,{children:[e.jsx(Ge,{heading:!0,title:w?e.jsx("button",{type:"button",onClick:()=>a(w),"aria-label":`${w} details`,className:"truncate typography-ui-label font-medium text-foreground underline-offset-4 outline-none hover:underline focus-visible:underline",children:w}):t.source,titleAccessory:t.pichamber?e.jsx(za,{}):null,detail:e.jsxs("p",{className:F(Pt,"line-clamp-2 text-pretty"),children:[b,t.installed?null:e.jsx("span",{className:"text-[var(--status-warning)]",children:" · Not installed"})]}),trailing:m?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&&f==="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&&f!=="update"?"Removing…":"Remove"})]}):void 0}),s.length===0?e.jsx("li",{className:F(Pt,"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(N=>e.jsx(Zi,{item:N,...r},N.id))]})}function Fd({pkg:t,directory:s,onClose:n}){const a=Je(m=>m.removePackage),[r,o]=l.useState(!1),[c,i]=l.useState(t);l.useEffect(()=>{t&&i(t)},[t]);const d=async()=>{if(!t)return;o(!0),Te("saving");const m=await a(t.id,t.scope==="project"?s:null);o(!1),Bs(m,t.source),n()},h=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(gt,{open:t!==null,onOpenChange:m=>{!m&&!r&&n()},children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Remove package?"}),e.jsx(yt,{children:`Pi stops loading ${c?.source??"this package"} ${h}. ${p}`})]}),e.jsxs(vs,{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 Bd({config:t,onRemove:s,onBrowse:n,onOpenPackage:a,...r}){const{view:o}=r,c=new Map,i=[],d=[],h=[];for(const m of t.extensions)m.group==="builtin"?h.push(m):m.group==="package"&&m.packageId?c.set(m.packageId,[...c.get(m.packageId)??[],m]):m.scope==="project"?d.push(m):i.push(m);const p=[...t.packages].sort((m,u)=>+(m.scope==="project")-+(u.scope==="project"));return e.jsxs("div",{className:"space-y-5",children:[e.jsx(ot,{title:"Packages",settingsItem:"plugins.extensions.packages",contentClassName:"space-y-2",children:p.length>0?p.map(m=>e.jsx(Ud,{pkg:m,items:c.get(m.id)??[],onRemove:s,onOpenPackage:a,...r},m.id)):e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("p",{className:F(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(ot,{title:e.jsx(Zn,{title:o==="project"?"Global extensions":"Your extensions",items:i,view:o}),settingsItem:"plugins.extensions.own",children:i.length>0?e.jsx(ea,{items:i,...r}):e.jsx("p",{className:F(he,"text-pretty"),children:p.length>0?"None outside packages.":"None yet. Pi loads the files in its extensions folder."})}),o==="project"&&d.length>0?e.jsx(ot,{title:e.jsx(Zn,{title:"This project's extensions",items:d,view:o}),children:e.jsx(ea,{items:d,...r})}):null,h.length>0?e.jsx(ot,{title:e.jsx(Zn,{title:"Built into Pi",items:h,view:o}),info:zd,settingsItem:"plugins.extensions.builtin",children:e.jsx(ea,{items:h,...r})}):null]})}function $d({directory:t,pluginNames:s,onBrowse:n,onOpenPackage:a}){const[r,o]=l.useState("global"),c=r==="project"&&t?"project":"global",i=c==="project"?t:null,d=xs(i),h=Je(w=>w.load),[p,m]=l.useState(null),u=d?.config??null,f=c==="project"&&u!==null&&!u.project.trusted,v=Ct(w=>w.loadVersions),g=(u?.packages??[]).filter(w=>w.installed&&!w.pinned&&w.version).map(Vs).filter(w=>!!w).sort().join(",");l.useEffect(()=>{g&&v(g.split(","))},[g,v]);let b;return!u&&d?.status==="error"?b=e.jsx(pt,{title:"Could not load Pi's extensions from the server",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{h(i,{force:!0})},children:"Try again"})}):u?b=e.jsxs("div",{className:"space-y-4",children:[d?.status==="error"?e.jsx(pt,{title:"Could not refresh this list",children:"It may be out of date."}):null,f?e.jsx(pt,{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(w=>e.jsx(pt,{title:`Pi could not load ${w.source}`,children:w.message},w.source)),e.jsx(Bd,{config:u,view:f?"global":c,readOnly:f,directory:i,notes:Dd(u,s),onRemove:m,onBrowse:n,onOpenPackage:a})]}):b=e.jsx("p",{className:he,children:"Loading extensions…"}),e.jsxs(q,{title:"Pi extensions",info:_d,settingsItem:"plugins.extensions",headerAction:t?e.jsx(Nn,{"aria-label":"Extension settings for",value:c,onChange:o,options:[{value:"global",label:"Global"},{value:"project",label:"This project"}]}):void 0,children:[b,e.jsx(Fd,{pkg:p,directory:i,onClose:()=>m(null)})]})}const Kd=t=>{const s=t.replace(/[\\/]+$/,"").split(/[\\/]/);return s[s.length-1]||t};function Vd({name:t,directory:s,projectTrusted:n,onClose:a}){const r=Je(u=>u.installPackage),[o,c]=l.useState("user"),[i,d]=l.useState(t);l.useEffect(()=>{t&&(d(t),c("user"))},[t]);const h=!!s&&n===!0,p=()=>{if(!t)return;const u=o==="project"&&h?s:null;a(),Te("saving"),r(t,u).then(f=>_a(f,t,"install"))};let m;return s&&n===!1?m="Pi does not trust this project, so it cannot install here.":s&&n===void 0&&(m="Checking this project…"),e.jsx(gt,{open:t!==null,onOpenChange:u=>{u||a()},children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{className:"break-all",children:`Install ${i??"package"}?`}),e.jsx(yt,{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(Zt,{"aria-label":"Where to install",children:[e.jsx(fs,{selected:o==="user",onSelect:()=>c("user"),label:"Every project"}),e.jsx(fs,{selected:o==="project",onSelect:()=>c("project"),disabled:!h,label:`This project only (${Kd(s)})`,description:m})]})]}):null,e.jsxs(vs,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:a,children:"Cancel"}),e.jsx(S,{variant:"solid",size:"sm",onClick:p,children:"Install"})]})]})})}const Hd={extensions:"Extensions",skills:"Skills",prompts:"Prompt templates",themes:"Themes"},Gd={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 cs({children:t}){return e.jsx("span",{className:F(Pt,"min-w-0 truncate text-right tabular-nums"),children:t})}function ta({title:t,url:s}){return e.jsx(Ge,{interactive:!0,title:e.jsx("button",{type:"button",onClick:()=>{us(s)},className:F("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(cs,{children:s.replace(/^https?:\/\//,"")}),e.jsx(R,{name:"external-link","aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})})}const Wd=t=>new Date(t).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});function qd({name:t,directory:s,backLabel:n,onBack:a,onInstall:r}){const o=Ct(P=>P.details[t]),c=Ct(P=>P.latest),i=Ct(P=>P.loadDetail),d=Je(P=>P.pending),h=Je(P=>P.updatePackage),p=xs(null)?.config,m=xs(s)?.config;l.useEffect(()=>{i(t)},[t,i]);const u=Wi([{config:p,view:"global"},...s?[{config:m,view:"project"}]:[]]).get(t),f=o?.data??null,v=u?Oa(u.pkg,c):void 0,g=d[di(t)]===!0,b=u?d[u.pkg.id]===!0:!1,w=e.jsxs(S,{variant:"ghost",size:"xs",onClick:a,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(R,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),n]}),k=()=>{u&&(Te("saving"),h(u.pkg.id,u.pkg.scope==="project"?s:null).then(P=>_a(P,t,"update")))};let N;g?N=e.jsx(S,{variant:"solid",size:"sm",disabled:!0,children:"Installing…"}):u&&v?N=e.jsx(S,{variant:"outline",size:"sm",disabled:b,onClick:k,children:b?"Updating…":`Update to ${v}`}):u||(N=e.jsx(S,{variant:"solid",size:"sm",onClick:()=>r(t),children:"Install"}));let A="Not installed",j;u?(A=u.pkg.scope==="project"?"Installed in this project":"Installed in every project",j=Gi(u.pkg)||void 0):g&&(A="Installing",j="npm is downloading it. This can take a minute.");let x;return!f&&o?.status==="error"?x=e.jsx(pt,{title:"Could not load this package from npm",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{i(t,{force:!0})},children:"Try again"}),children:"It may have been removed, or the PiChamber server cannot reach npm."}):f?x=e.jsxs(e.Fragment,{children:[f.isPiPackage?null:e.jsx(pt,{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:f.contains.length>0?e.jsx(rt,{children:f.contains.map(P=>e.jsx(Ge,{title:Hd[P],detail:Gd[P]},P))}):e.jsx("p",{className:F(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:F(he,"text-pretty"),children:f.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:[f.version?e.jsx(Ge,{title:"Latest version",trailing:e.jsx(cs,{children:f.version})}):null,f.date?e.jsx(Ge,{title:"Published",trailing:e.jsx(cs,{children:Wd(f.date)})}):null,f.publisher?e.jsx(Ge,{title:"Maintainer",trailing:e.jsx(cs,{children:f.publisher})}):null,f.license?e.jsx(Ge,{title:"License",trailing:e.jsx(cs,{children:f.license})}):null,f.weeklyDownloads!==void 0?e.jsx(Ge,{title:"Downloads",trailing:e.jsx(cs,{children:`${qi(f.weeklyDownloads)} a week`})}):null]})}),e.jsx(q,{title:"Links",children:e.jsxs(rt,{children:[e.jsx(ta,{title:"npm",url:f.links.npm}),f.links.repository?e.jsx(ta,{title:"Source code",url:f.links.repository}):null,f.links.homepage?e.jsx(ta,{title:"Homepage",url:f.links.homepage}):null]})})]}):x=e.jsx("p",{className:he,children:"Loading from npm…"}),e.jsxs(ye,{title:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("h1",{className:F(da,"min-w-0 break-all"),children:t}),f?.pichamber?e.jsx(za,{}):null]}),titleAbove:w,description:f?.description?e.jsx("p",{className:F(Ks,"text-pretty"),children:f.description}):void 0,children:[e.jsx(rt,{className:"mb-6",children:e.jsx(Ge,{title:A,detail:j,trailing:N})}),x]})}function eo(){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}`,Qd=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 to({plugin:t,className:s}){const n=Rs(o=>o.setEnabled),a=Rs(o=>o.pending[t.id]===!0),r=eo();return e.jsx(ca,{checked:t.enabled,disabled:a,ariaLabel:t.name,className:s,onChange:o=>{r(()=>n(t.id,o)).then(c=>{c&&Je.getState().invalidate()})}})}function so({plugin:t}){return e.jsx(R,{name:Al(t.icon),"aria-hidden":"true",className:F("size-5 shrink-0",t.enabled?"text-foreground":"text-muted-foreground")})}const Jd=t=>t.impactError?"Could not measure what it adds to the agent":Qd(t.impact);function no({plugin:t,replacement:s,showNativeTag:n=!0,onOpen:a}){return e.jsx(Ge,{interactive:!0,settingsItem:`plugins.${t.id}`,className:"items-start py-3",leading:e.jsx(so,{plugin:t}),title:e.jsx("button",{type:"button",onClick:a,"aria-label":`${t.name} settings`,className:F("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(Hi,{}):null,detail:e.jsxs(e.Fragment,{children:[e.jsx("p",{className:F(Pt,"line-clamp-2 text-pretty"),children:t.description}),s?e.jsx("p",{className:"truncate typography-meta text-[var(--status-warning)]",children:Ji(s)}):e.jsx("p",{className:"truncate typography-micro tabular-nums text-muted-foreground",children:t.enabled?Jd(t):"Off: adds nothing to the agent"})]}),trailing:e.jsxs(e.Fragment,{children:[e.jsx(to,{plugin:t,className:"relative z-10"}),e.jsx(R,{name:"arrow-right-s","aria-hidden":"true",className:"size-4 shrink-0 text-muted-foreground"})]})})}const Yd=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.",Xd="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.",Zd=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(" · "),eu=(t,s)=>[t.pkg.scope==="project"?"Installed in this project":"Installed",s&&Oa(t.pkg,{[Vs(t.pkg)??""]:s})?"update available":null].filter(Boolean).join(" · ");function tu({pkg:t,installed:s,installing:n,onOpen:a,onInstall:r}){const o=t.unavailable?"npm did not answer for this package":Zd(t),c=t.note??t.description;let i;return n?i=e.jsx(S,{variant:"outline",size:"xs",disabled:!0,className:"relative z-10",children:"Installing…"}):s?i=e.jsx("span",{className:F(Pt,"shrink-0"),children:eu(s,t.version)}):i=e.jsx(S,{variant:"outline",size:"xs",className:"relative z-10","aria-label":`Install ${t.name}`,onClick:r,children:"Install"}),e.jsx(Ge,{interactive:!0,className:"items-start py-3",title:e.jsx("button",{type:"button",onClick:a,"aria-label":`${t.name} details`,className:F("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(za,{}):null,detail:e.jsxs(e.Fragment,{children:[c?e.jsx("p",{className:F(Pt,"line-clamp-2 text-pretty"),children:c}):null,o?e.jsx("p",{className:"truncate typography-micro tabular-nums text-muted-foreground",children:o}):null]}),trailing:i})}function jr({packages:t,installed:s,onOpenPackage:n,onInstall:a}){const r=Je(o=>o.pending);return e.jsx(rt,{children:t.map(o=>e.jsx(tu,{pkg:o,installed:s.get(o.name),installing:r[di(o.name)]===!0,onOpen:()=>n(o.name),onInstall:()=>a(o.name)},o.name))})}function su(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 nu({plugins:t,directory:s,query:n,onQueryChange:a,filter:r,onFilterChange:o,onBack:c,onOpenPackage:i,onOpenPlugin:d,onInstall:h}){const p=su(n,Yd).trim(),m=r==="pichamber",u=Ct(T=>T.featured),f=Ct(T=>T.loadFeatured),v=Ct(T=>T.search),g=Ct(T=>T.searches[hc(p,m)]),b=xs(null)?.config,w=xs(s)?.config,k=l.useMemo(()=>Wi([{config:b,view:"global"},...s?[{config:w,view:"project"}]:[]]),[b,w,s]),N=p===""&&!m;l.useEffect(()=>{N&&f()},[N,f]),l.useEffect(()=>{v(p,m)},[p,m,v]);const A=Ad(t,p),j=new Set(N?(u.data?.packages??[]).map(T=>T.name):[]),x=(g?.packages??[]).filter(T=>!j.has(T.name));let P;if(!g||g.status==="loading"&&g.packages.length===0)P=e.jsx("p",{className:he,children:p?"Searching npm…":"Loading packages from npm…"});else if(g.status==="error"&&g.packages.length===0)P=e.jsx(pt,{title:"Could not reach npm",action:e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{v(p,m,{force:!0})},children:"Try again"}),children:"The PiChamber server could not get the package list. Check its network connection."});else if(x.length===0){let T;m?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.",P=e.jsx("p",{className:F(he,"text-pretty"),children:T})}else P=e.jsxs("div",{className:"space-y-3",children:[g.status==="error"?e.jsx(pt,{title:"Could not refresh these results",children:"They may be out of date."}):null,e.jsx(jr,{packages:x,installed:k,onOpenPackage:i,onInstall:h}),g.nextFrom!==null?e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-3",children:[g.moreFailed?e.jsx("span",{className:he,children:"Could not load more."}):null,e.jsx(S,{variant:"ghost",size:"sm",disabled:g.loadingMore,onClick:()=>{v(p,m,{more:!0})},children:g.loadingMore?"Loading…":g.moreFailed?"Try again":"Show more"})]}):null]});const C=p?"Results":m?"Enhanced for PiChamber":"Popular",y=!p&&g?.total!==void 0&&!m?e.jsx("span",{className:"typography-micro tabular-nums text-muted-foreground",children:`${g.total.toLocaleString()} Pi packages`}):null;let L=0;const I=()=>(L+=1,L>1);return e.jsxs(ye,{title:"Browse",titleAbove:e.jsxs(S,{variant:"ghost",size:"xs",onClick:c,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(R,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),"Extensions & Plugins"]}),description:e.jsx("p",{className:F(Ks,"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(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value: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(R,{name:"close",className:"size-4"})}):null]}),e.jsx(Nn,{"aria-label":"Show packages",value:r,onChange:o,options:[{value:"all",label:"All"},{value:"pichamber",label:"Enhanced for PiChamber"}]})]}),A.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:A.map(T=>e.jsx(no,{plugin:T,onOpen:()=>d(T.id)},T.id))})}):null,N?e.jsx(q,{divider:I(),title:"Featured",info:yr,children:u.data&&u.data.packages.length>0?e.jsx(jr,{packages:u.data.packages,installed:k,onOpenPackage:i,onInstall:h}):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:y,info:m?Xd:N?void 0:yr,children:P})]})}const au="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.",ru="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.",iu=[{id:"all",label:"All"},{id:"on",label:"On"},{id:"off",label:"Off"}],ou=7;function lu({plugins:t,config:s,onOpen:n}){const[a,r]=l.useState("all"),o={all:t.length,on:t.filter(i=>i.enabled).length,off:t.filter(i=>!i.enabled).length},c=t.filter(i=>a==="all"||(a==="on"?i.enabled:!i.enabled));return e.jsxs(q,{divider:!1,title:"Native plugins",info:au,contentClassName:"space-y-3",children:[t.length>=ou?e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",role:"group","aria-label":"Show plugins",children:iu.map(({id:i,label:d})=>e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":a===i,onClick:()=>r(i),children:[d,e.jsx("span",{className:"tabular-nums text-muted-foreground",children:o[i]})]},i))}):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(i=>e.jsx(no,{plugin:i,replacement:i.enabled?Qi(s,"plugin",i.id):void 0,showNativeTag:!1,onOpen:()=>n(i.id)},i.id))})]})}function cu({plugin:t,directory:s,disabled:n}){const a=Rs(h=>h.setState),r=Rs(h=>h.pending),o=eo(),i=(t.contributes.settings??Object.keys(t.stateSchema)).flatMap(h=>{const p=t.stateSchema[h];return p?p.scope==="project"&&!s?[]:[{key:h,field:p}]:[]});if(i.length===0)return null;const d=(h,p)=>{o(()=>a(t.id,h,p,s))};return e.jsx("div",{className:ft,children:i.map(({key:h,field:p})=>{const m=t.state[h]??p.default,u=n||r[`${t.id}
|
|
3
|
-
${h}`]===!0,f=p.scope==="project"?`${p.label} (this project)`:p.label,v=`plugins.${t.id}.${h}`;return p.type==="boolean"?e.jsx(Ce,{checked:m===!0,onChange:g=>d(h,g),label:f,ariaLabel:p.label,info:p.description,disabled:u,settingsItem:v},h):e.jsx(Ie,{label:f,info:p.description,settingsItem:v,children:e.jsxs(Re,{value:String(m),onValueChange:g=>d(h,g),disabled:u,children:[e.jsx(De,{size:Be,className:hs,"aria-label":p.label,children:e.jsx(_e,{children:(p.options??[]).find(g=>g.value===String(m))?.label??String(m)})}),e.jsx(ze,{children:(p.options??[]).map(g=>e.jsx(je,{value:g.value,children:g.label},g.value))})]})},h)})})}const du=(t,s)=>(t.contributes.settings??Object.keys(t.stateSchema)).some(n=>{const a=t.stateSchema[n];return!!a&&(a.scope!=="project"||!!s)});function ma({children:t}){return e.jsx("span",{className:F(Pt,"min-w-0 text-right tabular-nums"),children:t})}function uu({impact:t,error:s}){return s?e.jsx(pt,{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(Ge,{mono:!0,title:a.name,titleAccessory:e.jsx(gn,{children:"Tool"}),stackTrailing:!0,trailing:e.jsx(ma,{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(Ge,{mono:!0,title:`/${a}`,titleAccessory:e.jsx(gn,{children:"Command"})},a)),t.hooks.length>0?e.jsx(Ge,{wrap:!0,title:"Can change the prompt or the request before it is sent"}):null]})}function pu({plugin:t}){const s=Ml(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(Ge,{wrap:!0,title:`A ${a.label} switch in the composer`,detail:e.jsx("p",{className:F(Pt,"text-pretty"),children:"On in every new session. Changing it changes that session only."})},a.id)),s.map(a=>e.jsx(Ge,{wrap:!0,title:a},a))]})}function mu({replacement:t,config:s}){const n=Je(i=>i.setGlobal),a=Je(i=>i.setProjectState),r=Rd(s,t),o=Je(i=>r?i.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=>Bs(d,r.name))};return e.jsxs(pt,{className:"mb-3",title:"Pi is not loading this plugin",action:r?e.jsx(S,{variant:"outline",size:"sm",disabled:o,onClick:c,children:r.scope==="project"?`Turn off ${r.name} in this project`:`Turn off ${r.name} in every project`}):void 0,children:[Md(t),r?null:" To use this plugin, turn that extension off under Pi extensions."]})}function hu({plugin:t,directory:s,config:n,backLabel:a,onBack:r}){const o=du(t,s),c=t.enabled?Qi(n,"plugin",t.id):void 0;return e.jsxs(ye,{title:t.name,titleAbove:e.jsxs(S,{variant:"ghost",size:"xs",onClick:r,className:"-ml-2 gap-1 text-muted-foreground",children:[e.jsx(R,{name:"arrow-left-s","aria-hidden":"true",className:"size-4"}),a]}),titleLeading:e.jsx(so,{plugin:t}),titleAccessory:t.bundled?e.jsx(Hi,{}):null,description:e.jsx("p",{className:F(Ks,"text-pretty"),children:t.description}),children:[c?e.jsx(mu,{replacement:c,config:n}):null,e.jsx(rt,{className:"mb-6",children:e.jsx(Ge,{title:"Enabled",trailing:e.jsx(to,{plugin:t})})}),e.jsx(q,{divider:!1,title:"What it adds to the agent",info:ru,description:t.enabled?void 0:"Only while it is on. Off, it adds nothing.",settingsItem:`plugins.${t.id}`,children:e.jsx(uu,{impact:t.impact,error:t.impactError})}),e.jsx(q,{title:"In PiChamber",children:e.jsx(pu,{plugin:t})}),o?e.jsx(q,{title:"Options",description:t.enabled?void 0:"Turn the plugin on to change these.",children:e.jsx(cu,{plugin:t,directory:s,disabled:!t.enabled})}):null,e.jsx(q,{title:"About",children:e.jsxs(rt,{children:[e.jsx(Ge,{title:"Source",trailing:e.jsx(ma,{children:t.bundled?"Native: comes with PiChamber":"Installed"})}),e.jsx(Ge,{title:"Version",trailing:e.jsx(ma,{children:t.version})})]})})]})}const fu=()=>{const t=Ca()??null,{plugins:s,entry:n}=Ll(t),a=Rs(w=>w.load),[r,o]=l.useState({kind:"list"}),[c,i]=l.useState(""),[d,h]=l.useState("all"),[p,m]=l.useState(null),u=xs(t)?.config??null,f=t&&u?u.project.trusted:void 0,v=e.jsx(Vd,{name:p,directory:t,projectTrusted:f,onClose:()=>m(null)});if(r.kind==="plugin"){const w=s.find(k=>k.id===r.id);if(w)return e.jsx(hu,{plugin:w,directory:t,config:u,backLabel:r.from==="browse"?"Browse":"Extensions & Plugins",onBack:()=>o(r.from==="browse"?{kind:"browse"}:{kind:"list"})})}if(r.kind==="browse")return e.jsxs(e.Fragment,{children:[e.jsx(nu,{plugins:s,directory:t,query:c,onQueryChange:i,filter:d,onFilterChange:h,onBack:()=>o({kind:"list"}),onOpenPackage:w=>o({kind:"package",name:w,from:"browse"}),onOpenPlugin:w=>o({kind:"plugin",id:w,from:"browse"}),onInstall:m}),v]});if(r.kind==="package")return e.jsxs(e.Fragment,{children:[e.jsx(qd,{name:r.name,directory:t,backLabel:r.from==="browse"?"Browse":"Extensions & Plugins",onBack:()=>o(r.from==="browse"?{kind:"browse"}:{kind:"list"}),onInstall:m}),v]});let g;!n?.plugins&&n?.status==="error"?g=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?g=e.jsx(q,{divider:!1,title:"Native plugins",children:e.jsx("p",{className:he,children:"This server has no plugins."})}):g=e.jsx(lu,{plugins:s,config:u,onOpen:w=>o({kind:"plugin",id:w,from:"list"})}):g=e.jsx(q,{divider:!1,title:"Native plugins",children:e.jsx("p",{className:he,children:"Loading plugins…"})});const b=()=>o({kind:"browse"});return e.jsxs(ye,{title:"Extensions & Plugins",description:e.jsx("p",{className:F(Ks,"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(R,{name:"search","aria-hidden":"true",className:"size-3.5"}),"Browse"]}),children:[g,e.jsx($d,{directory:t,pluginNames:Object.fromEntries(s.map(w=>[w.id,w.name])),onBrowse:b,onOpenPackage:w=>o({kind:"package",name:w,from:"list"})})]})},gu=({project:t,sandbox:s,onSelect:n})=>{const a=ei(t),r=!!t.label?.trim(),o=Jo(h=>h.homeDirectory),c=Yo(t.path,o),i=!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}${i?`, ${i.toLowerCase()}`:""}`,className:F("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(ti,{directory:t.path,label:a,className:"size-8"}),i?e.jsxs("span",{title:i,className:F("inline-flex items-center gap-1 typography-micro whitespace-nowrap",d?"text-[var(--status-error)]":"text-subtle-foreground"),children:[e.jsx(R,{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(Rl,{value:c,className:F("flex typography-meta text-muted-foreground",r&&"font-mono")})]})]})},xu=({profile:t,saving:s,errors:n,onSave:a,onReset:r})=>{const[o,c]=l.useState(t.content),[i,d]=l.useState(!1);l.useEffect(()=>{c(t.content)},[t.content]);const h=o!==t.content;return e.jsx(Cn,{label:"Sandbox profile",divider:!1,className:"pb-0 pt-2",children:e.jsxs("div",{className:mt,children:[e.jsx("p",{className:F(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:o,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:F(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:F(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?i?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||!h,onClick:()=>{a(o)},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"})})]})})},vu=(t,s)=>{const n=t.limits??[];return s?.acceptedLimits?n.every(a=>s.acceptedLimits?.includes(a)):t.limitsAccepted===!0},bu=(t,s)=>({acceptedLimits:s?[...t]:[]}),yu=t=>t.available?t.version?`Available, version ${t.version}`:"Available":Dl(t.reason),ju="https://nono.sh",wr=()=>{const t=Oe(j=>j.launchers),s=Oe(j=>j.launchersStatus),n=Oe(j=>j.rechecking),a=Oe(j=>j.loadLaunchers),r=Oe(j=>j.recheck),o=Oe(j=>j.defaults),c=Oe(j=>j.defaultsStatus),i=Oe(j=>j.savingDefaults),d=Oe(j=>j.defaultsError),h=Oe(j=>j.loadDefaults),p=Oe(j=>j.saveDefaults),m=Oe(j=>j.profile),u=Oe(j=>j.savingProfile),f=Oe(j=>j.profileErrors),v=Oe(j=>j.loadProfile),g=Oe(j=>j.saveProfile),b=Oe(j=>j.resetProfile),w=Oe(j=>Object.values(j.projects).some(x=>x.mode!=="off"));l.useEffect(()=>{s==="idle"&&a()},[s,a]),l.useEffect(()=>{h(),v()},[h,v]);const k=l.useCallback(async j=>{Te("saving");const x=await g(j);return Te(x?"saved":"error"),x},[g]),N=l.useCallback(async()=>{Te("saving");const j=await b();return Te(j?"saved":"error"),j},[b]),A=l.useCallback(async j=>{const x=Oe.getState().defaults,P=(j.mode===void 0||j.mode===x?.mode)&&(j.allowHosts===void 0||JSON.stringify(j.allowHosts)===JSON.stringify(x?.allowHosts))&&(j.acceptedLimits===void 0||JSON.stringify(j.acceptedLimits)===JSON.stringify(x?.acceptedLimits??[]));if(x&&!x.invalid&&P)return;Te("saving");const C=await p(j);Te(C?"saved":"error")},[p]);return e.jsx(wu,{launchers:t,loadFailed:s==="failed",rechecking:n,onRecheck:()=>{r()},defaults:o,defaultsLoadFailed:c==="failed",savingDefaults:i,defaultsError:d,onSaveDefaults:A,profile:m&&(w||m.custom)?m:null,savingProfile:u,profileErrors:f,onSaveProfile:k,onResetProfile:N})},wu=({launchers:t,loadFailed:s,rechecking:n,onRecheck:a,defaults:r=null,defaultsLoadFailed:o=!1,savingDefaults:c=!1,defaultsError:i=null,onSaveDefaults:d,profile:h=null,savingProfile:p=!1,profileErrors:m=[],onSaveProfile:u,onResetProfile:f})=>{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:mt,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(g=>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:g.id}),e.jsx("p",{className:g.available?"typography-meta text-muted-foreground":"typography-meta text-[var(--status-error)]",children:yu(g)}),g.id==="nono"?e.jsx("a",{href:ju,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})]}),g.available&&g.limits&&g.limits.length>0?e.jsx(ku,{limits:g.limits,accepted:vu(g,r),disabled:c||!r||r.invalid===!0||!d,onChange:b=>{!r||r.invalid||!d||d(bu(g.limits??[],b))}}):null]},g.id)):e.jsx("p",{className:he,children:"Checking…"}),r&&d?e.jsx(Nu,{defaults:r,saving:c,onSave:d}):o?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,i?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:i}):null,h&&u&&f?e.jsx(xu,{profile:h,saving:p,errors:m,onSave:u,onReset:f}):null]})})},ku=({limits:t,accepted:s,disabled:n,onChange:a})=>e.jsxs(ot,{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:o,text:c}=_l(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:o}),e.jsx("p",{className:F(he,"text-pretty"),children:c})]},r)})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ce,{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."})]})]}),Nu=({defaults:t,saving:s,onSave:n})=>{const[a,r]=l.useState(()=>t.allowHosts.join(`
|
|
4
|
-
`)),o=t.allowHosts.join(`
|
|
5
|
-
`);l.useEffect(()=>{r(o)},[o]);const c=zl(a),i=h=>{const p=Ol(c,h);r(p.join(`
|
|
6
|
-
`)),d(p)},d=h=>{t.invalid||n({allowHosts:h})};return e.jsxs(Rt,{className:"pt-2",children:[e.jsx("div",{className:"min-w-0",children:e.jsx(Ce,{checked:t.mode==="nono",disabled:s,onChange:h=>{const p=h?"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(Ae,{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:h=>r(h.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,os.github),title:os.github.join(", "),onClick:()=>i(os.github),children:"Add GitHub"}),e.jsx(S,{variant:"outline",size:"xs",disabled:s||sr(c,os.registries),title:os.registries.join(", "),onClick:()=>i(os.registries),children:"Add package registries"})]})]})]})},Cu=()=>{const{isMobile:t}=lt(),s=dn(w=>w.projects),n=dn(w=>w.updateProjectMeta),a=W(w=>w.settingsProjectsSelectedId),r=W(w=>w.setSettingsProjectsSelectedId),[o,c]=l.useState(""),i=Oe(w=>w.projects),d=Oe(w=>w.projectsStatus),h=Oe(w=>w.loadProjects);l.useEffect(()=>{d==="idle"&&h()},[h,d]);const p=s.filter(w=>!i[w.id]).map(w=>w.id).sort().join(`
|
|
7
|
-
`),m=l.useRef("");l.useEffect(()=>{if(!p){m.current="";return}d==="ready"&&m.current!==p&&(m.current=p,h())},[p,d,h]);const u=l.useCallback(()=>{Ul.requestDirectoryDialog()},[]),f=l.useMemo(()=>a?s.find(w=>w.id===a)??null:null,[s,a]);l.useEffect(()=>{a&&!s.some(w=>w.id===a)&&r(null)},[s,a,r]);const v=l.useCallback(async w=>{f&&n(f.id,{label:w.label,defaultModel:w.defaultModel??null})},[f,n]),g=l.useMemo(()=>[...s].sort((w,k)=>{const N=(w.label?.trim()||w.path).toLowerCase(),A=(k.label?.trim()||k.path).toLowerCase();return N.localeCompare(A,void 0,{sensitivity:"base"})}),[s]),b=l.useMemo(()=>{const w=o.trim().toLowerCase();return w?g.filter(k=>{const N=(k.label??"").toLowerCase(),A=k.path.toLowerCase();return N.includes(w)||A.includes(w)}):g},[g,o]);if(f){const w=ei(f);return e.jsx(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx(ti,{directory:f.path,label:w,className:"size-5"}),e.jsx("span",{className:"truncate",children:w})]}),description:e.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:f.path}),children:e.jsx(fc,{project:f,onIdentitySave:v})})}return s.length===0?e.jsxs(ye,{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(R,{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(R,{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(R,{name:"add",className:"size-4"}),"Add folder"]})]})}),e.jsx(wr,{})]}):e.jsxs(ye,{title:t?void 0:"Projects",description:t?void 0:"Manage your projects and worktrees. Click a card to configure its defaults and actions.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:o,onChange:w=>c(w.target.value),placeholder:"Search projects","aria-label":"Search projects",className:"h-9 w-[18rem] max-w-full pl-8"}),o?e.jsx("button",{type:"button",onClick:()=>c(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(R,{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:()=>{h()},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 “",o,"”."]}),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(w=>e.jsx(gu,{project:w,sandbox:i[w.id],onSelect:r},w.id))})]}),e.jsx(wr,{})]})},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),Su=()=>{const t=W(x=>x.timeFormatPreference),[s,n]=l.useState(!1),[a,r]=l.useState(!0),[o,c]=l.useState(!1),[i,d]=l.useState(null),[h,p]=l.useState(!1),[m,u]=l.useState([]),[f,v]=l.useState(Fl),[g,b]=l.useState(""),w=l.useMemo(()=>Bl(),[]),k=l.useCallback(async()=>{r(!0),b("");try{const x=await $l();u(x)}catch(x){const P=x instanceof Error?x.message:"Could not load passkeys.";b(P)}finally{r(!1)}},[]);l.useEffect(()=>{let x=!1;return(async()=>{try{if(!w.supported){x||(n(!1),r(!1));return}x||n(!0)}catch{x||n(!1)}if(!x){const P=await Gn();if(v(P),!P.enabled){u([]),r(!1);return}await k()}})(),()=>{x=!0,nr()}},[k,w.supported]);const N=l.useCallback(async()=>{if(!f.enabled){const x="Enable the UI password lock before adding passkeys.";b(x),B.message(x);return}if(!s){b(w.reason),B.message(w.reason);return}if(o){nr(),c(!1);return}b(""),c(!0);try{await Kl(),v(await Gn()),await k(),B.success("Passkey added")}catch(x){if(Vl(x)){B.message("Passkey setup canceled");return}const P=x instanceof Error?x.message:"Could not add passkey.";b(P),B.error(P)}finally{c(!1)}},[o,k,f.enabled,w.reason,s]),A=l.useCallback(async x=>{d(x),b("");try{await Hl(x),v(await Gn()),await k(),B.success("Passkey removed")}catch(P){const C=P instanceof Error?P.message:"Could not remove passkey.";b(C),B.error(C)}finally{d(null)}},[k]),j=l.useCallback(async()=>{p(!0),b("");try{await Gl(),window.location.reload()}catch(x){const P=x instanceof Error?x.message:"Could not clear saved authentication.";b(P),B.error(P),p(!1)}},[]);return e.jsxs(q,{title:"Passkeys",settingsItem:"remote-access.passkeys",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ie,{label:"Current device",children:[e.jsx(S,{type:"button",variant:o?"secondary":"outline",size:"xs",onClick:()=>{N()},disabled:a||h,className:"!font-normal",children:o?"Cancel passkey setup":"Add passkey"}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{j()},disabled:a||o||h,className:"!font-normal text-muted-foreground hover:text-foreground",children:h?"Signing out…":"Sign out everywhere"})]}),!f.enabled&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Passkeys are available only when the UI password lock is enabled."}),f.enabled&&!s&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:w.reason}),a?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading passkeys…"}):m.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:m.map(x=>e.jsxs(Ie,{label:e.jsx("span",{className:"truncate",children:x.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:x.lastUsedAt?`Last used ${kr(x.lastUsedAt,"Never used",t)}`:`Added ${kr(x.createdAt,"Never used",t)}`}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",onClick:()=>{A(x.id)},disabled:i===x.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:i===x.id?"Removing…":"Delete"})]},x.id))})]}),g&&e.jsx("div",{className:"mt-1 py-1.5",children:e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:g})})]})},Pu=({addDevice:t,isDesktop:s})=>{const{phase:n,creating:a,loopbackOnly:r,pairingUrl:o,pairingQrDataUrl:c,pairingCopied:i,countdownText:d,announcedCountdownText:h,routeChips:p,error:m,closeDialog:u,regenerate:f,copyLink:v,scrollToWays:g}=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:()=>g("lan"),children:"Turn on local network"}):null,e.jsx(S,{type:"button",size:"xs",variant:s?"outline":"default",className:"!font-normal",onClick:()=>g("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&&!o?e.jsxs("div",{className:"flex items-center gap-2 py-6 typography-ui text-muted-foreground",role:"status",children:[e.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin","aria-hidden":!0}),"Creating secure code…"]}):e.jsxs("div",{className:"space-y-3",children:[c?e.jsx("div",{className:"flex justify-center",children:e.jsx("img",{src:c,alt:"PiChamber connection QR code",className:F("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:h??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,m?e.jsx("p",{className:"typography-meta text-center text-[var(--status-error)]",role:"alert",children:m}):null,o?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:o}),e.jsxs(S,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:v,"aria-label":i?"Pairing link copied":"Copy pairing link",children:[e.jsx(R,{name:i?"check":"file-copy",className:F("h-3.5 w-3.5",i&&"text-[var(--status-success)]"),"aria-hidden":!0}),i?"Copied":"Copy"]})]}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(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:f,disabled:a,children:[e.jsx(R,{name:"refresh",className:"h-3.5 w-3.5","aria-hidden":!0}),"New code"]})]})]})})},Tu=({addDevice:t,isDesktop:s})=>{const n=!t.loopbackOnly&&!!t.pairingQrDataUrl;return e.jsx(gt,{open:t.open,onOpenChange:a=>{a||t.closeDialog()},children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Add a device"}),n?e.jsx(yt,{children:"Scan this with the PiChamber app on your other device. It is single-use and expires."}):null]}),e.jsx(Pu,{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}},Iu=({devices:t})=>{const s=W(p=>p.timeFormatPreference),{remoteClients:n,pendingPairings:a,loading:r,error:o,revokedClientCount:c,revokeRemoteClient:i,purgeRevokedRemoteClients:d,cancelPendingPairing:h}=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:()=>h(p.id),"aria-label":`Cancel pairing for ${p.label||"new device"}`,children:"Cancel"})]},`pending-${p.id}`)),n.map(p=>{const m=p.clientKind==="desktop-local",u=p.lastUsedAt?Date.parse(p.lastUsedAt):Number.NaN,f=!p.revokedAt&&(m||Number.isFinite(u)&&Date.now()-u<9e4),v=p.revokedAt?"Revoked":f?p.lastTransport==="relay"&&!m?"Connected · Relay":"Connected · Local network":Number.isFinite(u)?`Last used ${Wl(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:F("h-2 w-2 shrink-0 rounded-full",p.revokedAt?"bg-muted-foreground/20":f?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),e.jsx("p",{className:"typography-ui-label text-foreground truncate",children:p.label}),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,m?e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"This device"}):null,e.jsx("span",{className:F("typography-micro truncate",f&&!p.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:v})]})}),e.jsx(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>i(p),disabled:!!p.revokedAt,"aria-label":`Revoke ${p.label}`,children:"Revoke"})]},p.id)})]}),o?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:o}):null]})},Eu=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:ft,children:e.jsx(Ce,{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"})})]}),Au=({lan:t})=>e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{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:nt,"aria-label":t.showPassword?"Hide password":"Show password","aria-pressed":t.showPassword,children:e.jsx(R,{name:t.showPassword?"eye-off":"eye",className:"h-4 w-4"})})]}),t.error?e.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t.error}):null,e.jsx("div",{className:"flex justify-start py-1.5",children:e.jsx(S,{type:"button",size:"xs",onClick:t.saveAndRestart,disabled:t.saveDisabled,className:"shrink-0 !font-normal",children:t.isSaving?"Saving...":"Save + Restart"})})]}),Lu=()=>{const t=Fe()&&ss(),[s,n]=D.useState(!1),[a,r]=D.useState(!1),[o,c]=D.useState(""),[i,d]=D.useState(""),[h,p]=D.useState(!1),[m,u]=D.useState(!1),[f,v]=D.useState(null),[g,b]=D.useState(!0),[w,k]=D.useState(!1),[N,A]=D.useState(null),[j,x]=D.useState(null);D.useEffect(()=>{if(!t){b(!1);return}let _=!1;return(async()=>{try{const O=await Ee("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!O.ok)throw new Error("Failed to load desktop settings");const V=await O.json().catch(()=>null);if(_)return;const H=V?.desktopLanAccessEnabled===!0,ne=typeof V?.desktopUiPassword=="string"?V.desktopUiPassword:"";n(H),r(H),c(ne),d(ne),u(V?.desktopLanAccessActive===!0),v(typeof V?.desktopLanAccessBlockedReason=="string"?V.desktopLanAccessBlockedReason:null),A(null)}catch(O){_||A(O instanceof Error?O.message:"Failed to load desktop settings")}finally{_||b(!1)}})(),()=>{_=!0}},[t]),D.useEffect(()=>{if(!t||!a){x(null);return}let _=!1;return(async()=>{const O=await Xo();_||x(O)})(),()=>{_=!0}},[a,t]);const P=a!==s||i!==o,C=D.useMemo(()=>{if(typeof window>"u")return null;const O=ht()||window.location.href;let V=0;try{V=Number(new URL(O).port)}catch{V=Number(window.location.port)}return Number.isFinite(V)&&V>0?V:null},[]),y=a&&m&&j&&C?`http://${j}:${C}`:null,L=a&&!i.trim(),I=s&&!m&&f==="missing-password",T=g||w||!P||L,E=D.useCallback(_=>{d(_),_.trim()||r(!1)},[]),U=D.useCallback(async()=>{if(P){k(!0),A(null);try{if(!(await Ee("/api/pi/ui-settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:a,desktopUiPassword:i})})).ok)throw new Error("Failed to save desktop settings");if(n(a),c(i),!await Jr())throw new Error("Saved, but failed to restart app")}catch(_){A(_ instanceof Error?_.message:"Failed to save desktop settings"),k(!1)}}},[i,a,P]);return{isLocalDesktop:t,isLoading:g,isSaving:w,error:N,draftLanEnabled:a,setDraftLanEnabled:r,draftPassword:i,handlePasswordChange:E,showPassword:h,setShowPassword:p,lanAccessActive:m,lanRequiresPassword:L,lanBlockedByMissingPassword:I,lanUrl:y,isDirty:P,saveDisabled:T,saveAndRestart:()=>{U()}}},ao=()=>{const[t,s]=D.useState(!1),n=D.useRef(null);D.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]);const a=D.useCallback(r=>{$s(r).then(o=>{o.ok&&(s(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>s(!1),2e3))})},[]);return{copied:t,copy:a}},Mu={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)]"},St=({tone:t,children:s})=>e.jsx("span",{className:F("typography-micro shrink-0 rounded border px-1.5 py-px leading-relaxed",Mu[t]),children:s}),ds=({id:t,icon:s,title:n,pill:a,description:r,settingsItem:o,children:c})=>e.jsx(ot,{settingsItem:o,title:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",id:t,children:[e.jsx(R,{name:s,className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:gc,children:n}),a]}),children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:r}),c]})}),ro=({url:t,copyLabel:s,onOpen:n,openLabel:a})=>{const{copied:r,copy:o}=ao(),c=r?`${s} (copied)`:s,i=e.jsxs(e.Fragment,{children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono typography-micro text-foreground",children:t}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[r?e.jsx("span",{className:"typography-micro text-[var(--status-success)]",children:"Copied"}):null,e.jsx(R,{name:r?"check":"file-copy",className:F("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:()=>o(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:i}),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(R,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})})]}):e.jsx("button",{type:"button",onClick:()=>o(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:i})},Ru=({lan:t})=>{if(Fe()&&ss()){const n=t.lanUrl?e.jsx(St,{tone:"success",children:"On"}):t.draftLanEnabled?e.jsx(St,{tone:"warning",children:"Restart needed"}):e.jsx(St,{tone:"neutral",children:"Off"});return e.jsx(ds,{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(Eu,{lan:t})})}return e.jsx(Du,{})},Du=()=>{const{clientAuth:t}=kn(),[s,n]=D.useState(null),[a,r]=D.useState(!0),[o,c]=D.useState(!1);return D.useEffect(()=>{if(!t?.getPairingTransports){r(!1);return}let i=!1;return(async()=>{try{const d=await t.getPairingTransports();i||(n(d),c(!1))}catch{i||c(!0)}finally{i||r(!1)}})(),()=>{i=!0}},[t]),a?e.jsx(ds,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(St,{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…"})}):o||!s?e.jsx(ds,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(St,{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(ds,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(St,{tone:"success",children:"On"}),description:"Phones and computers on your Wi-Fi reach this server directly.",settingsItem:"remote-access.lan",children:e.jsx(ro,{url:s.lan,copyLabel:"Copy local network address"})}):e.jsx(ds,{id:"remote-access-lan-row",icon:"home",title:"Local network",pill:e.jsx(St,{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},_u=async t=>{const s=await Ee("/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},zu=async t=>{const s=await Ee("/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},Ou=async()=>{const t=await Ee("/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},Uu=2e3,Fu=15e3,sa=t=>t==="starting"||t==="needs-approval"?Uu:Fu,io=t=>t.config.enabled?t.config.mode:"off",Bu=(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},$u=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}},Ku=()=>{const[t,s]=D.useState(null),[n,a]=D.useState(!0),[r,o]=D.useState(!1),[c,i]=D.useState(null),[d,h]=D.useState(null),[p,m]=D.useState(null),[u,f]=D.useState(!1),[v,g]=D.useState(null),[b,w]=D.useState(!1),k=D.useRef(0),N=D.useCallback(T=>{s(T),o(!1),i(null)},[]),A=D.useCallback(async T=>{const E=k.current;try{const U=await _u();if(k.current!==E)return;N(U)}catch(U){if(k.current!==E)return;T?.initial&&!t&&o(!0),i(U instanceof Error?U.message:"Failed to load Tailscale status")}finally{k.current===E&&T?.initial&&a(!1)}},[N]);D.useEffect(()=>(A({initial:!0}),()=>{k.current+=1}),[A]),D.useEffect(()=>{if(typeof window>"u")return;let T=null,E=!1;const U=async()=>{if(!E){if(typeof document<"u"&&document.visibilityState==="hidden"){_(sa(t?.state??null));return}await A(),E||_(sa(t?.state??null))}},_=V=>{E||(T=setTimeout(()=>{U()},V))};_(sa(t?.state??null));const O=()=>{document.visibilityState==="visible"&&(T&&clearTimeout(T),U())};return document.addEventListener("visibilitychange",O),()=>{E=!0,T&&clearTimeout(T),document.removeEventListener("visibilitychange",O)}},[A,t?.state]);const j=D.useCallback(async T=>{const E=k.current;f(!0),h(null),m(null);try{const U=await zu(T);if(k.current!==E)return;N(U)}catch(U){if(k.current!==E)return;const _=U.code;h(U instanceof Error?U.message:"Failed to update Tailscale"),m(typeof _=="string"?_:null)}finally{k.current===E&&(f(!1),g(null))}},[N]),x=D.useCallback(T=>{if(!t||u)return;const E=io(t);if(T!==E){if(Bu(E,T)){w(!0);return}g(T),j(T==="off"?{enabled:!1}:{enabled:!0,mode:T})}},[t,u,j]),P=D.useCallback(()=>{w(!1),!(!t||u)&&(g("public"),j({enabled:!0,mode:"public"}))},[t,u,j]),C=D.useCallback(()=>{w(!1)},[]),y=D.useCallback(T=>{!t||u||t.config.httpsPort!==T&&j({httpsPort:T})},[t,u,j]),L=D.useCallback(async()=>{const T=k.current;f(!0),h(null),m(null);try{const E=await Ou();if(k.current!==T)return;N(E)}catch(E){if(k.current!==T)return;const U=E.code;h(E instanceof Error?E.message:"Tailscale retry failed"),m(typeof U=="string"?U:null)}finally{k.current===T&&(f(!1),g(null))}},[N]),I=D.useCallback(()=>{a(!0),o(!1),i(null),A({initial:!0})},[A]);return{status:t,initialLoading:n,loadFailed:r,loadError:c,actionError:d,actionErrorCode:p,mutationInFlight:u,pendingMode:v,confirmPublicOpen:b,setMode:x,confirmPublic:P,cancelPublicConfirm:C,setPort:y,retryNow:L,reload:I}},Vu="https://tailscale.com/download",Sr="sudo tailscale set --operator=$USER",Hu=[{value:"off",label:"Off"},{value:"private",label:"Private"},{value:"public",label:"Public"}],Gu={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))},Wu=(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,qu=()=>{const t=Ku(),{status:s,initialLoading:n,loadFailed:a,loadError:r,actionError:o,actionErrorCode:c,mutationInFlight:i,pendingMode:d,confirmPublicOpen:h}=t,p=Fe(),m=$u(s),u=s?io(s):"off",f=d??u,{copied:v,copy:g}=ao(),b=!!m?.controlDisabled,w=Cr(s,"private"),k=Cr(s,"public"),N=s?!w||!k:!1,A=E=>i?!0:E==="off"?!1:b?!0:E==="private"?!w:E==="public"?!k:!1,j=E=>E==="off"||!s?null:b?m?.controlDisabledReason??null:E==="private"&&!w||E==="public"&&!k?"Set a UI password first":null,x=D.useRef(null),P=D.useCallback(E=>{x.current?.querySelector(`[data-mode="${E}"]`)?.focus()},[]),C=D.useCallback(E=>{if(E.key!=="ArrowRight"&&E.key!=="ArrowLeft"&&E.key!=="ArrowUp"&&E.key!=="ArrowDown")return;E.preventDefault();const U=["off","private","public"],_=E.target?.closest("[data-mode]")?.dataset.mode,O=U.includes(_)?_:f,V=U.indexOf(O),H=E.key==="ArrowRight"||E.key==="ArrowDown"?1:-1;for(let ne=1;ne<=U.length;ne+=1){const X=U[(V+H*ne+U.length)%U.length];if(!A(X)){P(X);return}}},[f,i,b,w,k,s]),y=n||!m?e.jsx(St,{tone:"neutral",children:a?"Unknown":"Checking…"}):e.jsx(St,{tone:i&&d?"info":m.tone,children:i&&d?"Saving…":m.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=Wu(o,c);return e.jsxs(ds,{id:"remote-access-tailscale-row",icon:"global",title:"Tailscale",pill:y,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:x,role:"radiogroup","aria-label":"Tailscale mode",className:"flex flex-wrap items-center gap-1",onKeyDown:C,children:Hu.map(E=>{const U=A(E.value),_=j(E.value),O=f===E.value;return e.jsx(S,{type:"button",variant:"chip",size:"xs","data-mode":E.value,role:"radio","aria-checked":O,"aria-label":_?`${E.label} (${_})`:E.label,title:_??void 0,disabled:U,"aria-pressed":void 0,className:"!font-normal",onClick:()=>t.setMode(E.value),children:E.label},E.value)})}),i&&d?e.jsx("p",{className:"typography-meta text-muted-foreground",role:"status",children:"Saving…"}):null,b?null:e.jsx("p",{className:he,children:Gu[f]}),N&&!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:!w&&!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,m?.headline&&m.showUrl!==!0&&!m.showAuthCallout&&!N?e.jsx("p",{className:"typography-ui-label text-foreground",children:m.headline}):null,m?.showUrl&&s?.url?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ro,{url:s.url,copyLabel:"Copy Tailscale address",onOpen:()=>{us(s.url)},openLabel:"Open Tailscale address"}),m?.publicDnsNote==="pending"?e.jsxs("p",{className:"flex items-center gap-2 typography-meta text-muted-foreground",role:"status",children:[e.jsx(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Public link is waiting for DNS. New Funnel links can take 10–15 minutes to work outside your tailnet; devices on your tailnet can connect now."]}):null,m?.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:()=>{us(Vu)},children:["Get Tailscale",e.jsx(R,{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:i,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:i,children:"Check again"})]}):null,m?.showAuthCallout&&!N?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(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}),"Setting up…"]}):null,m?.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:()=>{us(s.approvalUrl)},children:["Approve in Tailscale",e.jsx(R,{name:"external-link",className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null,m?.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:()=>g(Sr),"aria-label":v?"Fix command copied":"Copy fix command",children:e.jsx(R,{name:v?"check":"file-copy",className:F("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:i,children:"Try again"})]}):null,s?.state==="error"&&!m?.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:i,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(Cn,{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(E=>e.jsx(S,{type:"button",variant:"chip",size:"xs",role:"radio","aria-checked":String(s.config.httpsPort)===E,"aria-label":`Port ${E}`,className:"!font-normal",disabled:i,onClick:()=>t.setPort(Number(E)),children:E},E))})]})}):null]}),e.jsx(gt,{open:h,onOpenChange:E=>{E||t.cancelPublicConfirm()},children:e.jsxs(xt,{className:"sm:max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Make PiChamber reachable from the internet?"}),e.jsx(yt,{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"})]})]})})]})},Qu=t=>({...t.lan?{serverUrl:t.lan}:{},includeRelay:t.relayAvailable,includeDirect:!0}),Ju=t=>!t.lan&&!(t.tailscale?.available&&t.tailscale.url)&&!t.relayAvailable,Yu=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},na=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")}`},Xu=(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)},Zu=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"},ep=1e3,tp=(t,s)=>{const[n,a]=D.useState(!1),[r,o]=D.useState(!1),[c,i]=D.useState(!1),[d,h]=D.useState(null),[p,m]=D.useState(null),[u,f]=D.useState(!1),[v,g]=D.useState(null),[b,w]=D.useState(null),[k,N]=D.useState([]),[A,j]=D.useState(null),[x,P]=D.useState(null),[C,y]=D.useState(()=>Date.now()),[L,I]=D.useState(!1),[T,E]=D.useState(null),U=D.useRef(!1),_=D.useRef(0),O=D.useRef(null),V=c?"creating":Zu({expiresAt:b,nowMs:C,hasPayload:!!d,succeeded:L}),H=b?Date.parse(b)-C:Number.NaN,ne=V==="ready"?na(H):null,X=D.useMemo(()=>Yu({candidates:k,lanUrl:A}),[k,A]);D.useEffect(()=>{if(!n||!b||L)return;const re=window.setInterval(()=>{const xe=Date.now();y(xe);const ve=Date.parse(b)-xe,Ne=O.current;if(O.current=ve,Ne!==null&&Xu(ve,Ne)){const K=na(ve);K&&E(K)}},ep);return()=>window.clearInterval(re)},[n,b,L]);const we=D.useCallback(async()=>{if(!t?.createPairingSession){P("Pairing is not available on this server.");return}const re=_.current+1;_.current=re,o(!0),P(null),h(null),m(null),f(!1),g(null),w(null),N([]),I(!1),U.current=!1,O.current=null;try{const xe=await t.getPairingTransports();if(_.current!==re)return;if(j(xe.lan),Ju(xe)){i(!0);return}i(!1);const ve=Qu(xe),{pairing:Ne,server:K}=await t.createPairingSession({allowedClientKinds:["mobile","desktop"],serverUrl:ve.serverUrl,includeRelay:ve.includeRelay,includeDirect:ve.includeDirect});if(_.current!==re){t.cancelPairing&&t.cancelPairing(Ne.id).catch(()=>{});return}const ce=Zo({pairingId:Ne.id,secret:Ne.secret,label:K.label,fingerprint:Ne.fingerprint??void 0,expiresAt:Ne.expiresAt,candidates:K.candidates}),z=el(ce);if(h(z),m(await fi.toDataURL(z,{width:1024,margin:2,errorCorrectionLevel:"L"})),_.current!==re)return;g(Ne.id),w(Ne.expiresAt??null),N(K.candidates),y(Date.now()),O.current=Ne.expiresAt?Date.parse(Ne.expiresAt)-Date.now():null;const J=Ne.expiresAt?na(Date.parse(Ne.expiresAt)-Date.now()):null;E(J)}catch(xe){if(_.current!==re)return;P(xe instanceof Error?xe.message:String(xe))}finally{_.current===re&&o(!1)}},[t]),ie=D.useCallback(()=>{P(null),i(!1),a(!0),we()},[we]),ke=D.useCallback(re=>{!re||!t?.cancelPairing||t.cancelPairing(re).catch(()=>{})},[t]),oe=D.useCallback(()=>{L||ke(v),_.current+=1,a(!1),o(!1),g(null)},[L,v,ke]),ae=D.useCallback(()=>{ke(v),we()},[ke,v,we]),me=D.useCallback(()=>{d&&$s(d).then(re=>{re.ok&&(f(!0),window.setTimeout(()=>f(!1),2e3))})},[d]),le=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)){U.current=!0;return}U.current&&(I(!0),g(null),a(!1),G.some(re=>re.pairingId===v)&&B.success("Device connected."),Pe())}},[n,v,L,Q,G,Pe]),{open:n,phase:V,creating:r,loopbackOnly:c&&n&&!r&&!d,pairingUrl:d,pairingQrDataUrl:p,pairingCopied:u,expiresAt:b,countdownText:ne,announcedCountdownText:T,routeChips:X,error:x,openDialog:ie,closeDialog:oe,regenerate:ae,copyLink:me,scrollToWays:le}},sp=t=>{const[s,n]=D.useState([]),[a,r]=D.useState([]),[o,c]=D.useState(!1),[i,d]=D.useState(null),h=D.useMemo(()=>s.filter(g=>!!g.revokedAt).length,[s]),p=D.useCallback(async g=>{if(t){g?.silent||c(!0),g?.silent||d(null);try{const[b,w]=await Promise.all([t.listClients(),t.listPendingPairings().catch(()=>null)]);n(b),w&&r(w)}catch(b){g?.silent||d(b instanceof Error?b.message:String(b))}finally{g?.silent||c(!1)}}},[t]);D.useEffect(()=>{if(!t)return;p();const g=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||p({silent:!0})},5e3);return()=>window.clearInterval(g)},[t,p]);const m=D.useCallback(async g=>{if(t)try{await t.cancelPairing(g),r(b=>b.filter(w=>w.id!==g)),await p({silent:!0})}catch(b){d(b instanceof Error?b.message:String(b))}},[t,p]),u=D.useCallback(async g=>{if(!t)return;const b=g.clientKind==="desktop-local";d(null);try{if(await t.revokeClient(g.id),b&&Fe()){const w=await qr();await tl({hosts:w.hosts,defaultHostId:w.defaultHostId,initialHostChoiceCompleted:w.initialHostChoiceCompleted,localClientToken:null}),n(k=>k.map(N=>N.id===g.id?{...N,revokedAt:new Date().toISOString()}:N)),ja({apiBaseUrl:ht(),clientToken:null,runtimeKey:"local"});return}await p()}catch(w){d(w instanceof Error?w.message:String(w))}},[t,p]),f=D.useCallback(async()=>{if(t){d(null);try{await t.purgeRevokedClients(),await p()}catch(g){d(g instanceof Error?g.message:String(g))}}},[t,p]),v=D.useCallback(()=>{p({silent:!0})},[p]);return{remoteClients:s,pendingPairings:a,loading:o,error:i,revokedClientCount:h,reload:v,revokeRemoteClient:g=>{u(g)},purgeRevokedRemoteClients:()=>{f()},cancelPendingPairing:g=>{m(g)}}},np=t=>{const[s,n]=l.useState("loading");return l.useEffect(()=>{let a=!1;return(async()=>{try{const r=await ql();if(a)return;if(r.status===401){n("set");return}if(!r.ok){n("unknown");return}const o=await r.json().catch(()=>null);n(o?.disabled===!0?"not-set":"set")}catch{a||n("unknown")}})(),()=>{a=!0}},[t]),s},ap=()=>{const t=np(!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=Fe(),a=n&&ss(),r=Gt()&&!Fe()&&!Me(),o=Lu(),c=sp(s),i=tp(s,c);return e.jsxs(ye,{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:()=>i.openDialog(),children:[e.jsx(R,{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(Ru,{lan:o}),e.jsx(qu,{})]}),s?e.jsx(Iu,{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(Au,{lan:o}):null,a?null:e.jsx(ap,{})]}),r?e.jsx(Su,{}):null,e.jsx(Tu,{addDevice:i,isDesktop:n})]})},rp=({open:t,step:s,onStepChange:n,onClose:a,canScanQr:r,onScanQr:o,onImportLink:c,importSaving:i=!1,importError:d=null,onAddManual:h,manualSaving:p=!1,manualError:m=null})=>{const[u,f]=D.useState(""),[v,g]=D.useState(""),[b,w]=D.useState(""),[k,N]=D.useState(""),[A,j]=D.useState([]);D.useEffect(()=>{t||(f(""),g(""),w(""),N(""),j([]))},[t]);const x=i||p;return s==="menu"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(S,{type:"button",className:"w-full",disabled:x,onClick:()=>n("link"),children:"Paste a pairing link"}),r&&e.jsx(S,{type:"button",variant:"outline",className:"w-full",disabled:x,onClick:()=>o?.(),children:"Scan QR code"}),e.jsx(S,{type:"button",variant:"outline",className:"w-full",disabled:x,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:P=>{P.preventDefault(),c(u)},children:[e.jsx(ee,{className:"h-8",value:u,onChange:P=>f(P.target.value),placeholder:"pichamber://connect?...",disabled:x,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:x,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:x,children:"Cancel"}),e.jsxs(S,{type:"submit",size:"xs",className:"!font-normal",disabled:x||!u.trim(),children:[i?e.jsx(R,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null,"Import link"]})]})]})]}):e.jsxs("form",{className:"space-y-3",onSubmit:P=>{P.preventDefault(),h({label:v,url:b,token:k,headers:A})},children:[e.jsx(ee,{className:"h-8",value:v,onChange:P=>g(P.target.value),placeholder:"Label (optional)",disabled:x}),e.jsx(ee,{className:"h-8",value:b,onChange:P=>w(P.target.value),placeholder:"https://host:port",disabled:x,autoFocus:!0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"h-8",value:k,onChange:P=>N(P.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:x}),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."})]}),A.map(P=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:P.name,onChange:C=>j(y=>y.map(L=>L.id===P.id?{...L,name:C.target.value}:L)),placeholder:"Header name",disabled:x}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:P.value,onChange:C=>j(y=>y.map(L=>L.id===P.id?{...L,value:C.target.value}:L)),placeholder:"Header value",type:"password",disabled:x}),e.jsx("button",{type:"button",onClick:()=>j(C=>C.filter(y=>y.id!==P.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:x,children:e.jsx(R,{name:"close",className:"h-4 w-4","aria-hidden":"true"})})]},P.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>j(P=>[...P,si()]),disabled:x,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5","aria-hidden":"true"}),"Add header"]})]}),m?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:m}):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:x,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:x,children:"Cancel"}),e.jsx(S,{type:"submit",size:"xs",className:"!font-normal",disabled:x||!b.trim(),children:"Add server"})]})]})]})},oo=({open:t,onOpenChange:s,canScanQr:n,onScanQr:a,onImportLink:r,importSaving:o=!1,importError:c=null,onAddManual:i,manualSaving:d=!1,manualError:h=null,initialStep:p="menu"})=>{const[m,u]=D.useState(p);return D.useEffect(()=>{t&&u(p)},[t,p]),e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Add server"}),e.jsx(yt,{children:m==="manual"?"Add another PiChamber server by address. Use this when the server is already running and you have a connection token.":m==="link"?"Paste a pairing link from another PiChamber server.":"Import a pairing link from the other server, or add one by address."})]}),e.jsx(rp,{open:t,step:m,onStepChange:u,onClose:()=>s(!1),canScanQr:n,onScanQr:a,onImportLink:r,importSaving:o,importError:c,onAddManual:i,manualSaving:d,manualError:h})]})})},ip=({open:t,onOpenChange:s,label:n,onLabelChange:a,url:r,onUrlChange:o,token:c,onTokenChange:i,headers:d,onHeadersChange:h,saving:p,error:m=null,onSave:u})=>e.jsx(gt,{open:t,onOpenChange:s,children:e.jsxs(xt,{className:"sm:max-w-lg",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Edit"}),e.jsx(yt,{children:"Servers this app can switch to. Import a pairing link from the other server, or add one by address."})]}),e.jsxs("form",{className:"space-y-3",onSubmit:f=>{f.preventDefault(),u()},children:[e.jsx(ee,{className:"h-8",value:n,onChange:f=>a(f.target.value),placeholder:"Label (optional)",disabled:p}),e.jsx(ee,{className:"h-8",value:r,onChange:f=>o(f.target.value),placeholder:"https://host:port",disabled:p,autoFocus:!0}),e.jsx(ee,{className:"h-8",value:c,onChange:f=>i(f.target.value),placeholder:"Connection token (optional for trusted local servers)",type:"password",disabled:p}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ui,{children:"Additional headers"}),e.jsx(Ds,{children:"Optional HTTP headers for desktop API requests. Authorization is reserved for the connection token."})]}),d.map(f=>e.jsxs("div",{className:"flex w-full gap-2",children:[e.jsx(ee,{className:"h-8 font-mono text-xs",value:f.name,onChange:v=>h(g=>g.map(b=>b.id===f.id?{...b,name:v.target.value}:b)),placeholder:"Header name",disabled:p}),e.jsx(ee,{className:"h-8 font-mono text-xs",value:f.value,onChange:v=>h(g=>g.map(b=>b.id===f.id?{...b,value:v.target.value}:b)),placeholder:"Header value",type:"password",disabled:p}),e.jsx("button",{type:"button",onClick:()=>h(v=>v.filter(g=>g.id!==f.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":"Remove header",disabled:p,children:e.jsx(R,{name:"close",className:"h-4 w-4"})})]},f.id)),e.jsxs(S,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>h(f=>[...f,si()]),disabled:p,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add header"]})]}),m?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:m}):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"})]})]})]})}),op=t=>t.wasLast||t.wasActive,lp=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"},cp=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},dp=async(t,s,n)=>{const a=t.readConnectionCount()<=1,r=await t.removeConnection(s);return r?(op({wasLast:a,wasActive:t.isActive(r)})&&n(),!0):!1},up=t=>`mobile-connect:${t}`,pp=(t,s)=>Yl(up(t),s);function mp(t){const{onConnected:s,onActiveConnectionDeleted:n}=t,a=Di(s),r=Ql(),[o,c]=D.useState(null),i=D.useSyncExternalStore(sl,ms,ms),d=D.useRef(n);d.current=n;const h=D.useRef(a);h.current=a;const p=D.useCallback(async v=>{if(!h.current.connections.some(b=>b.id===v))return!1;c(v);try{return await pp(v,()=>cp(h.current,v)),!0}finally{c(b=>b===v?null:b)}},[]),m=D.useCallback(async v=>dp({connections:h.current.connections,connect:h.current.connect,removeConnection:h.current.removeConnection,readConnectionCount:()=>Ot().length,isActive:g=>an(g)},v,()=>d.current()),[]),u=a.pendingConnection?.id??null;return{items:D.useMemo(()=>{const v=a.connections.map(g=>ld(g,{isCurrent:an(g),status:lp({isCurrent:an(g),relayActive:i,needsLogin:u!==null&&u===g.id,connecting:o!==null&&o===g.id,uncertain:r}),probing:o!==null&&o===g.id}));return Jl(v)},[a.connections,o,u,i,r]),connections:a.connections,isBusy:a.isBusy,isPasswordBusy:a.isPasswordBusy,error:a.error,pendingConnection:a.pendingConnection,connectingId:o,conn:a,connectServer:p,removeServer:m}}const hp=({onConnect:t,onActiveConnectionDeleted:s,showDiagnostics:n=!1,layout:a="sheet"})=>{const r=mp({onConnected:t,onActiveConnectionDeleted:s}),{conn:o,items:c,connectingId:i}=r,{connections:d,isBusy:h,isPasswordBusy:p,error:m,pendingConnection:u,saveConnection:f,setError:v}=o,[g,b]=l.useState(null),w=g?d.find(z=>z.id===g)??null:null,[k,N]=l.useState(""),[A,j]=l.useState(""),[x,P]=l.useState(""),[C,y]=l.useState(""),[L,I]=l.useState(!1),[T,E]=l.useState(!1),[U,_]=l.useState(!1),[O,V]=l.useState(!1),[H,ne]=l.useState(null),X=l.useRef(null),we=l.useMemo(()=>rd(),[]);l.useEffect(()=>{u&&I(!1)},[u]);const ie=l.useCallback(()=>{b(null),N(""),j(""),P(""),v(null)},[v]),ke=l.useCallback(z=>{const J=d.find(te=>te.id===z)??null;J&&(b(z),N(Xt(J)),j(J.label),P(J.clientToken||""),v(null))},[d,v]),oe=l.useCallback(z=>{z.preventDefault(),f({id:g??void 0,url:k,label:A,clientToken:x}).then(J=>{J&&ie()})},[x,g,A,ie,f,k]),ae=l.useCallback(async()=>{if(X.current)return;v(null),E(!0);const z=new AbortController;X.current=z;try{const J=await id({signal:z.signal});switch(X.current===z&&(X.current=null,E(!1)),J.status){case"ok":_(!0),await o.connect({url:J.url,clientToken:J.clientToken,label:J.label});break;case"pairing":_(!0),await o.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),X.current===z&&(X.current=null,E(!1))}},[o,v]);l.useEffect(()=>()=>X.current?.abort(),[]);const me=l.useCallback(z=>{const J=Oi(z.trim());if(!J){v("Invalid PiChamber connection link.");return}if("pairing"in J){o.redeemPairingConnection(J.pairing);return}o.connect({url:J.url})},[o,v]),le=l.useCallback(z=>{if(!z.url.trim()){v("Enter a server URL.");return}o.connect({url:z.url,label:z.label,clientToken:z.token})},[o,v]),Q=l.useCallback(z=>{z.preventDefault(),o.submitPassword(C)},[o,C]),G=l.useCallback(()=>{y(""),o.cancelPassword()},[o]),Pe=l.useCallback(async()=>{if(!O){ne(null),V(!0);try{const z=await nl();ne(z==="copied"?"Diagnostics copied to the clipboard.":z==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{ne("Diagnostics export was cancelled or unavailable.")}finally{V(!1)}}},[O]),re=l.useCallback(()=>{v(null),I(!0)},[v]),xe=l.useCallback(()=>T?(X.current?.abort(),!0):L?(I(!1),!0):w?(ie(),!0):u?(G(),!0):!1,[L,G,w,T,u,ie]);Xr(xe);const ve=cd,Ne=a==="page",K=Ne?void 0:"flex h-full flex-col overflow-hidden",ce=Ne?void 0:"flex-1 overflow-y-auto px-5 py-4";return u?e.jsx("div",{className:K,children:e.jsx("form",{className:ce,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(R,{name:"lock",className:"size-[18px]"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate typography-ui-label text-foreground",children:u.label}),e.jsx("p",{className:"truncate typography-small text-muted-foreground",children:u.candidates.some(z=>z.kind==="direct")?Xt({candidates:u.candidates}):"via PiChamber Relay"})]})]}),e.jsx("input",{...Yn,value:C,onChange:z=>y(z.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:ve}),m?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:m}):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(dd,{onCancel:()=>X.current?.abort()}):null,U?e.jsx(ud,{}):null,e.jsx("div",{className:K,children:e.jsx("div",{className:ce,children:e.jsxs("div",{className:Ne?"space-y-4":"space-y-6",children:[e.jsx(ni,{items:c,layout:"touch",switchLabel:"Connect",pendingId:i,actionsDisabled:h,onSwitch:z=>{r.connectServer(z.id)},onEdit:z=>ke(z.id),onRemove:z=>{r.removeServer(z.id)},emptyMessage:"No saved servers yet."}),m&&!L&&!w?e.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",role:"alert",children:m}):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:O,children:[e.jsx(R,{name:"download",className:"size-[18px]"}),O?"Preparing diagnostics…":"Export diagnostics"]}),H?e.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:H}):null]}):null,w?e.jsxs("form",{className:"space-y-3",onSubmit:oe,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:ie,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",{...Yn,value:k,onChange:z=>N(z.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:ve})]}),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:A,onChange:z=>j(z.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:ve})]}),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",{...Yn,value:x,onChange:z=>P(z.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:ve}),e.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),m?e.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:m}):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:h,children:[e.jsx(R,{name:"add",className:"size-[18px]"}),"Add server"]})})]})})}),e.jsx(oo,{open:L,onOpenChange:z=>{I(z),z||v(null)},canScanQr:we,onScanQr:()=>{ae()},onImportLink:me,importSaving:h,importError:m,onAddManual:le,manualSaving:h,manualError:m})]})},fp=({onActiveConnectionDeleted:t})=>{const{isMobile:s}=lt();return e.jsx(ye,{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(hp,{layout:"page",onConnect:()=>{},onActiveConnectionDeleted:t??(()=>{})})})})},gp=({onActiveConnectionDeleted:t})=>l.useMemo(()=>Me(),[])?e.jsx(fp,{onActiveConnectionDeleted:t}):e.jsx(xp,{}),xp=()=>{const t=Xl(),[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,c]=l.useState(""),[i,d]=l.useState(""),[h,p]=l.useState(""),[m,u]=l.useState([]),f=l.useMemo(()=>t.items.filter(w=>!w.isLocal),[t.items]),v=t.remoteHosts;l.useEffect(()=>{v.length!==0&&t.probeAll(t.allHosts)},[v]);const g=l.useCallback(w=>{const k=t.remoteHosts.find(N=>N.id===w);k&&(r(k),c(k.label),d(k.apiUrl||k.url),p(k.clientToken||""),u(Zl(k.requestHeaders)),t.setError(null))},[t]),b=l.useCallback(async()=>{if(!a)return;(await t.updateServer(a.id,{label:o,url:i,token:h,headers:m})).ok&&r(null)},[a,o,i,h,m,t]);return e.jsxs(ye,{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(R,{name:"add",className:"h-3.5 w-3.5","aria-hidden":!0}),"Add server"]})}),children:[t.loading?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading servers..."}):e.jsx(ni,{items:f,emptyMessage:"No other servers added yet.",refreshing:t.probing,actionsDisabled:t.saving,onSwitch:w=>{t.switchToHost(w.id)},onSetDefault:w=>{t.setDefaultServer(w.id)},onEdit:w=>g(w.id),onRemove:w=>{t.removeServer(w.id)}}),t.error?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:t.error}):null]}),e.jsx(oo,{open:s,onOpenChange:n,canScanQr:!1,onImportLink:async w=>{(await t.importPairingLink(w)).ok&&n(!1)},importSaving:t.saving,importError:t.error,onAddManual:async w=>{(await t.addManualServer(w)).ok&&n(!1)},manualSaving:t.saving,manualError:t.error}),e.jsx(ip,{open:!!a,onOpenChange:w=>{w||r(null)},label:o,onLabelChange:c,url:i,onUrlChange:d,token:h,onTokenChange:p,headers:m,onHeadersChange:u,saving:t.saving,error:t.error,onSave:()=>{b()}})]})},ha=128e3,fa=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 vp(t){let s=!1,n=!1;for(const a of t)n?n=!1:s&&a==="\\"?n=!0:a==='"'&&(s=!s);return s}function ga(t){const s=[];let n=0,a=!1,r=!1;for(let c=0;c<t.length;c+=1){const i=t[c];if(r){r=!1;continue}if(a&&i==="\\"){r=!0;continue}if(i==='"'){a=!a;continue}if(!a&&(i===","||i===`
|
|
8
|
-
`)){const d=t.slice(n,c).trim();d&&s.push(d),n=c+1}}const o=t.slice(n).trim();return o&&s.push(o),s}function bp(t){const s=ga(t??"");if(s.length===0)return{};const n={};for(const a of s){const r=a.indexOf("="),o=r>=0?a.slice(0,r).trim():void 0,c=o?Ir.find(d=>d===o):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 i=a;if(r>=0){const d=a.slice(r+1).trim();if(!d)return{error:"Thinking values cannot be empty"};if(d==="null")i=null;else if(d.startsWith('"'))try{const h=JSON.parse(d);if(typeof h!="string")throw new Error("not a string");i=h}catch{return{error:"Quoted thinking values must be valid strings"}}else i=d}if(i!==null&&i.length>512)return{error:"Thinking values must be 512 characters or fewer"};n[c]=i}return{value:n}}function lo(t){const s=t.modelId.trim(),n=(t.displayName??"").trim(),a=Er(t.contextWindowText),r=Er(t.maxTokensText),o=bp(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"}:{},...o.error?{thinkingLevelMap:o.error}:{},...o.value&&!t.supportsThinking?{thinkingLevelMap:"Enable Supports thinking to add thinking levels"}:{}};if(Object.values(c).some(Boolean))return{errors:c};const i=[...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}:{},...i.length>0?{input:i}:{},...t.supportsThinking?{reasoning:!0}:{},...o.value?{thinkingLevelMap:o.value}:{}}}}const yp="@ai-sdk/openai-compatible",jp=/^[a-z0-9][a-z0-9-_]*$/,wp=/^https?:\/\//,kp=/^\{env:([^}]+)\}$/,Np=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function co(t){return Np.some(s=>s===t)}let Cp=0;const Ba=()=>`row-${Cp++}`,xn=()=>({row:Ba(),advancedOpen:!1,modelId:"",displayName:"",contextWindowText:"",maxTokensText:"",inputText:!1,inputImage:!1,supportsThinking:!1,thinkingLevelMapText:""}),$a=()=>({row:Ba(),key:"",value:""}),Sp=()=>({providerID:"",name:"",baseURL:"",api:"openai-completions",apiKey:"",models:[xn()],headers:[$a()]});function Pp(t){const s=t.trim();if(!s)return{};const a=s.match(kp)?.[1]?.trim();return a?{env:a}:{key:s}}function Tp(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(h=>typeof h[0]=="string"&&typeof h[1]=="string").map(([h,p])=>({row:Ba(),key:h,value:p})),o=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([h,p])=>({...p&&typeof p=="object"&&!Array.isArray(p)?p:{},id:h,name:p&&typeof p=="object"&&"name"in p&&typeof p.name=="string"?p.name:h})):[],c=o.length>0?o.map(h=>({...xn(),modelId:typeof h?.id=="string"?h.id:"",displayName:typeof h?.name=="string"?h.name:"",contextWindowText:h&&"contextWindow"in h&&typeof h.contextWindow=="number"?String(h.contextWindow):"",maxTokensText:h&&"maxTokens"in h&&typeof h.maxTokens=="number"?String(h.maxTokens):"",inputText:!!(h&&"input"in h&&Array.isArray(h.input)&&h.input.includes("text")),inputImage:!!(h&&"input"in h&&Array.isArray(h.input)&&h.input.includes("image")),supportsThinking:!!(h&&("supportsThinking"in h&&h.supportsThinking===!0||"reasoning"in h&&h.reasoning===!0)),thinkingLevelMapText:h&&"thinkingLevelMap"in h&&h.thinkingLevelMap?Object.entries(h.thinkingLevelMap).map(([p,m])=>`${p}=${m===null?"null":JSON.stringify(m)}`).join(`
|
|
9
|
-
`):""})):[xn()],i=Array.isArray(t.env)?t.env.find(h=>typeof h=="string"&&h.trim().length>0)?.trim():void 0,d=typeof t.api=="string"&&co(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:i?`{env:${i}}`:"",models:c,headers:r.length>0?r:[$a()]}}function Ip(t){const s=t.form.providerID.trim(),n=t.form.name.trim(),a=t.form.baseURL.trim(),{env:r,key:o}=Pp(t.form.apiKey),c=t.disabledProviders??[],i=t.editingProviderID?.trim(),d=s?jp.test(s)?void 0:"Use lowercase letters, numbers, hyphens, or underscores":"Provider ID is required",h=n?void 0:"Display name is required",p=a?wp.test(a)?void 0:"Base URL must start with http:// or https://":"Base URL is required",u=!!(r||o||i&&t.allowExistingAuth&&i===s)?void 0:"API key or {env:VAR_NAME} is required",f=c.includes(s),g=d||!!(i&&i===s)?void 0:t.existingProviderIDs.has(s)&&!f?"A provider with this ID is already connected":void 0,b=new Set,w=t.form.models.map(I=>{const T=lo(I),E=I.modelId.trim();return E&&b.has(E)?{errors:{...T.errors,modelId:"Duplicate"}}:(E&&b.add(E),T)}),k=w.map(I=>I.errors),N=w.every(I=>I.result!==void 0),A=Object.fromEntries(w.flatMap(I=>I.result?[[I.result.id,I.result]]:[])),j=new Set,x=t.form.headers.map(I=>{const T=I.key.trim(),E=I.value.trim();return!T&&!E?{}:{key:T?j.has(T.toLowerCase())?"Duplicate":void j.add(T.toLowerCase()):"Required",value:E?void 0:"Required"}}),P=x.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])),y={providerID:d??g,name:h,baseURL:p,apiKey:u};return!d&&!g&&!h&&!p&&!u&&N&&P?{err:y,models:k,headers:x,result:{providerID:s,name:n,apiKey:o,config:{npm:yp,name:n,api:t.form.api,...r?{env:[r]}:{},options:{baseURL:a,...Object.keys(C).length>0?{headers:C}:{}},models:A}}}:{err:y,models:k,headers:x}}const uo=({value:t,onChange:s,disabled:n=!1,hasError:a=!1,id:r})=>{const[o,c]=l.useState(""),i=ga(t),d=()=>{const h=ga(o);if(h.length===0)return;const p=[...i];for(const m of h)p.includes(m)||p.push(m);s(p.join(`
|
|
10
|
-
`)),c("")};return e.jsxs("div",{className:"space-y-2",children:[i.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5","aria-label":"Configured thinking levels",children:i.map(h=>e.jsxs(S,{type:"button",variant:"chip",size:"xs",disabled:n,"aria-label":`Remove ${h}`,onClick:()=>s(i.filter(p=>p!==h).join(`
|
|
11
|
-
`)),children:[e.jsx("span",{className:"font-mono text-xs normal-case",children:h}),e.jsx(R,{name:"close",className:"size-3","aria-hidden":!0})]},h))}):null,e.jsx(ee,{id:r,value:o,onChange:h=>c(h.target.value),onKeyDown:h=>{(h.key==="Enter"||h.key===","&&!vp(o))&&(h.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.'})]})},Ns=({children:t})=>t?e.jsx("p",{role:"alert",className:"mt-1 typography-meta text-[var(--status-error)]",children:t}):null,Ep=({model:t,errors:s,busy:n,removable:a,onChange:r,onRemove:o})=>{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:i=>r("modelId",i.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(Ns,{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:i=>r("displayName",i.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(Ns,{children:s?.displayName})]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:nt,disabled:!a||n,onClick:o,"aria-label":"Remove model",children:e.jsx(R,{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(R,{name:"arrow-down-s",className:F("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:i=>r("contextWindowText",i.target.value,"contextWindow"),placeholder:String(ha),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:n,"aria-invalid":!!s?.contextWindow||void 0}),e.jsx(Ns,{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:i=>r("maxTokensText",i.target.value,"maxTokens"),placeholder:String(fa),inputMode:"numeric",className:"mt-1 h-8 font-mono text-xs",disabled:n,"aria-invalid":!!s?.maxTokens||void 0}),e.jsx(Ns,{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(Ce,{checked:!!t.inputText,onChange:i=>r("inputText",i),label:"Text",ariaLabel:"Text input",disabled:n}),e.jsx(Ce,{checked:!!t.inputImage,onChange:i=>r("inputImage",i),label:"Image",ariaLabel:"Image input",disabled:n})]})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(Ce,{checked:!!t.supportsThinking,onChange:i=>r("supportsThinking",i,"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(uo,{id:`${c}-thinking`,value:t.thinkingLevelMapText??"",onChange:i=>r("thinkingLevelMapText",i,"thinkingLevelMap"),disabled:n||!t.supportsThinking,hasError:!!s?.thinkingLevelMap}),e.jsx(Ns,{children:s?.thinkingLevelMap})]})]})]}):null]})},Ap=({existingProviderIDs:t,disabledProviders:s=[],busy:n=!1,mode:a="create",initialValues:r,allowExistingAuth:o=!1,authFailureHint:c=null,onSubmit:i,onCancel:d,onDisconnect:h})=>{const p=a==="edit",[m,u]=l.useState(()=>r??Sp()),[f,v]=l.useState({}),[g,b]=l.useState([]),[w,k]=l.useState([]),N=l.useRef(null);l.useEffect(()=>{r&&(p&&N.current===r.providerID||(N.current=p?r.providerID:null,u(r),v({}),b([]),k([])))},[r,p]);const A=(C,y)=>{u(L=>({...L,[C]:y})),v(L=>({...L,[C]:void 0}))},j=(C,y,L,I)=>{u(T=>({...T,models:T.models.map((E,U)=>U===C?{...E,[y]:L}:E)})),I&&b(T=>{const E=[...T];return E[C]={...E[C]??{},[I]:void 0},E})},x=(C,y,L)=>{u(I=>({...I,headers:I.headers.map((T,E)=>E===C?{...T,[y]:L}:T)})),k(I=>{const T=[...I];return T[C]={...T[C]??{},[y]:void 0},T})},P=async C=>{if(C.preventDefault(),n)return;const y=Ip({form:m,existingProviderIDs:t,disabledProviders:s,editingProviderID:p?m.providerID:void 0,allowExistingAuth:p&&o});v(y.err),b(y.models),k(y.headers),y.result&&await i(y.result)};return e.jsxs("form",{onSubmit:P,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:mt,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(Rt,{children:[e.jsxs(Ae,{label:"Provider ID",info:"Lowercase letters, numbers, hyphens, and underscores. Used as the Pi provider id.",children:[e.jsx(ee,{value:m.providerID,onChange:C=>A("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":!!f.providerID,"aria-label":"Provider ID"}),f.providerID?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.providerID}):null]}),e.jsxs(Ae,{label:"Display name",info:"Shown in the provider and model pickers.",children:[e.jsx(ee,{value:m.name,onChange:C=>A("name",C.target.value),placeholder:"My provider",className:"h-8 rounded-md px-3","aria-invalid":!!f.name,"aria-label":"Display name"}),f.name?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.name}):null]}),e.jsxs(Ae,{label:"Base URL",info:"Provider API base URL. Must start with http:// or https://.",children:[e.jsx(ee,{value:m.baseURL,onChange:C=>A("baseURL",C.target.value),placeholder:"https://api.example.com/v1",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!f.baseURL,"aria-label":"Base URL"}),f.baseURL?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.baseURL}):null]}),e.jsx(Ae,{label:"API format",info:"Select the request and response format implemented by this provider.",children:e.jsxs(Re,{value:m.api,onValueChange:C=>{co(C)&&u(y=>({...y,api:C}))},disabled:n,children:[e.jsx(De,{size:Be,className:Dt,"aria-label":"API format",children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"openai-completions",children:"OpenAI Chat Completions"}),e.jsx(je,{value:"openai-responses",children:"OpenAI Responses"}),e.jsx(je,{value:"anthropic-messages",children:"Anthropic Messages"}),e.jsx(je,{value:"google-generative-ai",children:"Google Generative AI"})]})]})}),e.jsxs(Ae,{label:"API key",info:p&&o?"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:m.apiKey,onChange:C=>A("apiKey",C.target.value),placeholder:p&&o?"Leave blank to keep existing key":"sk-... or {env:VAR_NAME}",className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":!!f.apiKey,"aria-label":"API key"}),f.apiKey?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:f.apiKey}):null]})]})]}),e.jsxs(q,{title:"Models",contentClassName:mt,children:[m.models.map((C,y)=>e.jsx(Ep,{model:C,errors:g[y],busy:n,removable:m.models.length>1,onChange:(L,I,T)=>j(y,L,I,T),onRemove:()=>{m.models.length<=1||(u(L=>({...L,models:L.models.filter((I,T)=>T!==y)})),b(L=>L.filter((I,T)=>T!==y)))}},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:mt,children:[e.jsx("p",{className:he,children:"Optional request headers sent with every call."}),m.headers.map((C,y)=>e.jsx("div",{className:`${ps} 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=>x(y,"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"}),w[y]?.key?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:w[y]?.key}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,children:"Header value"}),e.jsx(ee,{value:C.value,onChange:L=>x(y,"value",L.target.value),placeholder:"value",className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":"Header value"}),w[y]?.value?e.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:w[y]?.value}):null]})]}),e.jsx(S,{type:"button",variant:"ghost",size:"icon",className:nt,disabled:m.headers.length<=1,onClick:()=>{m.headers.length<=1||(u(L=>({...L,headers:L.headers.filter((I,T)=>T!==y)})),k(L=>L.filter((I,T)=>T!==y)))},"aria-label":"Remove header",children:e.jsx(R,{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,h?e.jsx(S,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{h()},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"})]})]})},st=()=>({runtimeKey:qe()}),Xs="__pi_fallback__",Lp=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},Mp=t=>[...t].sort((s,n)=>s.authenticated!==n.authenticated?s.authenticated?-1:1:s.label.localeCompare(n.label,void 0,{sensitivity:"base"})),Rp=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."},Dp=({open:t,onOpenChange:s,providerId:n,providerLabel:a,onAdded:r,initialAdvancedOpen:o=!1})=>{const[c,i]=l.useState(""),[d,h]=l.useState(""),[p,m]=l.useState(""),[u,f]=l.useState(""),[v,g]=l.useState(!1),[b,w]=l.useState(!1),[k,N]=l.useState(!1),[A,j]=l.useState(""),[x,P]=l.useState(o),[C,y]=l.useState({}),[L,I]=l.useState(null),[T,E]=l.useState(!1);l.useEffect(()=>{t&&(i(""),h(""),m(""),f(""),g(!1),w(!1),N(!1),j(""),P(o),y({}),I(null),E(!1))},[t,n,o]);const U=H=>{T&&!H||s(H)},_=H=>{y(ne=>ne[H]===void 0?ne:{...ne,[H]:void 0})},O=async H=>{if(H.preventDefault(),T)return;const ne=lo({modelId:c,displayName:d,contextWindowText:p,supportsThinking:k,maxTokensText:u,inputText:v,inputImage:b,thinkingLevelMapText:A});y(ne.errors);const X=ne.result;if(!X){(ne.errors.displayName||ne.errors.contextWindow||ne.errors.maxTokens||ne.errors.thinkingLevelMap)&&P(!0),I(null);return}E(!0),I(null);try{const we=await Ue.addProviderModel({providerId:n,model:X},st()),ie=jn(we);ie?B.info(Qt("Model")):B.success("Model added"),s(!1),await r?.({deferred:ie,providerId:n,modelId:X.id})}catch(we){I(Rp(we))}finally{E(!1)}},V=(H,ne,X)=>X?`${H} ${ne}`:H;return e.jsx(gt,{open:t,onOpenChange:U,children:e.jsxs(xt,{className:F(x?"max-w-3xl":"max-w-md","w-full @container p-4 sm:p-6"),children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Add model"}),e.jsx(yt,{children:`Add a manual model to ${a}. Only the Model ID is required.`})]}),e.jsxs("form",{onSubmit:O,className:"@container space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[e.jsx("label",{className: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=>{i(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":x,"aria-controls":"add-model-advanced",onClick:()=>P(H=>!H),className:"w-full justify-between px-0",children:[e.jsx("span",{children:"Advanced settings"}),e.jsx(R,{name:"arrow-down-s",className:F("size-4 transition-transform",x&&"rotate-180"),"aria-hidden":!0})]}),x?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(Ds,{contentClassName:"max-w-xs",children:"Shown in pickers."})]}),e.jsx(ee,{id:"add-model-label",value:d,onChange:H=>{h(H.target.value),_("displayName")},placeholder:"Same as model ID",className:"h-8",disabled:T,"aria-invalid":!!C.displayName||void 0,"aria-describedby":V("add-model-label-hint","add-model-label-error",!!C.displayName),"aria-label":"Display name"}),e.jsx("p",{id:"add-model-label-hint",className:F(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=>{m(H.target.value),_("contextWindow")},placeholder:String(ha),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:T,"aria-invalid":!!C.contextWindow||void 0,"aria-describedby":V("add-model-context-hint","add-model-context-error",!!C.contextWindow),"aria-label":"Context window"}),e.jsx("p",{id:"add-model-context-hint",className:F(he,"mt-1"),children:`Pi uses ${ha.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=>{f(H.target.value),_("maxTokens")},placeholder:String(fa),inputMode:"numeric",className:"h-8 font-mono text-xs",disabled:T,"aria-invalid":!!C.maxTokens||void 0,"aria-describedby":V("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:F(he,"mt-1"),children:`Pi uses ${fa.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(Ds,{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(Ce,{checked:v,onChange:H=>g(H),label:"Text",ariaLabel:"Text input",disabled:T}),e.jsx(Ce,{checked:b,onChange:H=>w(H),label:"Image",ariaLabel:"Image input",disabled:T})]}),e.jsx("p",{id:"add-model-input-hint",className:F(he,"mt-1"),children:"Defaults to text when omitted."})]}),e.jsxs("div",{className:"space-y-2 @xl:col-span-2",children:[e.jsx(Ce,{checked:k,onChange:H=>{N(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(uo,{id:"add-model-thinking-map",value:A,onChange:H=>{j(H),_("thinkingLevelMap")},disabled:T||!k,hasError:!!C.thinkingLevelMap}),e.jsx("p",{id:"add-model-thinking-map-hint",className:F(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(vs,{className:"gap-2",children:[e.jsx(S,{type:"button",variant:"ghost",size:"sm",onClick:()=>U(!1),disabled:T,children:"Cancel"}),e.jsx(S,{type:"submit",size:"sm",disabled:T,children:T?"Adding…":"Add model"})]})]})]})})},_p=({provider:t,onSelect:s})=>{const n=t.models.length,a=n===1?"1 model":`${n} models`,{hasLogo:r}=ec(t.id);return e.jsxs("button",{type:"button",onClick:()=>s(t.id),"aria-label":`${t.label} provider, ${a}${t.authenticated?", authenticated":""}`,className:F("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(ai,{providerId:t.id,className:"size-8 shrink-0 rounded-md object-contain"}):e.jsx("span",{className:"inline-flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground",children:e.jsx(R,{name:"cloud",className:"size-4","aria-hidden":!0})}),t.authenticated?e.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro font-medium text-[var(--status-success)]",children:[e.jsx(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Connected"]}):null]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:t.label}),e.jsx("div",{className:"truncate font-mono typography-micro text-muted-foreground",children:t.id})]}),e.jsxs("div",{className:"flex items-center gap-1.5 typography-micro text-muted-foreground",children:[e.jsx(R,{name:"stack",className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),e.jsx("span",{className:"tabular-nums",children:a})]})]})},zp=({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))}),Cs="__pi_custom_provider__",xa=kc(t=>({selectedProviderId:null,setSelectedProviderId:s=>t(n=>n.selectedProviderId===s?n:{selectedProviderId:s})})),Op=(t,s,n)=>t.some(a=>a.providerID===s&&a.modelID===n),po=l.memo(({providerId:t,model:s,storedLevel:n,isBusy:a,isHidden:r,isConnected:o,onThinkingChange:c,onToggleHidden:i})=>{const d=l.useMemo(()=>ri(s),[s]),p=l.useMemo(()=>ii(d),[d])||n!==void 0,m=l.useMemo(()=>Lp(d,n),[d,n]),u=n??Xs;return e.jsxs("div",{className:F("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(Re,{value:u,onValueChange:f=>c(t,s.id,f===Xs?null:f),disabled:a,children:[e.jsx(De,{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(_e,{children:f=>f===Xs?"Default":f&&oi(f)?un[f]:f??""})}),e.jsxs(ze,{children:[e.jsx(je,{value:Xs,children:"Default"}),m.map(f=>e.jsx(je,{value:f,children:un[f]},f))]})]}):null,s.supportsThinking?e.jsx(R,{name:"brain-ai-3",className:"size-4 shrink-0 text-muted-foreground","aria-label":"Reasoning"}):null,typeof s.contextWindow=="number"?e.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:s.contextWindow}):null,o?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>i(t,s.id),"aria-label":r?"Show model in pickers":"Hide model from pickers",title:r?"Show model in pickers":"Hide model from pickers",children:e.jsx(R,{name:r?"eye":"eye-off",className:"size-4"})}):null]})});po.displayName="ProviderModelRow";const Up=t=>{if(!t)return null;try{const s=new URL(t);return s.protocol==="http:"||s.protocol==="https:"?s:null}catch{return null}},Fp=({login:t,authUrl:s,promptValue:n,onPromptValueChange:a,onSubmit:r,busy:o})=>{const[c,i]=l.useState(!1),d=t.prompt?.placeholder,h=Up(d)!==null,p=n.trim(),m=h&&d&&/^https?:\/\//i.test(p)&&!p.startsWith(d);l.useEffect(()=>{if(!c)return;const v=window.setTimeout(()=>i(!1),2e3);return()=>window.clearTimeout(v)},[c]);const u=async()=>{(await $s(s)).ok?i(!0):B.error("Could not copy the sign-in link")},f=v=>{v.preventDefault(),!(o||p.length===0||m)&&r()};return e.jsxs("div",{className:"space-y-5 border-t border-[var(--surface-subtle)] pt-4",children:[e.jsxs(Ae,{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(R,{name:"external-link",className:"size-4"}),"Open sign-in page"]})}),e.jsx(S,{variant:"ghost",size:"icon",className:nt,onClick:()=>{u()},"aria-label":c?"Sign-in link copied":"Copy sign-in link",title:c?"Copied":"Copy sign-in link",children:e.jsx(R,{name:c?"check":"file-copy",className:"size-4"})})]}),e.jsxs("form",{onSubmit:f,children:[e.jsxs(Ae,{label:h?"2. Paste the redirect URL":"2. Paste the code",description:h?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:h?`${d}?code=…`:t.prompt?.placeholder,"aria-label":h?"Redirect URL":"Authorization code","aria-invalid":m?!0:void 0,autoComplete:"off",spellCheck:!1}),e.jsx(S,{type:"submit",size:"sm",disabled:o||p.length===0||!!m,children:o?"Connecting...":"Connect"})]}),m?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(R,{name:"loader-4",className:"size-4 shrink-0 animate-spin"}),h?"Waiting for sign-in. If your browser runs on the same machine as PiChamber, this finishes on its own.":"Waiting for the code…"]})]})},Bp=t=>{const{login:s,promptValue:n,onPromptValueChange:a,onSubmit:r,busy:o}=t;return s.authUrl&&s.prompt?.type==="manual_code"?e.jsx(Fp,{...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(Ie,{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(Re,{value:n,onValueChange:a,children:[e.jsx(De,{size:Be,className:hs,children:e.jsx(_e,{})}),e.jsx(ze,{children:s.prompt.options.map(c=>e.jsx(je,{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:o||n.length===0,children:"Continue"})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Waiting for authorization…"})]})};function $p(){const t=xa($=>$.selectedProviderId),s=xa($=>$.setSelectedProviderId),n=W($=>$.hiddenModels),a=W($=>$.toggleHiddenModel),r=W($=>$.hideAllModels),o=W($=>$.showAllModels),c=He($=>$.providers),i=He($=>$.settingsDefaultThinkingByModel),d=He($=>$.setSettingsDefaultThinkingByModel),h=He($=>$.setSettingsDefaultThinking),[p,m]=l.useState(null),[u,f]=l.useState(""),[v,g]=l.useState(""),[b,w]=l.useState(null),[k,N]=l.useState(!1),[A,j]=l.useState(null),[x,P]=l.useState(!1),[C,y]=l.useState(!1),[L,I]=l.useState(!1),[T,E]=l.useState(!1),[U,_]=l.useState(null),[O,V]=l.useState(new Set),[H,ne]=l.useState(""),[X,we]=l.useState(80),[ie,ke]=l.useState(null),oe=l.useCallback(async()=>{const{providers:$}=await Ue.listProviders(st());m($),y(!1),He.getState().loadProviders({source:"providersPage:refresh"})},[]),ae=l.useCallback(async()=>{if(!L){I(!0);try{const{providers:$}=await Ue.refreshProviders(st());m($),y(!1);const Y=He.getState();Y.invalidateProviderCache(),Y.loadProviders({source:"providersPage:refreshCatalog"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:$}))}catch{y(!0)}finally{I(!1)}}},[L]),me=l.useCallback(async()=>{if(!T){E(!0),_(null);try{const{providers:$}=await Ue.refreshProviders(st());m($),y(!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{y(!0),_("error"),B.error("Could not refresh model catalog")}finally{E(!1)}}},[T]),le=l.useCallback(async($,Y)=>{if($){ke(Y);return}const de=st();try{const{providers:Z}=await Ue.listProviders(de);if(de.runtimeKey!==qe())return;m(Z),y(!1);const fe=He.getState();fe.invalidateProviderCache(),fe.loadProviders({source:"providersPage:addModel"}),window.dispatchEvent(new CustomEvent("pichamber:providers-refreshed",{detail:Z}))}catch{if(de.runtimeKey!==qe())return;B.error("Model added, but providers could not be refreshed")}},[]);l.useEffect(()=>{!ie||!c.some(Y=>Y.id===ie.providerId&&Y.models.some(de=>de.id===ie.modelId))||(ke(null),le(!1,ie))},[c,ie,le]),l.useEffect(()=>{let $=!0;return oe().catch(()=>{$&&y(!0)}),()=>{$=!1}},[oe]),l.useEffect(()=>{let $=!0;const Y=st();return Ue.getSettings(Y).then(de=>{if(!$||Y.runtimeKey!==qe())return;const Z=de.pichamber.defaultThinkingByModel??{},fe=de.pichamber.defaultThinking,We=He.getState().settingsDefaultThinkingByModel;(()=>{const Qe=Object.keys(We),at=Object.keys(Z);if(Qe.length!==at.length)return!1;for(const Tt of Qe)if(We[Tt]!==Z[Tt])return!1;return!0})()||d(Z),fe!==He.getState().settingsDefaultThinking&&h(fe)}).catch(()=>{}),()=>{$=!1}},[h,d]),l.useEffect(()=>{if(!b||b.state!=="pending")return;let $=!0;const Y=window.setInterval(()=>{Ue.getProviderLogin(b.providerId,b.id,st()).then(de=>{$&&(w(de.login),de.login.state==="complete"&&oe().catch(()=>y(!0)))}).catch(()=>{$&&w(de=>de&&{...de,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})})},1e3);return()=>{$=!1,window.clearInterval(Y)}},[b,oe]),l.useEffect(()=>{if(!b||b.state!=="complete"||!p)return;p.find(Y=>Y.id===b.providerId)?.authenticated===!0&&w(null)},[b,p]),l.useEffect(()=>{const $=Y=>{const de=Y.detail;Array.isArray(de)&&(m(de),y(!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){j(null);return}let $=!0;return Ue.getProviderConfig(G,st()).then(Y=>{$&&j(Y.config)}).catch(()=>{$&&j(null)}),()=>{$=!1}},[G]);const Pe=l.useCallback(async($,Y,de)=>{const Z=pn({providerId:$,modelId:Y});if(!Z)return;const fe=st(),We=He.getState().settingsDefaultThinkingByModel,jt={...We};de===null?delete jt[Z]:jt[Z]=de,d(jt),V(Qe=>new Set(Qe).add(Z)),Te("saving");try{const Qe=await Ue.setPiChamberDefaults({defaultThinkingByModel:{[Z]:de}},fe);if(fe.runtimeKey!==qe()){d(We);return}const at=Qe.pichamber.defaultThinkingByModel??{};d(at),Qe.pichamber.defaultThinking!==void 0&&h(Qe.pichamber.defaultThinking),Te("saved")}catch{fe.runtimeKey===qe()&&d(We),Te("error")}finally{V(Qe=>{const at=new Set(Qe);return at.delete(Z),at})}},[h,d]),re=l.useCallback(($,Y,de)=>{Pe($,Y,de)},[Pe]),xe=l.useCallback(($,Y)=>{a($,Y)},[a]);l.useEffect(()=>{we(80)},[G]);const ve=l.useMemo(()=>Q?Q.models.slice(0,X):[],[Q,X]),Ne=Q?Q.models.length>ve.length:!1,K=l.useMemo(()=>p?Mp(p):[],[p]),ce=l.useMemo(()=>{const $=H.trim().toLowerCase();return $?K.filter(Y=>{const de=Y.label.toLowerCase(),Z=Y.id.toLowerCase();return de.includes($)||Z.includes($)}):K},[K,H]);return{selectedProviderId:t,setSelectedProviderId:s,hiddenModels:n,toggleHiddenModel:a,hideAllModels:r,showAllModels:o,settingsDefaultThinkingByModel:i,setSettingsDefaultThinkingByModel:d,setSettingsDefaultThinking:h,providers:p,setProviders:m,apiKey:u,setApiKey:f,promptValue:v,setPromptValue:g,login:b,setLogin:w,customEditing:k,setCustomEditing:N,providerConfig:A,setProviderConfig:j,busy:x,setBusy:P,failed:C,setFailed:y,refreshing:L,setRefreshing:I,refreshingCatalog:T,setRefreshingCatalog:E,catalogRefreshFeedback:U,setCatalogRefreshFeedback:_,thinkingBusyKeys:O,setThinkingBusyKeys:V,providerQuery:H,setProviderQuery:ne,visibleCap:X,setVisibleCap:we,refresh:oe,refreshProviders:ae,refreshCatalog:me,refreshAfterModelAdd:le,provider:Q,providerId:G,sortedProviders:K,filteredProviders:ce,displayModels:ve,hasMore:Ne,saveCustomProvider:async $=>{P(!0);try{const Y=await Ue.setProviderModels({providerId:$.providerID,label:$.name,baseUrl:$.config.options.baseURL,api:$.config.api,models:Object.values($.config.models).map(de=>({...de,providerId:$.providerID,...de.name?{label:de.name}:{}})),...$.config.options.headers?{headers:$.config.options.headers}:{},...$.config.env?.[0]?{apiKeyReference:`{env:${$.config.env[0]}}`}:{}},st());if(jn(Y)){B.info("Provider configuration saved. Connect it after active sessions are idle.");return}$.apiKey&&w((await Ue.loginProvider({providerId:$.providerID,type:"api_key",apiKey:$.apiKey},st())).login),s($.providerID),N(!1),await oe()}catch(Y){wn(Y)?B.info(Jt("Provider configuration")):y(!0)}finally{P(!1)}},startLogin:async $=>{if(!(!Q||x||$==="api_key"&&u.trim().length===0)){P(!0);try{const Y=await Ue.loginProvider({providerId:Q.id,type:$,...$==="api_key"?{apiKey:u.trim()}:{}},st());f(""),g(""),w(Y.login),Y.login.state==="complete"&&await oe()}catch{w({id:"",providerId:Q.id,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}finally{P(!1)}}},submitPrompt:async()=>{if(!(!b||!b.prompt||v.length===0||x)){P(!0);try{const $=await Ue.respondProviderLogin(b.providerId,b.id,v,st());g(""),w($.login),$.login.state==="complete"&&await oe()}catch{try{const $=await Ue.getProviderLogin(b.providerId,b.id,st());w($.login),$.login.state==="complete"&&await oe()}catch{w($=>$&&{...$,state:"failed",error:{code:"PROVIDER_AUTH_REQUIRED"}})}}finally{P(!1)}}},logout:async()=>{if(!(!Q||x)){P(!0);try{await Ue.logoutProvider({providerId:Q.id},st()),w(null),await oe()}catch{y(!0)}finally{P(!1)}}},handleThinkingChange:re,handleToggleHidden:xe}}const Kp=()=>{const{isMobile:t}=lt(),{selectedProviderId:s,setSelectedProviderId:n,hiddenModels:a,hideAllModels:r,showAllModels:o,settingsDefaultThinkingByModel:c,providers:i,apiKey:d,setApiKey:h,promptValue:p,setPromptValue:m,login:u,customEditing:f,setCustomEditing:v,providerConfig:g,busy:b,failed:w,refreshing:k,refreshingCatalog:N,catalogRefreshFeedback:A,thinkingBusyKeys:j,providerQuery:x,setProviderQuery:P,setVisibleCap:C,refreshProviders:y,refreshCatalog:L,refreshAfterModelAdd:I,provider:T,filteredProviders:E,displayModels:U,hasMore:_,saveCustomProvider:O,startLogin:V,submitPrompt:H,logout:ne,handleThinkingChange:X,handleToggleHidden:we}=$p(),[ie,ke]=l.useState(!1);if(w&&!i)return e.jsx(ye,{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:()=>{y()},disabled:k,children:[e.jsx(R,{name:"refresh",className:F("size-4",k&&"animate-spin")}),k?"Retrying…":"Retry"]})]})});if(f||s===Cs){const ae=g?.providerId===T?.id?g:null,me=ae?Tp({id:ae.providerId,name:ae.label,options:{baseURL:ae.baseUrl},api:ae.api,models:ae.models}):void 0;return e.jsx(ye,{title:ae?"Edit custom provider":"Custom provider",children:e.jsx(Ap,{existingProviderIDs:new Set(i?.map(le=>le.id)??[]),mode:ae?"edit":"create",initialValues:me,allowExistingAuth:T?.authenticated===!0,busy:b,onSubmit:le=>{O(le)},onCancel:()=>{v(!1),n(T?.id??null)}})})}if(T){const ae=u?.providerId===T.id?u:null,me=T.authenticated||ae?.state==="complete";return e.jsxs(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx(ai,{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:[w?e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:"Unavailable"}):null,e.jsxs(q,{title:"Authentication",divider:!1,settingsItem:"providers.auth",headerAction:me?e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{ne()},disabled:b,children:b?"Disconnecting...":"Disconnect"}):null,children:[me?e.jsxs("div",{className:"flex items-center gap-1.5 py-1.5 typography-ui-label",children:[e.jsx(R,{name:"check",className:"size-4 text-[var(--status-success)]"}),"Connected"]}):e.jsxs("div",{className:"space-y-4 py-1.5",children:[e.jsx(Ie,{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:le=>h(le.target.value),placeholder:"sk-...",autoComplete:"off"}),e.jsx(S,{size:"sm",onClick:()=>{V("api_key")},disabled:b||d.trim().length===0,children:b?"Saving...":"Save key"})]})}),e.jsx(S,{variant:"outline",size:"sm",onClick:()=>{V("oauth")},disabled:b,children:"Reconnect"})]}),ae?.state==="pending"?e.jsx(Bp,{login:ae,promptValue:p,onPromptValueChange:m,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:()=>ke(!0),"aria-label":`Add model to ${T.label}`,title:`Add model to ${T.label}`,children:e.jsx(R,{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:N||b,"aria-label":"Refresh model catalog",title:"Refresh model catalog",children:e.jsx(R,{name:"refresh",className:F("size-4",N&&"animate-spin")})}),me?e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>o(T.id),children:"Show all"}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>r(T.id,T.models.map(le=>le.id)),children:"Hide all"})]}):null,g?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:N?"Refreshing model catalog":A==="success"?"Model catalog refreshed":A==="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."}):U.map(le=>{const Q=Op(a,T.id,le.id),G=pn({providerId:T.id,modelId:le.id})??`${T.id}/${le.id}`,Pe=c[G],re=oi(Pe)?Pe:void 0,xe=j.has(G);return e.jsx(po,{providerId:T.id,model:le,storedLevel:re,isBusy:xe,isHidden:Q,isConnected:me,onThinkingChange:X,onToggleHidden:we},le.id)}),_?e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>C(le=>le+80),children:["Show ",Math.min(80,T.models.length-U.length)," more (",U.length," of"," ",T.models.length,")"]})}):null]})]}),e.jsx(Dp,{open:ie,onOpenChange:ke,providerId:T.id,providerLabel:T.label,onAdded:le=>{I(le.deferred,le)}})]})}return i===null?e.jsx(ye,{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:()=>{y()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:F("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(zp,{count:6})})})}):E.length===0&&x.trim()===""&&i.length===0?e.jsx(ye,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:x,onChange:ae=>P(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:()=>{y()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:F("size-4",k&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Cs),children:[e.jsx(R,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"cloud-off",className:"size-8 text-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(Cs),children:"Add custom provider"})]})}):e.jsxs(ye,{title:t?void 0:"Providers",description:t?void 0:"Manage model providers and authentication. Authenticated providers appear first.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:x,onChange:ae=>P(ae.target.value),placeholder:"Search providers","aria-label":"Search providers",className:"h-9 w-[18rem] max-w-full pl-8"}),x?e.jsx("button",{type:"button",onClick:()=>P(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:t?"sm":"icon",onClick:()=>{y()},disabled:k,"aria-label":"Refresh providers",title:"Refresh providers",children:e.jsx(R,{name:"refresh",className:F("size-4",k&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>n(Cs),children:[e.jsx(R,{name:"add",className:"size-4"}),"Add custom provider"]})]}),children:[w?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:E.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-center",children:[e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["No providers match “",x,"”."]}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>P(""),children:"Clear search"})]}):e.jsxs("div",{className:"grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3",children:[E.map(ae=>e.jsx(_p,{provider:ae,onSelect:n},ae.id)),e.jsxs("button",{type:"button",onClick:()=>n(Cs),"aria-label":"Add custom provider",className:F("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"Add custom provider"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"OpenAI-compatible"})]})]})})]})},Vp=({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",o=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:F("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:F("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,o?"…":null]})]})]})},mo=({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))}),Hp=t=>t.split(/[,\s]+/).map(s=>s.trim()).filter(s=>s.length>0),Gp=()=>{const{isMobile:t}=lt(),s=Ca(),n=it(z=>z.selectedSnippetId),a=it(z=>z.snippetDraft),r=it(z=>z.snippets),o=it(z=>z.isLoading),c=it(z=>z.setSelectedSnippet),i=it(z=>z.setSnippetDraft),d=it(z=>z.createSnippet),h=it(z=>z.updateSnippet),p=it(z=>z.deleteSnippet),m=it(z=>z.loadSnippets),u=l.useMemo(()=>n?r.find(z=>z.id===n)??null:null,[n,r]),f=!!(a&&!u),[v,g]=l.useState(""),[b,w]=l.useState("global"),[k,N]=l.useState(""),[A,j]=l.useState(""),[x,P]=l.useState(""),[C,y]=l.useState(!1),[L,I]=l.useState(!1),[T,E]=l.useState(!1),U=l.useRef(""),_=l.useRef(""),O=l.useRef(""),V=l.useRef(""),H=l.useRef("global");l.useEffect(()=>{f&&a?(g(a.name),w(a.scope),N(a.description??""),j(""),P(a.content??""),U.current=a.content??"",_.current=a.description??"",O.current=a.name,V.current="",H.current=a.scope):u&&(g(u.name),w(u.source),N(u.description??""),j((u.aliases??[]).join(", ")),P(u.content),U.current=u.content,_.current=u.description??"",O.current=u.name,V.current=(u.aliases??[]).join(", "),H.current=u.source)},[a,f,u]);const ne=l.useCallback(()=>{f&&i(null),c(null)},[f,c,i]),X=l.useCallback(async()=>{const z=v.trim().replace(/\s+/g,"-");if(!z){B.error("Snippet name is required");return}if(!/^[a-z0-9_-]+$/i.test(z)){B.error("Snippet name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){B.error("Snippet content is required");return}const J=Hp(A);if(J.length>10){B.error("Snippets support at most 10 aliases");return}for(const et of J)if(!/^[a-z0-9_-]+$/i.test(et)){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}y(!0);const te=f?await d(z,x,{description:k,aliases:J,scope:b,directory:s}):await h(u?.id??"",{name:z!==O.current?z:void 0,content:x!==U.current?x:void 0,description:k!==_.current?k:void 0,aliases:A.trim()!==V.current.trim()?J:void 0,...b!==H.current?{scope:b,...b==="project"&&s?{directory:s}:{}}:{}},s);y(!1),te?(f||i(null),B.success(f?"Snippet created":"Snippet updated")):B.error(f?"Failed to create snippet":"Failed to update snippet")},[A,x,d,k,s,f,v,b,u?.id,i,h]),we=l.useCallback(async()=>{if(!u)return;I(!0);const z=await p(u.id,s);I(!1),z?(B.success("Snippet deleted"),E(!1)):B.error("Failed to delete snippet")},[p,s,u]),[ie,ke]=l.useState(""),[oe,ae]=l.useState("all"),[me,le]=l.useState(!1),Q=l.useCallback(async()=>{if(!me){le(!0);try{const{invalidateSnippetsLoadCache:z}=await Yt(async()=>{const{invalidateSnippetsLoadCache:J}=await import("./useAppFontEffects-CV5UyTRw.js").then(te=>te.e$);return{invalidateSnippetsLoadCache:J}},__vite__mapDeps([10,4,5,1,6,2,7,8,9,0,11,3]));z(s),await m(s)}finally{le(!1)}}},[s,m,me]);l.useEffect(()=>{m(s)},[s,m]);const G=l.useMemo(()=>[...r].sort((z,J)=>z.name.localeCompare(J.name)),[r]),Pe=l.useMemo(()=>{let z=G;oe!=="all"&&(z=z.filter(te=>te.source===oe));const J=ie.trim().toLowerCase();return J?z.filter(te=>{const et=te.name.toLowerCase().includes(J),$=(te.description??"").toLowerCase().includes(J),Y=te.content.toLowerCase().includes(J),de=(te.aliases??[]).some(Z=>Z.toLowerCase().includes(J));return et||$||Y||de}):z},[G,oe,ie]),re=l.useMemo(()=>{let z=0,J=0;for(const te of r)te.source==="project"?J+=1:z+=1;return{all:r.length,global:z,project:J}},[r]),xe=l.useCallback(async()=>{const z=new Set(r.map(et=>et.name.toLowerCase()));let J="new-snippet",te=1;for(;z.has(J.toLowerCase());)J=`new-snippet-${te++}`;i({name:J,scope:"global",content:"",description:""}),c(null)},[c,i,r]),ve=it(z=>z.snippetsFile),Ne=l.useCallback(async()=>{if(!ve)return;(await $s(ve)).ok?B.success("Snippets file path copied"):B.error("Could not copy the path")},[ve]),K=ve?e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Ne()},"aria-label":"Copy snippets file path",title:`Copy snippets file path: ${ve}`,children:e.jsx(R,{name:"file-copy",className:"size-4"})}):null;if(n!==null||a){if(!u&&!f)return e.jsx(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:"Not found"})]}),description:"This snippet no longer exists.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"file-text",className:"size-8 text-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 z=f?v.trim()!==O.current||k!==_.current||x!==U.current||A.trim()!==V.current.trim()||b!==H.current:v.trim()!==O.current||x!==U.current||k!==_.current||A.trim()!==V.current.trim()||b!==H.current,J=z&&!C&&x.trim().length>0&&v.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New snippet":`#${u?.name??v}`})]}),description:f?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:!f&&u?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>E(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(R,{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=>g(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(Re,{value:b,onValueChange:te=>w(te),children:[e.jsx(De,{size:Be,className:"w-full",children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"global",children:"Global"}),e.jsx(je,{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=>N(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:A,onChange:te=>j(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:z?"Unsaved changes":"No changes"}),children:[e.jsx(Tn,{value:x,onChange:P,initialMode:f?"write":"preview",triggerPreview:`#${v.trim()||"name"}`},f?"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:()=>{X()},disabled:!J,children:C?"Saving…":f?"Create snippet":"Save changes"})]})]}),!f&&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:()=>E(!0),disabled:L,children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(gt,{open:T,onOpenChange:te=>!te&&E(!1),children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Delete snippet?"}),e.jsxs(yt,{children:["This will permanently delete #",u?.name??"",". This cannot be undone."]})]}),e.jsxs(vs,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>E(!1),disabled:L,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{we()},disabled:L,children:L?"Deleting…":"Delete"})]})]})})]})}if(o&&r.length===0)return e.jsx(ye,{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:[K,e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:me,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(R,{name:"refresh",className:F("size-4",me&&"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(mo,{count:6})})})});const ce=Pe.length===0&&r.length===0;return e.jsx(ye,{title:t?void 0:"Snippets",description:t?void 0:"Text snippets that expand as #name in the composer.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:ie,onChange:z=>ke(z.target.value),placeholder:"Search snippets","aria-label":"Search snippets",className:"h-9 w-[15rem] max-w-full pl-8"}),ie?e.jsx("button",{type:"button",onClick:()=>ke(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),K,e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:me,"aria-label":"Refresh snippets",title:"Refresh snippets",children:e.jsx(R,{name:"refresh",className:F("size-4",me&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{xe()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New snippet"]})]}),children:ce?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(R,{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:()=>{xe()},children:[e.jsx(R,{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":oe==="all",onClick:()=>ae("all"),children:["All ",re.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":oe==="project",onClick:()=>ae("project"),children:["Project ",re.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":oe==="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:ie.trim()?`No snippets match “${ie}”.`:`No ${oe} snippets.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{ke(""),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(z=>e.jsx(Vp,{snippet:z,onSelect:c,showSourcePill:oe==="all"},`${z.source}:${z.id}`)),e.jsxs("button",{type:"button",onClick:()=>{xe()},"aria-label":"Create new snippet",className:F("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New snippet"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Reusable text expansion"})]})]})]})})};function ho(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 Wp(t){return`$${ho(t)+1}`}function qp(t){const s=ho(t);return s<1?null:`\${@:${s+1}}`}function Qp(t){const s=Wp(t),n=qp(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 Jp=async({previousName:t,nextName:s,previousLocation:n,nextLocation:a})=>{const r=dn.getState(),o=r.projects.find(g=>g.id===r.activeProjectId),c=o?.path?{id:o.id,path:o.path}:null,i=W.getState().globalDraftStarters??[],d=c?await sc(c):[];if(!(n==="project"?d:i).some(g=>g.type==="prompt"&&g.name===t))return!0;if(a==="project"&&!c)return!1;const m=g=>g.filter(b=>!(b.type==="prompt"&&b.name===t));let u=n==="global"?m(i):i,f=n==="project"?m(d):d;const v={type:"prompt",name:s,scope:a};return a==="project"?f.some(g=>g.type==="prompt"&&g.name===s)||(f=[...f,v]):u.some(g=>g.type==="prompt"&&g.name===s)||(u=[...u,v]),JSON.stringify(u)!==JSON.stringify(i)&&(W.getState().setGlobalDraftStarters(u),await Ke({draftStarters:u})),c&&JSON.stringify(f)!==JSON.stringify(d)?nc(c,f):!0},Yp=()=>{const{isMobile:t}=lt(),s=Ca(),n=ct(K=>K.selectedPromptId),a=ct(K=>K.promptDraft),r=ct(K=>K.prompts),o=ct(K=>K.isLoading),c=ct(K=>K.setSelectedPrompt),i=ct(K=>K.setPromptDraft),d=ct(K=>K.createPrompt),h=ct(K=>K.updatePrompt),p=ct(K=>K.deletePrompt),m=ct(K=>K.loadPrompts),u=l.useMemo(()=>n?r.find(K=>K.id===n)??null:null,[r,n]),f=!!(a&&!u),v=f||u?.editable===!0,g=!f&&u&&u.editable!==!0,[b,w]=l.useState(""),[k,N]=l.useState("global"),[A,j]=l.useState(""),[x,P]=l.useState(""),[C,y]=l.useState(!1),[L,I]=l.useState(!1),[T,E]=l.useState(!1),U=l.useRef(""),_=l.useRef(""),O=l.useRef(""),V=l.useRef("global");l.useEffect(()=>{f&&a?(w(a.name),N(a.location),j(a.description??""),P(a.content??""),U.current=a.name,_.current=a.description??"",O.current=a.content??"",V.current=a.location):u&&(w(u.name),N(u.location==="project"?"project":"global"),j(u.description??""),P(u.content??""),U.current=u.name,_.current=u.description??"",O.current=u.content??"",V.current=u.location==="project"?"project":"global")},[a,f,u]);const H=l.useCallback(()=>{f&&i(null),c(null)},[f,i,c]),ne=l.useCallback(async()=>{const K=b.trim().replace(/\s+/g,"-");if(!K){B.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(K)){B.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){B.error("Prompt content is required");return}if(k==="project"&&!s?.trim()){B.error("Project prompts need an active project directory");return}y(!0);const ce=await d(K,x,{description:A,location:k,directory:s});y(!1),ce==="busy"?B.info(Jt(`Prompt /${K}`)):ce==="deferred"?B.info(Qt(`Prompt /${K}`)):ce?B.success(`Prompt /${K} created`):B.error("Failed to create prompt template")},[x,d,A,s,k,b]),X=l.useCallback(async()=>{if(!u)return;const K=b.trim().replace(/\s+/g,"-");if(!K){B.error("Prompt name is required");return}if(!/^[a-z0-9_-]+$/i.test(K)){B.error("Prompt name may only contain letters, numbers, dashes and underscores");return}if(!x.trim()){B.error("Prompt content is required");return}if(k==="project"&&!s?.trim()){B.error("Project prompts need an active project directory");return}y(!0);const ce=U.current,z=V.current,J=await h(u.id,{...K!==U.current?{name:K}:{},...A!==_.current?{description:A}:{},...x!==O.current?{content:x}:{},...k!==V.current?{location:k}:{}},s);if(y(!1),J==="busy")B.info(Jt(`Prompt /${K}`));else if(J){let te=!0;if(ce&&(K!==ce||k!==z))try{te=await Jp({previousName:ce,nextName:K,previousLocation:z,nextLocation:k})}catch{te=!1}J==="deferred"?B.info(Qt(`Prompt /${K}`)):B.success(`Prompt /${K} 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")},[x,A,s,k,b,u,h]),we=l.useCallback(async()=>{if(!u)return;I(!0);const K=await p(u.id,s);I(!1),K==="busy"?B.info(Jt("Prompt template")):K==="deferred"?(B.info(Qt("Prompt template")),E(!1)):K?(B.success("Prompt template deleted"),E(!1)):B.error("Failed to delete prompt template")},[p,s,u]),[ie,ke]=l.useState(""),[oe,ae]=l.useState("all"),[me,le]=l.useState(!1),Q=l.useCallback(async()=>{if(!me){le(!0);try{tc(s),await m(s)}finally{le(!1)}}},[s,m,me]);l.useEffect(()=>{m(s)},[s,m]);const G=l.useMemo(()=>[...r].sort((K,ce)=>K.name.localeCompare(ce.name)),[r]),Pe=l.useMemo(()=>{let K=G;oe!=="all"&&(K=K.filter(z=>z.location===oe));const ce=ie.trim().toLowerCase();return ce?K.filter(z=>z.name.toLowerCase().includes(ce)||(z.description??"").toLowerCase().includes(ce)||(z.content??"").toLowerCase().includes(ce)):K},[oe,ie,G]),re=l.useMemo(()=>{let K=0,ce=0;for(const z of r)z.location==="project"?ce+=1:z.location==="global"&&(K+=1);return{all:r.length,global:K,project:ce}},[r]),xe=l.useMemo(()=>Qp(x),[x]),ve=l.useCallback(()=>{const K=new Set(r.map(J=>J.name.toLowerCase()));let ce="new-prompt",z=1;for(;K.has(ce.toLowerCase());)ce=`new-prompt-${z++}`;i({name:ce,location:"global"}),c(null)},[r,i,c]);if(n!==null||a){if(!u&&!f)return e.jsx(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:"Not found"})]}),description:"This prompt template no longer exists.",children:e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-12 text-center",children:[e.jsx(R,{name:"terminal",className:"size-8 text-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 K=u?.location==="project"?"Project":u?.location==="global"?"Global":u?.location??"Global",z=b.trim().replace(/\s+/g,"-")!==U.current||A!==_.current||x!==O.current||k!==V.current,J=z&&!C&&x.trim().length>0&&b.trim().length>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ye,{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(R,{name:"arrow-left-s",className:"size-4"})}),e.jsx("span",{className:"truncate",children:f?"New prompt template":`/${u?.name??b}`})]}),description:f?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:!f&&u?.editable===!0?e.jsxs(S,{variant:"ghost",size:"xs",onClick:()=>E(!0),className:"text-destructive hover:text-destructive",children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]}):null,children:[f?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=>w(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(Re,{value:k,onValueChange:te=>N(te),children:[e.jsx(De,{size:Be,className:"w-full",children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"global",children:"Global"}),e.jsx(je,{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:A,onChange:te=>j(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:F("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:K}),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(R,{name:"check",className:"size-3.5","aria-hidden":!0}),"Editable"]}):e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-muted px-2.5 py-1 font-medium text-muted-foreground",children:"Read-only"})]}),g?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(Re,{value:k,onValueChange:te=>N(te),children:[e.jsx(De,{size:Be,className:"w-full","aria-label":"Prompt template scope",children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"global",children:"Global"}),e.jsx(je,{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=>w(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:A,onChange:te=>j(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:z?"Unsaved changes":"No changes"}):void 0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Tn,{value:x,onChange:P,initialMode:f?"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:xe},f?"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:()=>{f?H():(w(U.current),N(V.current),j(_.current),P(O.current))},children:"Cancel"}),e.jsx(S,{size:"sm",onClick:()=>{f?ne():X()},disabled:!J,children:C?"Saving…":f?"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."})})}),!f&&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:()=>E(!0),disabled:L,children:[e.jsx(R,{name:"delete-bin",className:"size-4"}),"Delete"]})]})}):null]}),e.jsx(gt,{open:T,onOpenChange:te=>!te&&E(!1),children:e.jsxs(xt,{className:"max-w-md",children:[e.jsxs(vt,{children:[e.jsx(bt,{children:"Delete prompt?"}),e.jsxs(yt,{children:["This will permanently delete /",u?.name??"",". This cannot be undone."]})]}),e.jsxs(vs,{children:[e.jsx(S,{variant:"ghost",size:"sm",onClick:()=>E(!1),disabled:L,children:"Cancel"}),e.jsx(S,{variant:"destructive",size:"sm",onClick:()=>{we()},disabled:L,children:L?"Deleting…":"Delete"})]})]})})]})}if(o&&r.length===0)return e.jsx(ye,{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:me,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(R,{name:"refresh",className:F("size-4",me&&"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(mo,{count:6})})})});const Ne=Pe.length===0&&r.length===0;return e.jsx(ye,{title:t?void 0:"Prompt templates",description:t?void 0:"Native Pi commands that run as /name with Pi argument expansion.",headerEnd:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-0 max-w-full",children:[e.jsx(R,{name:"search",className:"pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),e.jsx(ee,{value:ie,onChange:K=>ke(K.target.value),placeholder:"Search prompt templates","aria-label":"Search prompt templates",className:"h-9 w-[18rem] max-w-full pl-8"}),ie?e.jsx("button",{type:"button",onClick:()=>ke(""),"aria-label":"Clear search",className:"absolute right-1 top-1/2 inline-flex size-7 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:e.jsx(R,{name:"close",className:"size-4"})}):null]}),e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>{Q()},disabled:me,"aria-label":"Refresh prompt templates",title:"Refresh prompt templates",children:e.jsx(R,{name:"refresh",className:F("size-4",me&&"animate-spin")})}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>{ve()},children:[e.jsx(R,{name:"add",className:"size-4"}),"New prompt"]})]}),children:Ne?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(R,{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:()=>{ve()},children:[e.jsx(R,{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":oe==="all",onClick:()=>ae("all"),children:["All ",re.all]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":oe==="project",onClick:()=>ae("project"),children:["Project ",re.project]}),e.jsxs(S,{variant:"chip",size:"xs","aria-pressed":oe==="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:ie.trim()?`No prompt templates match “${ie}”.`:`No ${oe} prompt templates.`}),e.jsx(S,{variant:"ghost",size:"xs",onClick:()=>{ke(""),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(K=>{const ce=K.editable===!0,z=K.location==="project"?"Project":K.location==="global"?"Global":K.location,J=K.description?.trim()||(K.content??"").replace(/\s+/g," ").trim().slice(0,140)||"No description";return e.jsxs("button",{type:"button",onClick:()=>c(K.id),"aria-label":`${K.name} prompt template, ${z}${ce?"":", read-only"}`,className:F("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:F("inline-flex shrink-0 items-center rounded-full px-2 py-0.5 typography-micro font-medium capitalize",K.location==="project"?"bg-[var(--primary-base)]/10 text-[var(--primary-base)]":"bg-muted text-muted-foreground"),children:z}),ce?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:["/",K.name]}),e.jsx("div",{className:"mt-1 line-clamp-2 typography-micro text-muted-foreground",children:J})]})]},K.id)}),e.jsxs("button",{type:"button",onClick:()=>{ve()},"aria-label":"Create new prompt template",className:F("group flex min-h-[118px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed p-4","border-border/60 bg-transparent text-muted-foreground","hover:border-border hover:bg-interactive-hover hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","transition-colors duration-150"),children:[e.jsx("span",{className:"inline-flex size-9 items-center justify-center rounded-full bg-muted",children:e.jsx(R,{name:"add",className:"size-5"})}),e.jsx("span",{className:"typography-ui-label font-medium",children:"New prompt"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Native / command"})]})]})]})})},Ka=()=>{const t=al(),s=W(i=>i.gitChangesViewMode),n=W(i=>i.setGitChangesViewMode),[a,r]=l.useState(!0),o=l.useMemo(()=>[{id:"flat",label:"Flat list"},{id:"tree",label:"Tree view"}],[]);l.useEffect(()=>{(async()=>{try{let d=null;if(!d){const h=wa()?.settings;if(h)try{const m=(await h.load())?.settings;m&&(d={gitChangesViewMode:m.gitChangesViewMode==="flat"||m.gitChangesViewMode==="tree"?m.gitChangesViewMode:void 0})}catch{}}if(!d){const h=await Ee("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});h.ok&&(d=await h.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(i=>{i!==s&&(n(i),Ke({gitChangesViewMode:i}))},[s,n]);return a?null:e.jsxs(e.Fragment,{children:[e.jsx(q,{title:"Git preferences",divider:!1,children:e.jsxs("div",{className:ft,children:[e.jsx(ot,{settingsItem:"git.changes-view",title:"Changes view",children:e.jsx(Zt,{"aria-label":"Git changes view mode",children:o.map(i=>e.jsx(fs,{selected:s===i.id,onSelect:()=>{c(i.id)},label:i.label,ariaLabel:`Git changes view mode: ${i.label}`},i.id))})}),e.jsx(Ce,{settingsItem:"git.gitignored-files",checked:t,onChange:rl,label:"Display gitignored files",ariaLabel:"Display gitignored files"})]})}),e.jsx(Xp,{})]})},Xp=()=>{const s=kn().github??null,n=Wn(d=>d.status),a=Wn(d=>d.isLoading),r=Wn(d=>d.refresh);l.useEffect(()=>{s&&r(s)},[s,r]);const o=l.useCallback(()=>{s&&r(s,{force:!0})},[s,r]),c=l.useCallback(d=>{$s(d).then(h=>{B[h.ok?"success":"error"](h.ok?"Command copied":"Failed to copy command")}).catch(()=>B.error("Failed to copy command"))},[]),i=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:mt,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(Ie,{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"})}),i.length===0?e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-account",children:"No signed-in hosts. Run gh auth login on the machine running PiChamber, then check again."}):i.map(d=>e.jsx(Ie,{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(R,{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:o,disabled:a,children:[e.jsx(R,{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:o,children:[e.jsx(R,{name:"refresh",className:"size-3.5"}),"Check again"]})]}):e.jsx("p",{className:"typography-ui text-muted-foreground","data-settings-item":"git.github-status",children:"GitHub is not available in this runtime."}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"git push uses your normal git credentials. PiChamber never changes git or gh configuration."})]})})},Ar=()=>{const t=Ac();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},Zp=()=>{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},em=[{value:"system",label:"System",description:"Follow system setting"},{value:"light",label:"Light",description:"Always use light appearance"},{value:"dark",label:"Dark",description:"Always use dark appearance"}],tm=[{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."}],Ps="PiChamber - AI Coding Assistant",fo=[{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."}],go=[{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."}],sm=[{value:"default",label:"Old"},{value:"new",label:"New"}],va=t=>t==="portrait"||t==="landscape"?t:"system",xo=[{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."}],vo=[{id:"auto",label:"Auto",description:"Use locale week start."},{id:"monday",label:"Monday"},{id:"sunday",label:"Sunday"}],nm=[{id:"workspace",label:"Workspace"},{id:"folder",label:"By folder"},{id:"threads",label:"Threads"}],Lr=[{id:"timeline",label:"Timeline"}],am={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."},rm=[{id:"steer",label:"Steering"},{id:"queue",label:"Follow-up"}],Zs=l.memo(function({theme:s}){return e.jsxs("div",{"data-theme-preview":s.metadata.id,className:"flex h-full w-full",style:{backgroundColor:s.colors.surface.background},children:[e.jsxs("div",{className:"flex w-[38%] shrink-0 flex-col gap-[4px] overflow-hidden border-r p-[5px]",style:{backgroundColor:s.colors.surface.muted,borderColor:s.colors.interactive.border},children:[e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",style:{backgroundColor:s.colors.interactive.selection},children:e.jsx("div",{className:"h-[3px] w-[70%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})}),e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",children:e.jsx("div",{className:"h-[3px] w-[85%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})}),e.jsx("div",{className:"flex items-center rounded-[3px] px-[3px] py-[3px]",children:e.jsx("div",{className:"h-[3px] w-[55%] rounded-full opacity-60",style:{backgroundColor:s.colors.surface.foreground}})})]}),e.jsxs("div",{className:"flex min-w-[0px] flex-1 flex-col gap-[4px] overflow-hidden p-[6px]",children:[e.jsx("div",{className:"h-[3px] w-[80%] rounded-full opacity-70",style:{backgroundColor:s.colors.surface.foreground}}),e.jsx("div",{className:"h-[3px] w-[55%] rounded-full opacity-40",style:{backgroundColor:s.colors.surface.foreground}}),e.jsxs("div",{className:"flex items-center gap-[3px]",children:[e.jsx("div",{className:"h-[3px] w-[18%] rounded-full",style:{backgroundColor:s.colors.syntax.base.keyword}}),e.jsx("div",{className:"h-[3px] w-[30%] rounded-full",style:{backgroundColor:s.colors.syntax.base.string}}),e.jsx("div",{className:"h-[3px] w-[22%] rounded-full",style:{backgroundColor:s.colors.syntax.base.function}})]}),e.jsx("div",{className:"mt-auto flex h-[11px] items-center justify-end rounded-[3px] border px-[2px]",style:{backgroundColor:s.colors.surface.elevated,borderColor:s.colors.interactive.border},children:e.jsx("div",{className:"h-[5px] w-[9px] rounded-full",style:{backgroundColor:s.colors.primary.base}})})]})]})}),im=({mode:t,lightTheme:s,darkTheme:n})=>e.jsxs("div",{"data-color-mode-preview":t,className:"relative h-full w-full",children:[t==="light"&&s&&e.jsx(Zs,{theme:s}),t==="dark"&&n&&e.jsx(Zs,{theme:n}),t==="system"&&e.jsxs(e.Fragment,{children:[s&&e.jsx(Zs,{theme:s}),n&&e.jsx("div",{className:"absolute inset-0 [clip-path:polygon(100%_0,100%_100%,0_100%)]",children:e.jsx(Zs,{theme:n})})]})]}),en=({theme:t})=>e.jsxs("span",{"aria-hidden":!0,"data-theme-swatch":t.metadata.id,className:"inline-flex h-[16px] w-[30px] shrink-0 items-center justify-center gap-[3px] rounded-[4px] border",style:{backgroundColor:t.colors.surface.background,borderColor:t.colors.interactive.border},children:[e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.primary.base}}),e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.syntax.base.keyword}}),e.jsx("span",{className:"h-[6px] w-[6px] rounded-full",style:{backgroundColor:t.colors.syntax.base.string}})]}),om=({themeMode:t,setThemeMode:s,showMobileLayoutSetting:n,mobileLayoutPreference:a,onMobileLayoutPreferenceChange:r,selectedLightTheme:o,setLightThemePreference:c,lightThemes:i,selectedDarkTheme:d,setDarkThemePreference:h,darkThemes:p,formatThemeLabel:m,customThemesLoading:u,themesReloading:f,setThemesReloading:v,reloadCustomThemes:g,dockBadgeSupported:b,dockBadgeEnabled:w,setDockBadgeEnabled:k})=>e.jsxs(q,{title:"Color mode & theme",divider:!1,contentClassName:"space-y-4",children:[e.jsx(ot,{title:"Color mode",children:e.jsx(Zt,{"aria-label":"Color mode",className:"grid max-w-[30rem] grid-cols-3 gap-2 space-y-0 @xl:gap-3",children:em.map(N=>e.jsx(pi,{selected:t===N.value,onSelect:()=>s(N.value),label:N.label,ariaLabel:N.label,preview:e.jsx(im,{mode:N.value,lightTheme:o,darkTheme:d})},N.value))})}),n&&e.jsx(Ae,{label:"Mobile layout",children:e.jsx(Nn,{value:a,options:sm.map(N=>({value:N.value,label:N.label})),onChange:r,"aria-label":"Mobile layout"})}),e.jsxs(Rt,{className:"gap-4 @md:grid-cols-2 @md:gap-8 @3xl:gap-10",children:[e.jsx(Ae,{label:"Light theme",settingsItem:"appearance.light-theme",children:e.jsxs(Re,{value:o?.metadata.id??"",onValueChange:c,children:[e.jsx(De,{"aria-label":"Select light theme",size:Be,className:Dt,children:e.jsx(_e,{placeholder:"Select theme",children:o?e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(en,{theme:o}),e.jsx("span",{className:"truncate",children:m(o.metadata.name,"light")})]}):void 0})}),e.jsx(ze,{children:i.map(N=>e.jsx(je,{value:N.metadata.id,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(en,{theme:N}),e.jsx("span",{className:"truncate",children:m(N.metadata.name,"light")})]})},N.metadata.id))})]})}),e.jsx(Ae,{label:"Dark theme",settingsItem:"appearance.dark-theme",children:e.jsxs(Re,{value:d?.metadata.id??"",onValueChange:h,children:[e.jsx(De,{"aria-label":"Select dark theme",size:Be,className:Dt,children:e.jsx(_e,{placeholder:"Select theme",children:d?e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(en,{theme:d}),e.jsx("span",{className:"truncate",children:m(d.metadata.name,"dark")})]}):void 0})}),e.jsx(ze,{children:p.map(N=>e.jsx(je,{value:N.metadata.id,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(en,{theme:N}),e.jsx("span",{className:"truncate",children:m(N.metadata.name,"dark")})]})},N.metadata.id))})]})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{type:"button",disabled:u||f,onClick:()=>{const N=Date.now();v(!0),g().finally(()=>{const A=Date.now()-N;if(A<500){window.setTimeout(()=>{v(!1)},500-A);return}v(!1)})},className:"typography-settings-link inline-flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:[e.jsx(R,{name:"restart",className:F("h-3.5 w-3.5",f&&"animate-spin")}),f?"Reloading themes...":"Reload themes"]}),e.jsx(Ds,{children:"Import custom themes from ~/.config/pichamber/themes/"})]}),b&&e.jsx(mi,{settingsItem:"appearance.dock-badge",children:e.jsx(Ce,{checked:w,onChange:k,label:"Dock badge",info:"Show a count of chats with unseen activity on the macOS dock icon.",ariaLabel:"Dock badge"})})]}),lm=({shouldShowTimeFormat:t,shouldShowWeekStart:s,timeFormatPreference:n,selectedTimeFormatLabel:a,onTimeFormatPreferenceChange:r,weekStartPreference:o,selectedWeekStartLabel:c,onWeekStartPreferenceChange:i})=>e.jsx(q,{title:"Localization",children:e.jsxs(Rt,{className:"gap-4 @md:grid-cols-2 @md:gap-8 @3xl:gap-10",children:[t&&e.jsx(Ae,{label:"Time format",settingsItem:"appearance.time-format",children:e.jsxs(Re,{value:n,onValueChange:d=>r(d),children:[e.jsx(De,{"aria-label":"Select time format",size:Be,className:Dt,children:e.jsx(_e,{children:a})}),e.jsx(ze,{children:xo.map(d=>e.jsx(je,{value:d.id,children:d.label},d.id))})]})}),s&&e.jsx(Ae,{label:"Week starts on",settingsItem:"appearance.week-start",children:e.jsxs(Re,{value:o,onValueChange:d=>i(d),children:[e.jsx(De,{"aria-label":"Select week start",size:Be,className:Dt,children:e.jsx(_e,{children:c})}),e.jsx(ze,{children:vo.map(d=>e.jsx(je,{value:d.id,children:d.label},d.id))})]})})]})}),cm=({showPwaInstallNameSetting:t,pwaInstallName:s,setPwaInstallName:n,onApplyPwaInstallName:a,showPwaOrientationSetting:r,pwaOrientation:o,selectedPwaOrientationLabel:c,onApplyPwaOrientation:i,showMobileKeyboardModeSetting:d,mobileKeyboardMode:h,selectedMobileKeyboardModeLabel:p,onSetMobileKeyboardMode:m})=>e.jsxs(q,{title:"App install",divider:!1,className:"pb-0",contentClassName:mt,children:[t&&e.jsxs(Ie,{label:"Install app name",info:"Used by PWA installation process.",settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:ps,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(Ps),a("")},className:nt,"aria-label":"Reset install app name",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),r&&e.jsxs(Ie,{label:"Install orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:ps,children:[e.jsxs(Re,{value:o,onValueChange:u=>{const f=va(u);i(f)},children:[e.jsx(De,{"aria-label":"PWA install orientation",size:Be,className:ar,children:e.jsx(_e,{placeholder:"Select orientation",children:c})}),e.jsx(ze,{children:fo.map(u=>e.jsx(je,{value:u.id,children:u.label},u.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{i("system")},disabled:o==="system",className:nt,"aria-label":"Reset install orientation",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),d&&e.jsxs(Ie,{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:ps,children:[e.jsxs(Re,{value:h,onValueChange:u=>{const f=Yr(u);m(f)},children:[e.jsx(De,{"aria-label":"Mobile keyboard behavior",size:Be,className:ar,children:e.jsx(_e,{placeholder:"Select keyboard behavior",children:p})}),e.jsx(ze,{children:go.map(u=>e.jsx(je,{value:u.id,children:u.label},u.id))})]}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>{m("native")},disabled:h==="native",className:nt,"aria-label":"Reset mobile keyboard behavior",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})]});function Mr(t,s,n){return Math.min(n,Math.max(s,t))}function dm(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 Rr(t,s){const n=dm(s);return n<=0?t:Number(t.toFixed(n))}const Nt=D.forwardRef(({value:t,onValueChange:s,min:n=-1/0,max:a=1/0,step:r=1,className:o,containerClassName:c,onBlur:i,disabled:d,fallbackValue:h,onClear:p,emptyLabel:m="—",...u},f)=>{const[v,g]=D.useState(()=>t==null?"":String(t)),{isMobile:b}=lt(),w=D.useRef(!1),k=D.useRef(null),N=D.useCallback(()=>{if(typeof document>"u"||typeof window>"u")return;k.current?.();const _=H=>{H.preventDefault(),H.stopPropagation(),H.stopImmediatePropagation?.(),k.current?.()},O=window.setTimeout(()=>{k.current?.()},700),V=()=>{window.clearTimeout(O),document.removeEventListener("click",_,!0),k.current=null};k.current=V,document.addEventListener("click",_,!0)},[]);D.useEffect(()=>()=>{k.current?.()},[]),D.useEffect(()=>{g(t==null?"":String(t))},[t]);const A=D.useMemo(()=>t!==void 0?t:h!==void 0?h:Number.isFinite(n)?n:0,[h,n,t]),j=D.useRef(A);D.useEffect(()=>{j.current=A},[A]);const x=D.useCallback(_=>{const O=Mr(_,n,a),V=Rr(O,r);j.current=V,s(V)},[a,n,s,r]),P=D.useCallback(_=>{const O=_.target.value;if(g(O),O.trim()===""){p?.();return}const V=Number(O);Number.isFinite(V)&&x(V)},[x,p]),C=D.useCallback(_=>{if(v.trim()===""){p||g(t==null?"":String(t)),i?.(_);return}const O=Number(v);if(!Number.isFinite(O))g(t==null?"":String(t));else{const V=Mr(O,n,a),H=Rr(V,r);H!==t?x(O):j.current=H,g(String(H))}i?.(_)},[x,v,a,n,i,p,r,t]),y=!!(d||A>=a),L=!!(d||A<=n),I=()=>{L||x(j.current-r)},T=()=>{y||x(j.current+r)},E=_=>O=>{O.preventDefault(),O.stopPropagation(),w.current=!0,N(),_()},U=_=>O=>{if(w.current){w.current=!1,O.preventDefault(),O.stopPropagation();return}_()};return b?e.jsxs("div",{className:F("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:E(I),onClick:U(I),className:F("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(R,{name:"subtract",className:"block h-4 w-4"})}),e.jsx("div",{className:F("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]",o),"aria-live":"polite",children:t==null?m:v}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:y,onTouchStart:E(T),onClick:U(T),className:F("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",!y&&"active:bg-interactive-hover"),children:e.jsx(R,{name:"add",className:"block h-4 w-4"})})]}):e.jsxs("div",{className:F("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:()=>x(j.current-r),className:F("flex h-full w-7 shrink-0 items-center justify-center overflow-x-hidden overflow-y-hidden border-r border-border p-0 leading-none touch-manipulation","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50","transition-colors duration-150 ease-in-out"),children:e.jsx(R,{name:"subtract",className:"block h-3.5 w-3.5"})}),e.jsx("input",{...u,ref:f,type:"text",inputMode:u.inputMode??"numeric",value:v,onChange:P,onBlur:C,disabled:d,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:F("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",o)}),e.jsx("button",{type:"button","aria-label":"Increase value",disabled:y,onClick:()=>x(j.current+r),className:F("flex h-full w-7 shrink-0 items-center justify-center overflow-x-hidden overflow-y-hidden border-l border-border p-0 leading-none touch-manipulation","text-muted-foreground hover:bg-interactive-hover hover:text-foreground","disabled:pointer-events-none disabled:opacity-50","transition-colors duration-150 ease-in-out"),children:e.jsx(R,{name:"add",className:"block h-3.5 w-3.5"})})]})});Nt.displayName="NumberInput";const um=({shouldShow:t,uiFont:s,setUiFont:n,monoFont:a,setMonoFont:r,fontSize:o,setFontSize:c,terminalFontSize:i,setTerminalFontSize:d,editorFontSize:h,setEditorFontSize:p,padding:m,setPadding:u,inputBarOffset:f,setInputBarOffset:v,isMobile:g})=>e.jsxs(q,{title:"Density & type",contentClassName:mt,children:[t("fontSize")||t("terminalFontSize")?e.jsxs(Rt,{children:[t("fontSize")&&e.jsxs(Ae,{label:"Interface font",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[e.jsxs(Re,{value:s,onValueChange:b=>n(b),children:[e.jsx(De,{"aria-label":"Select interface font",size:Be,className:Dt,children:e.jsx(_e,{children:Ha.find(b=>b.id===s)?.label})}),e.jsx(ze,{children:Ha.map(b=>e.jsx(je,{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(Ga),disabled:s===Ga,className:nt,"aria-label":"Reset interface font",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]}),t("terminalFontSize")&&e.jsxs(Ae,{label:"Code font",controlClassName:"w-full",children:[e.jsxs(Re,{value:a,onValueChange:b=>r(b),children:[e.jsx(De,{"aria-label":"Select code font",size:Be,className:Dt,children:e.jsx(_e,{children:Wa.find(b=>b.id===a)?.label})}),e.jsx(ze,{children:Wa.map(b=>e.jsx(je,{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:nt,"aria-label":"Reset code font",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,t("fontSize")||t("terminalFontSize")||t("editorFontSize")?e.jsxs(Rt,{children:[t("fontSize")&&e.jsx(Ae,{label:"Interface font size",settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:o,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx("span",{className:Mt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>c(100),disabled:o===100,className:nt,"aria-label":"Reset font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("terminalFontSize")&&e.jsx(Ae,{label:"Terminal font size",settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:i,onValueChange:d,min:9,max:52,step:1}),e.jsx("span",{className:Mt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>d(13),disabled:i===13,className:nt,"aria-label":"Reset terminal font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("editorFontSize")&&e.jsx(Ae,{label:"Editor font size",settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:h,onValueChange:p,min:9,max:32,step:1}),e.jsx("span",{className:Mt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>p(13),disabled:h===13,className:nt,"aria-label":"Reset editor font size",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,t("spacing")||t("inputBarOffset")&&g?e.jsxs(Rt,{children:[t("spacing")&&e.jsx(Ae,{label:"Spacing density",settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:m,onValueChange:u,min:50,max:200,step:5}),e.jsx("span",{className:Mt,children:"%"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>u(100),disabled:m===100,className:nt,"aria-label":"Reset spacing",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})}),t("inputBarOffset")&&g&&e.jsx(Ae,{label:"Input bar offset",info:"Raise input bar to avoid OS-level screen obstructions like home bars.",settingsItem:"appearance.input-bar-offset",controlClassName:"w-full",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:f,onValueChange:v,min:0,max:100,step:5}),e.jsx("span",{className:Mt,children:"px"}),e.jsx(S,{size:"sm",type:"button",variant:"ghost",onClick:()=>v(0),disabled:f===0,className:nt,"aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(R,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),vn=({width:t,tone:s="bg-foreground/60",className:n})=>e.jsx("div",{className:F("h-[3px] rounded-full",s,t,n)}),ls=({width:t,selected:s=!1,chevron:n=!1})=>e.jsxs("div",{className:F("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"})]}),$t=({title:t,details:s,selected:n=!1,quiet:a=!1})=>e.jsxs("div",{className:F("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})]}),aa=({width:t,selected:s=!1})=>e.jsx("div",{className:F("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})}),pm=({width:t})=>e.jsxs("div",{className:"mx-[3px] flex shrink-0 items-center gap-[3px]",children:[e.jsx("div",{className:F("h-[2px] rounded-full bg-foreground/35",t)}),e.jsx("div",{className:"h-[2px] w-[3px] rounded-full bg-foreground/20"})]}),mm=({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(ls,{width:"w-[55%]",selected:!0}),e.jsx(ls,{width:"w-[70%]"}),e.jsx(ls,{width:"w-[45%]"}),e.jsx("div",{className:"h-px shrink-0 bg-border"}),e.jsx($t,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx($t,{title:"w-[60%]",details:"w-[40%]"})]}),t==="folder"&&e.jsxs(e.Fragment,{children:[e.jsx(ls,{width:"w-[60%]",chevron:!0}),e.jsx(aa,{width:"w-[70%]",selected:!0}),e.jsx(aa,{width:"w-[55%]"}),e.jsx(ls,{width:"w-[45%]",chevron:!0}),e.jsx(aa,{width:"w-[65%]"}),e.jsx(ls,{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($t,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx($t,{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($t,{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($t,{title:"w-[75%]",details:"w-[50%]",selected:!0}),e.jsx($t,{title:"w-[60%]",details:"w-[45%]"}),e.jsx("div",{className:"mt-auto h-px shrink-0 bg-border"}),e.jsx(pm,{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"})]})]}),Dr="grid max-w-[40rem] grid-cols-2 gap-2 @xl:grid-cols-4 @xl:gap-3",hm=({shouldShow:t,sidebarViewMode:s,onSidebarViewModeChange:n,fileEditorKeymap:a,setFileEditorKeymap:r,autoSaveEnabled:o,setAutoSaveEnabled:c,expandedEditorToolbar:i,onExpandedEditorToolbarChange:d,wrapLinesByDefault:h,onWrapLinesByDefaultChange:p,showTerminalQuickKeysOnDesktop:m,setShowTerminalQuickKeysOnDesktop:u,showTerminalShellSetting:f,terminalShell:v,setTerminalShell:g,terminalShellOptions:b,terminalShellSupportsLogin:w,terminalLoginShellEnabled:k,setTerminalLoginShellEnabled:N})=>{const A=j=>e.jsx(pi,{selected:s===j.id,onSelect:()=>n(j.id),label:j.label,ariaLabel:j.label,preview:e.jsx(mm,{mode:j.id}),description:am[j.id]},j.id);return e.jsxs(q,{title:"Navigation",contentClassName:"space-y-4",children:[t("sidebarViewMode")&&e.jsx(ot,{title:"Sidebar view",info:"Applies to every device connected to this server.",settingsItem:"appearance.sidebar-view",children:e.jsxs(Zt,{"aria-label":"Sidebar view",className:"space-y-0",children:[e.jsx("div",{className:Dr,children:nm.map(A)}),e.jsx(Cn,{label:"Legacy views",divider:!1,className:"pt-4 pb-0",defaultOpen:Lr.some(j=>j.id===s),children:e.jsx("div",{className:Dr,children:Lr.map(A)})})]})}),t("fileEditorKeymap")&&e.jsx(ot,{title:"File editor keymap",settingsItem:"appearance.file-editor-keymap",children:e.jsx(Zt,{"aria-label":"File editor keymap",children:["default","vim"].map(j=>e.jsx(fs,{selected:a===j,onSelect:()=>r(j),label:j==="default"?"Default":"Vim",ariaLabel:j==="default"?"Default":"Vim"},j))})}),e.jsxs("div",{className:ft,children:[t("autoSaveEnabled")&&e.jsx(Ce,{checked:o,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(Ce,{checked:i,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(Ce,{checked:h,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(Ce,{checked:m,onChange:u,label:"Terminal quick keys",ariaLabel:"Terminal quick keys",settingsItem:"appearance.terminal-quick-keys",info:"Show Esc, Ctrl, Arrows in terminal view"}),f&&e.jsx(Ae,{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(Re,{value:v,onValueChange:j=>{il(j)&&g(j)},children:[e.jsx(De,{"aria-label":"Select terminal shell",size:Be,className:Dt,children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"auto",children:"Auto"}),b.map(j=>e.jsx(je,{value:j.id,children:j.name},j.id))]})]})}),f&&w&&e.jsx(Ce,{checked:k,onChange:N,label:"Start as login shell",ariaLabel:"Start as login shell",settingsItem:"appearance.terminal-login-shell"})]})]})},fm=({hasBehaviorSettings:t,showBehaviorMessageOptions:s,behaviorSectionDivider:n,shouldShow:a,diffLayoutPreference:r,setDiffLayoutPreference:o,followUpBehavior:c,setFollowUpBehavior:i,draftStartersVisible:d,onDraftStartersVisibleChange:h})=>t?e.jsxs(e.Fragment,{children:[s&&e.jsx(q,{title:"Message options",divider:n,children:e.jsxs(Rt,{className:"lg:gap-y-6",children:[a("diffLayout")&&e.jsx(ot,{title:"Diff layout",children:e.jsx(Zt,{"aria-label":"Diff layout",children:tm.map(p=>e.jsx(fs,{selected:r===p.id,onSelect:()=>o(p.id),label:p.label,ariaLabel:`Diff layout: ${p.label}`},p.id))})}),a("followUpBehavior")&&e.jsx(ot,{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(Zt,{"aria-label":"Follow-up behavior",children:rm.map(p=>e.jsx(fs,{selected:c===p.id,onSelect:()=>i(p.id),label:p.label,ariaLabel:`Follow-up behavior: ${p.label}`},p.id))})})]})}),e.jsx(q,{title:"Features",contentClassName:ft,children:e.jsx(Ce,{checked:d,onChange:h,label:"Show starters on new session screen",ariaLabel:"Show starters on the new session screen",settingsItem:"chat.draft-starters-visible"})})]}):null,gm=({perfHudEnabled:t,onPerfHudEnabledChange:s,processRecordingSupported:n,processRecordingEnabled:a,processRecordingActive:r,processRecordingSaving:o,processRecordingError:c,onProcessRecordingEnabledChange:i})=>e.jsxs(q,{title:"Diagnostics",contentClassName:ft,children:[e.jsx(Ce,{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(Ce,{checked:a,onChange:i,disabled:o,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]}),In=({visibleSettings:t})=>{const{isMobile:s}=lt(),{terminal:n}=kn(),{browserTab:a}=Zp(),r=W(M=>M.expandedEditorToolbar),o=W(M=>M.setExpandedEditorToolbar),c=W(M=>M.wrapLinesByDefault),i=W(M=>M.setWrapLinesByDefault),d=W(M=>M.autoSaveEnabled),h=W(M=>M.setAutoSaveEnabled),p=W(M=>M.fontSize),m=W(M=>M.setFontSize),u=W(M=>M.terminalFontSize),f=W(M=>M.setTerminalFontSize),v=W(M=>M.terminalShell),g=W(M=>M.setTerminalShell),b=W(M=>M.terminalLoginShells),w=W(M=>M.setTerminalLoginShells),k=W(M=>M.editorFontSize),N=W(M=>M.setEditorFontSize),A=W(M=>M.uiFont),j=W(M=>M.setUiFont),x=W(M=>M.monoFont),P=W(M=>M.setMonoFont),C=W(M=>M.padding),y=W(M=>M.setPadding),L=W(M=>M.inputBarOffset),I=W(M=>M.setInputBarOffset),T=W(M=>M.mobileKeyboardMode),E=W(M=>M.setMobileKeyboardMode),U=W(M=>M.diffLayoutPreference),_=W(M=>M.setDiffLayoutPreference),O=W(M=>M.showTerminalQuickKeysOnDesktop),V=W(M=>M.setShowTerminalQuickKeysOnDesktop),H=W(M=>M.fileEditorKeymap),ne=W(M=>M.setFileEditorKeymap),X=Qa(M=>M.followUpBehavior),we=Qa(M=>M.setFollowUpBehavior),ie=W(M=>M.timeFormatPreference),ke=W(M=>M.setTimeFormatPreference),oe=W(M=>M.weekStartPreference),ae=W(M=>M.setWeekStartPreference),me=W(M=>M.sidebarViewMode),le=W(M=>M.setSidebarViewMode),Q=W(M=>M.draftStartersVisible),G=W(M=>M.setDraftStartersVisible),{themeMode:Pe,setThemeMode:re,availableThemes:xe,customThemesLoading:ve,reloadCustomThemes:Ne,lightThemeId:K,darkThemeId:ce,setLightThemePreference:z,setDarkThemePreference:J}=ac(),[te,et]=l.useState(!1),$=l.useMemo(()=>Fe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),Y=W(M=>M.dockBadgeEnabled),de=W(M=>M.setDockBadgeEnabled),Z=l.useSyncExternalStore(ol,ll,()=>!1),fe=Fe(),[We,jt]=l.useState(!1),[Qe,at]=l.useState(!1),[Tt,Ut]=l.useState(!1),[bs,Hs]=l.useState(!1),[En,Ft]=l.useState(null),An=l.useCallback(M=>{G(M),Ke({draftStartersVisible:M})},[G]),It=l.useCallback(M=>{o(M),Ke({expandedEditorToolbar:M})},[o]),Ln=l.useCallback(M=>{i(M),Ke({wrapLinesByDefault:M})},[i]),Mn=l.useCallback(M=>{ke(M),Ke({timeFormatPreference:M})},[ke]),Rn=l.useCallback(M=>{ae(M),Ke({weekStartPreference:M})},[ae]),Dn=l.useCallback(M=>{le(M),Ke({sidebarViewMode:M})},[le]),as=l.useMemo(()=>xe.filter(M=>M.metadata.variant==="light").sort((M,ue)=>M.metadata.name.localeCompare(ue.metadata.name)),[xe]),Et=l.useMemo(()=>xe.filter(M=>M.metadata.variant==="dark").sort((M,ue)=>M.metadata.name.localeCompare(ue.metadata.name)),[xe]),_n=l.useMemo(()=>as.find(M=>M.metadata.id===K)??as[0],[as,K]),zn=l.useMemo(()=>Et.find(M=>M.metadata.id===ce)??Et[0],[Et,ce]),On=l.useCallback((M,ue)=>{const Xe=ue==="dark"?" Dark":" Light";return M.endsWith(Xe)?M.slice(0,-Xe.length):M},[]),pe=M=>t?t.includes(M):!0,Bt=pe("perfHud");l.useEffect(()=>{if(!Bt||!fe){jt(!1),at(!1),Ut(!1),Ft(null);return}let M=!1;return Ja().then(ue=>{M||(jt(ue?.supported===!0),at(ue?.enabled===!0),Ut(ue?.active===!0),Ft(ue?.enabled===!0&&ue.active!==!0?"Recording could not start. Disable it and try again.":null))}),()=>{M=!0}},[fe,Bt]),l.useEffect(()=>{if(!Bt||!fe||!Qe)return;let M=!1;const ue=window.setInterval(()=>{Ja().then(Xe=>{M||!Xe?.supported||(Ut(Xe.active),Xe.active||Ft("Recording stopped after a file write failure. Disable it and try again."))})},1e4);return()=>{M=!0,window.clearInterval(ue)}},[fe,Qe,Bt]);const Un=l.useCallback(async M=>{if(!We||bs)return;const ue=Qe,Xe=Tt;at(M),Hs(!0),Ft(null);try{const Ze=await cl(M);if(!Ze?.supported||Ze.enabled!==M||M&&!Ze.active)throw new Error("Failed to update process performance recording");at(Ze.enabled),Ut(Ze.active)}catch{at(ue),Ut(Xe),Ft("Failed to update process performance recording.")}finally{Hs(!1)}},[Tt,Qe,bs,We]),Fn=pe("theme"),Bn=pe("theme")||pe("timeFormat")||pe("weekStart"),Gs=s&&Gt()&&!Fe(),se=pe("theme")||Gs||pe("pwaInstallName")||pe("pwaOrientation")||pe("timeFormat")||pe("weekStart"),Se=pe("fontSize")||pe("terminalFontSize")||pe("editorFontSize")||pe("spacing")||pe("inputBarOffset")&&s,Ye=pe("sidebarViewMode")||pe("terminalQuickKeys")||pe("terminalShell")||pe("terminalLoginShell")||pe("fileEditorKeymap")||pe("autoSaveEnabled")||pe("expandedEditorToolbar")||pe("wrapLinesByDefault"),ge=pe("diffLayout")||pe("followUpBehavior"),wt=pe("diffLayout")||pe("followUpBehavior"),dt=se||Se||Ye,be=pe("pwaInstallName")&&Gt()&&a&&!Fe(),tt=pe("pwaOrientation")&&Gt()&&!Fe(),kt=pe("mobileKeyboardMode")&&Gt()&&!Fe()&&dl(),ys=pe("terminalShell")||pe("terminalLoginShell"),[js,ws]=l.useState([]),[Ws,$n]=l.useState(0);l.useEffect(()=>yn(()=>{ws([]),$n(M=>M+1)}),[]),l.useEffect(()=>{let M=!1;if(!(!ys||!n.listShells))return n.listShells().then(ue=>{M||ws(ue)}).catch(()=>{M||ws([])}),()=>{M=!0}},[ys,n,Ws]);const Kn=l.useMemo(()=>{const M=js.filter(ue=>ue.id!=="auto");return v==="auto"||M.some(ue=>ue.id===v)?M:[{id:v,name:v,supportsLogin:!1},...M]},[js,v]),qs=js.find(M=>M.id===v)?.supportsLogin===!0,rs=b.includes(v),Qs=M=>{w(M?[...b.filter(ue=>ue!==v),v]:b.filter(ue=>ue!==v))},[ks,So]=l.useState(()=>Nc()),[Po,is]=l.useState(""),[Vn,Js]=l.useState("system"),To=l.useMemo(()=>xo.find(ue=>ue.id===ie)?.label??"Auto",[ie]),Io=l.useMemo(()=>vo.find(ue=>ue.id===oe)?.label??"Auto",[oe]),Eo=l.useMemo(()=>{const M=fo.find(ue=>ue.id===Vn);return M?M.label:void 0},[Vn]),Ao=l.useMemo(()=>{const M=go.find(ue=>ue.id===T);return M?M.label:void 0},[T]),Lo=l.useCallback(M=>{M!==ks&&(So(M),Cc(M),window.location.reload())},[ks]),Mo=l.useCallback(async M=>{if(typeof window>"u")return;const ue=window,Ze=M.trim().replace(/\s+/g," ").slice(0,64);if(await Ke({pwaAppName:Ze}),typeof ue.__PICHAMBER_SET_PWA_INSTALL_NAME__=="function"){const Va=ue.__PICHAMBER_SET_PWA_INSTALL_NAME__(Ze);is(Va);return}is(Ze||Ps),ue.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Ro=l.useCallback(async M=>{if(typeof window>"u")return;const ue=window,Xe=va(M);if(await Ke({pwaOrientation:Xe}),typeof ue.__PICHAMBER_SET_PWA_ORIENTATION__=="function"){const Ze=ue.__PICHAMBER_SET_PWA_ORIENTATION__(Xe);Js(Ze);return}Js(Xe),ue.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return l.useEffect(()=>{if(typeof window>"u"||!be&&!tt&&!kt)return;let M=!1;return(async()=>{try{const Xe=await Ee("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Xe.ok){M||is(Ps);return}const Ze=await Xe.json().catch(()=>({})),Do=(typeof Ze?.pwaAppName=="string"?Ze.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),_o=va(Ze?.pwaOrientation),zo=Yr(Ze?.mobileKeyboardMode);M||(be&&is(Do||Ps),tt&&Js(_o),kt&&E(zo))}catch{M||(be&&is(Ps),tt&&Js("system"),kt&&E("native"))}})(),()=>{M=!0}},[E,kt,be,tt]),e.jsxs(e.Fragment,{children:[se&&Fn&&e.jsx(om,{themeMode:Pe,setThemeMode:re,showMobileLayoutSetting:Gs,mobileLayoutPreference:ks,onMobileLayoutPreferenceChange:Lo,selectedLightTheme:_n,setLightThemePreference:z,lightThemes:as,selectedDarkTheme:zn,setDarkThemePreference:J,darkThemes:Et,formatThemeLabel:On,customThemesLoading:ve,themesReloading:te,setThemesReloading:et,reloadCustomThemes:Ne,dockBadgeSupported:$,dockBadgeEnabled:Y,setDockBadgeEnabled:de}),Ye&&e.jsx(hm,{shouldShow:pe,sidebarViewMode:me,onSidebarViewModeChange:Dn,fileEditorKeymap:H,setFileEditorKeymap:ne,autoSaveEnabled:d,setAutoSaveEnabled:h,expandedEditorToolbar:r,onExpandedEditorToolbarChange:It,wrapLinesByDefault:c,onWrapLinesByDefaultChange:Ln,showTerminalQuickKeysOnDesktop:O,setShowTerminalQuickKeysOnDesktop:V,showTerminalShellSetting:ys,terminalShell:v,setTerminalShell:g,terminalShellOptions:Kn,terminalShellSupportsLogin:qs,terminalLoginShellEnabled:rs,setTerminalLoginShellEnabled:Qs}),se&&Bn&&e.jsx(lm,{shouldShowTimeFormat:pe("timeFormat"),shouldShowWeekStart:pe("weekStart"),timeFormatPreference:ie,selectedTimeFormatLabel:To,onTimeFormatPreferenceChange:Mn,weekStartPreference:oe,selectedWeekStartLabel:Io,onWeekStartPreferenceChange:Rn}),Se&&e.jsx(um,{shouldShow:pe,uiFont:A,setUiFont:j,monoFont:x,setMonoFont:P,fontSize:p,setFontSize:m,terminalFontSize:u,setTerminalFontSize:f,editorFontSize:k,setEditorFontSize:N,padding:C,setPadding:y,inputBarOffset:L,setInputBarOffset:I,isMobile:s}),e.jsx(fm,{hasBehaviorSettings:ge,showBehaviorMessageOptions:wt,behaviorSectionDivider:dt,shouldShow:pe,diffLayoutPreference:U,setDiffLayoutPreference:_,followUpBehavior:X,setFollowUpBehavior:we,draftStartersVisible:Q,onDraftStartersVisibleChange:An}),pe("perfHud")&&e.jsx(gm,{perfHudEnabled:Z,onPerfHudEnabledChange:ul,processRecordingSupported:We,processRecordingEnabled:Qe,processRecordingActive:Tt,processRecordingSaving:bs,processRecordingError:En,onProcessRecordingEnabledChange:Un}),se&&(be||tt||kt)&&e.jsx(Cn,{label:"Show legacy options",children:e.jsx(cm,{showPwaInstallNameSetting:be,pwaInstallName:Po,setPwaInstallName:is,onApplyPwaInstallName:Mo,showPwaOrientationSetting:tt,pwaOrientation:Vn,selectedPwaOrientationLabel:Eo,onApplyPwaOrientation:Ro,showMobileKeyboardModeSetting:kt,mobileKeyboardMode:T,selectedMobileKeyboardModeLabel:Ao,onSetMobileKeyboardMode:M=>{E(M),Ke({mobileKeyboardMode:M})}})})]})},xm=[{value:"system",label:"System browser"},{value:"pichamber",label:"PiChamber browser"}],vm=()=>{const t=W(i=>i.chatLinkTarget),s=W(i=>i.setChatLinkTarget),[n,a]=l.useState(!1),[r,o]=l.useState(!1),c=async()=>{o(!0);try{await xc(),B.success("Browsing data cleared"),a(!1)}catch(i){B.error(i instanceof Error?i.message:"Could not clear browsing data")}finally{o(!1)}};return e.jsx(q,{title:"Web browser",children:e.jsxs("div",{className:mt,children:[e.jsx(Ie,{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(Nn,{value:t,onChange:s,options:xm})}),e.jsx(Ie,{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"})})]})})},_r=1,zr=365,tn=7,Or=30,Ur=t=>t===1?"day":"days",bm=({archiveAfterDays:t,deleteAfterDays:s,onArchiveAfterDaysChange:n,onDeleteAfterDaysChange:a})=>{const r=t===0,o=s===0,c=!r&&!o,i=c?t:tn,d=c?s:Or,h=`Only archived sessions are deleted, counted from the day each one was archived. ${c?"With these settings":`With archiving at ${i} days and deleting at ${d}`}, a session is deleted ${i+d} days after you last used it.`;return e.jsxs(e.Fragment,{children:[e.jsx(Ie,{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:Lt,children:[e.jsx(Nt,{value:r?void 0:t,fallbackValue:tn,onValueChange:n,onClear:()=>n(0),emptyLabel:"Off",placeholder:"Off",min:_r,max:zr,step:1,"aria-label":"Days before an idle session is archived",className:"w-20 tabular-nums"}),e.jsx("span",{className:Mt,children:Ur(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(Ie,{settingsItem:"sessions.auto-delete",label:"Delete archived sessions",info:h,description:o?void 0:"Deleted sessions can't be restored.",children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:o?void 0:s,fallbackValue:Or,onValueChange:a,onClear:()=>a(0),emptyLabel:"Off",placeholder:"Off",min:_r,max:zr,step:1,"aria-label":"Days after archiving before a session is deleted",className:"w-20 tabular-nums"}),e.jsx("span",{className:Mt,children:`${Ur(s)} after archiving`})]})})]})},bo=()=>{const t=W(m=>m.sessionAutoArchiveAfterDays),s=W(m=>m.sessionAutoDeleteAfterDays),n=W(m=>m.setSessionAutoArchiveAfterDays),a=W(m=>m.setSessionAutoDeleteAfterDays),r=l.useCallback(m=>{n(m),Ke({sessionAutoArchiveAfterDays:m})},[n]),o=l.useCallback(m=>{a(m),Ke({sessionAutoDeleteAfterDays:m})},[a]),{archiveCandidates:c,deleteCandidates:i,isRunning:d,runCleanup:h}=rc({autoRun:!1}),p=l.useCallback(async()=>{const m=await h(),u=m.archive.completedIds.length,f=m.delete.completedIds.length,v=m.archive.failedIds.length,g=m.delete.failedIds.length;if(m.skippedReason==="running"){B.message("Archive and delete is already running. Try again in a moment.");return}if(m.skippedReason==="disabled"){B.message("Archiving and deleting are both off");return}if(u+f+v+g===0){B.message(m.skippedReason==="partial"||m.skippedReason==="stale"?"Could not check every folder. Try again later.":"No sessions to archive or delete");return}u>0&&B.success(`Archived ${Ys(u)}`),f>0&&B.success(`Deleted ${Ys(f)}`),v>0&&B.error(`Could not archive ${Ys(v)}`),g>0&&B.error(`Could not delete ${Ys(g)}`)},[h]);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(bm,{archiveAfterDays:t,deleteAfterDays:s,onArchiveAfterDaysChange:r,onDeleteAfterDaysChange:o}),e.jsx(Ie,{settingsItem:"sessions.auto-cleanup",label:"Run now",description:`Ready to archive: ${c.length}. Ready to delete: ${i.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"})})]})},ym=t=>{if(!t)return;const s=t.providerId.trim(),n=t.modelId.trim();if(!(!s||!n))return`${s}/${n}`},ra=t=>{const s=ic(t??void 0);return s?{providerId:s.providerId,modelId:s.modelId}:null},jm=(t,s={})=>{if(!t)return{};const n={};if(!s.defaultModel){const a=ra(typeof t.defaultModel=="string"?t.defaultModel:void 0);a&&(n.defaultModel=a)}if(!s.smallModel&&t.smallModelUseDefault===!1){const a=ra(typeof t.smallModelOverride=="string"?t.smallModelOverride:void 0);a&&(n.smallModel=a)}if(!s.walkthroughModel){const a=ra(typeof t.walkthroughModelOverride=="string"?t.walkthroughModelOverride:void 0);a&&(n.walkthroughModel=a)}return n},wm=t=>!!(t.defaultModel||t.smallModel||t.walkthroughModel),ia=()=>({runtimeKey:qe()}),sn="__pi_fallback__",oa={terminal:"Terminal UI",dialogs:"Standard dialogs"},km=(t,s)=>{const n=[...t];return s&&!n.includes(s)&&n.push(s),n},yo=()=>{const t=He(y=>y.providers),s=He(y=>y.modelsMetadata),n=He(y=>y.loadProviders),a=He(y=>y.setProvider),r=He(y=>y.setModel),o=He(y=>y.setSettingsDefaultModel),c=He(y=>y.setSettingsDefaultThinking),i=He(y=>y.setSettingsDefaultThinkingByModel),d=W(y=>y.showDeletionDialog),h=W(y=>y.setShowDeletionDialog),[p,m]=l.useState(null),[u,f]=l.useState("loading"),v=l.useCallback(y=>{m(y),o(ym(y.defaultModel)),c(y.defaultThinking),i(y.defaultThinkingByModel??{})},[o,c,i]);l.useEffect(()=>{n({source:"sessionsDefaults"}),He.getState().ensureModelMetadata()},[n]),l.useEffect(()=>{let y=!0;return(async()=>{try{const I=await Ue.getSettings(ia());if(!y)return;let T=I.pichamber;if(!T.defaultModel&&!T.smallModel&&!T.walkthroughModel){const E=wa()?.settings;if(E)try{const U=await E.load(),_=jm(U?.settings,T);if(wm(_)){const O=await Ue.setPiChamberDefaults(_,ia());if(!y)return;T=O.pichamber,await Ke({defaultModel:"",smallModelOverride:"",walkthroughModelOverride:""})}}catch{}}if(!y)return;v(T),f("ready")}catch{y&&f("failed")}})(),()=>{y=!1}},[v]);const g=l.useCallback(async y=>{Te("saving");try{const L=await Ue.setPiChamberDefaults(y,ia());v(L.pichamber),Te("saved")}catch{Te("error")}},[v]),b=l.useCallback((y,L)=>{const I=t.find(E=>E.id===y);return(Array.isArray(I?.models)?I.models:[]).find(E=>E.id===L)},[t]),w=l.useCallback(y=>{y&&t.find(I=>I.id===y.providerId)&&(a(y.providerId),r(y.modelId)),g({defaultModel:y})},[g,t,r,a]),k=l.useCallback((y,L)=>{const I=pn(y);I&&g({defaultThinkingByModel:{[I]:L}})},[g]),N=l.useCallback((y,L)=>s.get(`${y}/${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 A=pn(p?.defaultModel),j=p?.defaultModel?b(p.defaultModel.providerId,p.defaultModel.modelId):void 0,x=ri(j),P=!!(p?.defaultModel&&ii(x)),C=A?p?.defaultThinkingByModel?.[A]: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:mt,children:[e.jsx(Ie,{settingsItem:"sessions.default-model",label:"Default model",info:"The model new sessions start with. Unset keeps Pi's default.",children:e.jsx(qn,{value:p?.defaultModel??null,noneLabel:"Default",ariaLabel:"Default model",onChange:w})}),P&&p?.defaultModel?e.jsx(Ie,{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(Re,{value:C??sn,onValueChange:y=>{k(p.defaultModel,y===sn?null:y)},children:[e.jsx(De,{size:Be,className:hs,"aria-label":"Default thinking",children:e.jsx(_e,{children:y=>y===sn?"Default":y?un[y]??y:""})}),e.jsxs(ze,{children:[e.jsx(je,{value:sn,children:"Default"}),km(x,C).map(y=>e.jsx(je,{value:y,children:un[y]},y))]})]})}):null,e.jsx(Ie,{settingsItem:"sessions.small-model",label:"Small model",info:"A cheap model for quick utility tasks like short recaps and summaries.",children:e.jsx(qn,{value:p?.smallModel??null,noneLabel:"Use default small model",ariaLabel:"Small model",onChange:y=>{g({smallModel:y})}})}),e.jsx(Ie,{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(qn,{value:p?.walkthroughModel??null,noneLabel:"Small model",ariaLabel:"Changes walkthrough model",isModelAllowed:N,onChange:y=>{g({walkthroughModel:y})}})}),e.jsx(Ie,{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:ps,children:e.jsxs("div",{className:Lt,children:[e.jsx(Nt,{value:p?.defaultRetryLimit??3,min:0,max:10,step:1,"aria-label":"Default retry limit",onValueChange:y=>{if(!Number.isFinite(y))return;const L=Math.max(0,Math.min(10,Math.round(y)));g({defaultRetryLimit:L})}}),e.jsx("span",{className:Mt,children:"retries"})]})})}),e.jsx(Ie,{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(Re,{value:p?.extensionUi??"terminal",onValueChange:y=>{g({extensionUi:y})},children:[e.jsx(De,{size:Be,className:hs,"aria-label":"Extension interface",children:e.jsx(_e,{children:y=>oa[y]??""})}),e.jsxs(ze,{children:[e.jsx(je,{value:"terminal",children:oa.terminal}),e.jsx(je,{value:"dialogs",children:oa.dialogs})]})]})}),e.jsx(mi,{className:ft,children:e.jsx(Ce,{settingsItem:"sessions.deletion-dialog",checked:d,onChange:h,label:"Show deletion dialog",ariaLabel:"Show deletion dialog"})})]})})},Nm=()=>{const t=l.useMemo(()=>Fe(),[]),s=l.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),n=!t&&!s,a=W(k=>k.nativeNotificationsEnabled),r=W(k=>k.setNativeNotificationsEnabled),o=W(k=>k.notificationMode),c=W(k=>k.setNotificationMode),i=W(k=>k.notifyOnCompletion),d=W(k=>k.setNotifyOnCompletion),h=W(k=>k.notifyOnError),p=W(k=>k.setNotifyOnError),m=W(k=>k.notifyOnInputNeeded),u=W(k=>k.setNotifyOnInputNeeded),[f,v]=l.useState("default");l.useEffect(()=>{n&&typeof Notification<"u"&&v(Notification.permission)},[n]);const g=async k=>{if(t){r(k);return}if(!n){r(k);return}if(k&&typeof Notification<"u"&&Notification.permission==="default")try{const N=await Notification.requestPermission();v(N),N==="granted"?r(!0):B.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(N){console.error("Failed to request notification permission:",N),B.error("Failed to request notification permission")}else r(!!(k&&f==="granted"))},b=t||s||n&&typeof Notification<"u"&&Notification.permission==="granted",w=async()=>{const k=wa();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(N){console.error("Test notification failed:",N),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:ft,children:[e.jsx(Ce,{checked:a&&b,onChange:k=>{g(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(Ce,{checked:o==="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:()=>{w()},children:"Send test notification"})})]})]}),n&&e.jsxs("div",{className:"mt-1",children:[f==="denied"&&e.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:"Notification permission denied. Enable it in your browser settings."}),f==="granted"&&!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:ft,children:[e.jsx(Ce,{checked:i,onChange:d,label:"Work completed",ariaLabel:"Notify when work is completed"}),e.jsx(Ce,{checked:h,onChange:p,label:"Errors",ariaLabel:"Notify when work fails"}),e.jsx(Ce,{checked:m,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}],Cm="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",Sm="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."}],Pm=[".yml",".yaml",".json"],Tm="Config file must use .yml, .yaml, or .json extension.",Ts=t=>{const s=t.trim().toLowerCase();return Pm.some(n=>s.endsWith(n))},Im=()=>"cloudflared",jo=()=>{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"},Em=(t=jo())=>t==="win32"?"winget install --id Cloudflare.cloudflared":t==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",la=(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():Im(),r=typeof s?.platform=="string"&&s.platform.trim().length>0?s.platform.trim():jo(),o=typeof s?.installCommand=="string"&&s.installCommand.trim().length>0?s.installCommand.trim():Em(r);return{provider:n,dependency:a,installCommand:o}},Am=t=>t==="cloudflare"?"Cloudflare":t,Kt=t=>t==="managed-local"?"managed-local":"managed-remote",ya=(t,s,n)=>t.find(r=>r.ms===s)?.value||n,Fr=(t,s,n)=>{const a=ya(t,s,n);return t.find(r=>r.value===a)?.label||a},wo=t=>{const s=Math.max(0,t),n=Math.floor(s/1e3),a=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return a>0?`${a}h ${r}m`:r>0?`${r}m ${o}s`:`${o}s`},Lm=(t,s)=>oc(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()}},Mm=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 o=r,c=typeof o.id=="string"?o.id.trim():"",i=typeof o.name=="string"?o.name.trim():"",d=bn(typeof o.hostname=="string"?o.hostname:"");!c||!i||!d||s.has(c)||n.has(d)||(s.add(c),n.add(d),a.push({id:c,name:i,hostname:d}))}return a},Rm=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,Dm=({provider:t})=>{const s=Am(t),n=t==="cloudflare";return e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(R,{name:"cloud",className:F("size-4 shrink-0",n?"text-[var(--status-warning)]":"text-muted-foreground")}),e.jsx("span",{children:s})]})},_m=({records:t,timeFormatPreference:s})=>t.length===0?null:e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)]/30 p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(R,{name:"information",className:"size-4 text-[var(--status-info)]"}),e.jsx("p",{className:hi,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)]",o=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(R,{name:"checkbox-blank-circle-fill",className:F("size-2.5 shrink-0",o)}),e.jsx("span",{className:F("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 ${Lm(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)})})]})}),zm=({installInfo:t})=>e.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning)]/30 bg-[var(--status-warning)]/5 p-3",children:[e.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:hi,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})]})]})}),Om=({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:F(Le,"shrink-0"),children:"Connect link TTL"}),e.jsxs(Re,{value:ya(rn,t,"1800000"),onValueChange:a,disabled:n,children:[e.jsx(De,{size:Be,className:"max-w-[11rem] min-w-0",children:e.jsx(_e,{className:"truncate",children:Fr(rn,t,"1800000")})}),e.jsx(ze,{children:rn.map(o=>e.jsx(je,{value:o.value,children:o.label},o.value))})]})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:F(Le,"shrink-0"),children:"Tunnel session TTL"}),e.jsxs(Re,{value:ya(on,s,"28800000"),onValueChange:r,disabled:n,children:[e.jsx(De,{size:Be,className:"max-w-[11rem] min-w-0",children:e.jsx(_e,{className:"truncate",children:Fr(on,s,"28800000")})}),e.jsx(ze,{children:on.map(o=>e.jsx(je,{value:o.value,children:o.label},o.value))})]})]})]}),Um=({suggestedConnectorPort:t,managedRemoteTunnelPresets:s,expandedManagedRemoteTunnels:n,sessionTokensByPresetId:a,savedTokenPresetIds:r,disabled:o,isAddingPreset:c,newPresetName:i,newPresetHostname:d,newPresetToken:h,managedRemoteValidationError:p,selectedPreset:m,onToggleAddPreset:u,onCancelAddPreset:f,onNewPresetNameChange:v,onNewPresetHostnameChange:g,onNewPresetTokenChange:b,onSaveNewPreset:w,onTogglePresetCollapse:k,onRemovePreset:N,onPresetTokenChange:A,onPersistToken:j})=>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(ui,{children:"Saved managed remote tunnels"}),e.jsxs(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:u,disabled:o,children:[e.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Create"]})]}),s.length>0?e.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:s.map((x,P)=>{const C=a[x.id]||"",y=r.has(x.id),L=n[x.id]??!1;return e.jsx("div",{className:F(P<s.length-1&&"border-b border-[var(--surface-subtle)]"),children:e.jsxs(Sc,{open:L,onOpenChange:I=>k(x.id,I),className:"py-1.5",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3",children:[e.jsxs(Pc,{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:o,children:[L?e.jsx(R,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):e.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-ui-label min-w-0 flex-1 truncate text-foreground",children:x.name})]}),e.jsx(S,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":`Remove ${x.name}`,onClick:()=>N(x.id),disabled:o,children:e.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsx(Tc,{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:x.hostname})]}),e.jsx(ee,{type:"password",value:C,onChange:I=>A(x.id,I.target.value),onBlur:I=>{const T=I.currentTarget.value.trim();T&&j({presetId:x.id,presetName:x.name,hostname:x.hostname,token:T})},placeholder:y?"Saved token available (optional to replace)":"Paste token for this tunnel",className:"h-7",disabled:o}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",disabled:o||C.trim().length===0,onClick:()=>{j({presetId:x.id,presetName:x.name,hostname:x.hostname,token:C})},children:"Save token"})})]})})]})},x.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:i,onChange:x=>v(x.target.value),placeholder:"Tunnel name (e.g. Production)",className:"h-7",disabled:o}),e.jsx(ee,{value:d,onChange:x=>g(x.target.value),placeholder:"Hostname (e.g. oc.example.com)",className:"h-7",disabled:o}),e.jsx(ee,{type:"password",value:h,onChange:x=>b(x.target.value),placeholder:"Token",className:"h-7",disabled:o}),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:w,disabled:o,children:"Save changes"}),e.jsx(S,{variant:"ghost",size:"xs",className:"!font-normal",onClick:f,disabled:o,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(Ds,{children:"Tokens are saved in ~/.config/pichamber/cloudflare-managed-remote-tunnels.json."})]}),!m&&p&&e.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:p})]}),Fm=({managedLocalConfigPath:t,isManagedLocalConfigPathInvalid:s,managedLocalConfigExtensionError:n,disabled:a,fileInputRef:r,onInputChange:o,onInputBlur:c,onBrowse:i,onClear:d,onFileSelected:h})=>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:h}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{value:t||"",onChange:p=>o(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:i,disabled:a,children:e.jsx(R,{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(R,{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})]})}),Bm=({tunnelMode:t,selectedPresetId:s,managedRemoteTunnelPresets:n,selectedPreset:a,willReplaceActiveTunnel:r,state:o,isSavingMode:c,isManagedLocalConfigPathInvalid:i,primaryCtaClass:d,onSelectPreset:h,onStart:p,onOpenDocUrl:m})=>e.jsxs("div",{"data-settings-item":"tunnel.start",className:"space-y-6",children:[e.jsx("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)] p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(R,{name:"information",className:"mt-0.5 size-4 shrink-0 text-[var(--status-info)]"}),e.jsxs("div",{className:"space-y-1",children:[t==="managed-remote"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed remote tunnels require a purchased domain in your Cloudflare account."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{m(Cm)},children:["Check documentation on how to configure a managed remote tunnel",e.jsx(R,{name:"external-link",className:"size-3.5"})]})]}),t==="managed-local"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:"Managed local tunnels use your local cloudflared configuration file."}),e.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{m(Sm)},children:["Check documentation on managed local tunnel configuration",e.jsx(R,{name:"external-link",className:"size-3.5"})]})]}),e.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:`Start a ${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(Re,{value:s||(n[0]?.id??""),onValueChange:h,disabled:c||o==="starting"||o==="stopping"||n.length<=1,children:[e.jsx(De,{size:Be,children:e.jsx(_e,{placeholder:"Select saved tunnel",children:a?.name})}),e.jsx(ze,{fitContent:!0,children:n.map(u=>e.jsx(je,{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(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),e.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:"Starting this tunnel replaces the active tunnel and revokes existing connect links and remote sessions."})]})}),e.jsx(S,{size:"sm",variant:"outline",onClick:p,disabled:o==="starting"||c||t==="managed-remote"&&!a||t==="managed-local"&&i,className:F(d,o==="starting"&&"opacity-70"),children:o==="starting"?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Starting tunnel..."]}):"Start tunnel"})]}),$m=({tunnelInfo:t,isConnectLinkLive:s,copied:n,onCopyUrl:a,remainingText:r,qrDataUrl:o,onNewConnectLink:c,onStop:i,stopping:d,isSavingMode:h,isManagedLocalConfigPathInvalid:p,tunnelMode:m,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(R,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):e.jsx(R,{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:[o?e.jsx("img",{src:o,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||h||m==="managed-local"&&p,className:u,children:[e.jsx(R,{name:"restart",className:"size-3.5"}),"New connect link"]}),e.jsx(S,{size:"sm",variant:"ghost",onClick:i,disabled:d||h,className:"gap-2 text-[var(--status-error)]",children:d?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"loader-4",className:"size-3.5 animate-spin"})," ","Stopping..."]}):"Stop tunnel"})]})})]});function Km({saveTunnelSettings:t,setManagedRemoteValidationError:s}){const[n,a]=l.useState([]),[r,o]=l.useState({}),[c,i]=l.useState(""),[d,h]=l.useState({}),[p,m]=l.useState(new Set),[u,f]=l.useState(!1),[v,g]=l.useState(""),[b,w]=l.useState(""),[k,N]=l.useState(""),A=l.useMemo(()=>n.find(L=>L.id===c)||n[0]||null,[n,c]),j=l.useCallback(async L=>{const I=L.token.trim();if(I)try{const T={...d,[L.presetId]:I};await Ke({managedRemoteTunnelPresetTokens:T}),m(E=>{const U=new Set(E);return U.add(L.presetId),U})}catch{B.error("Failed to save managed remote tunnel token")}},[d]),x=l.useCallback(async(L,I)=>{try{await Ke({managedRemoteTunnelPresets:I})}catch{B.error("Failed to save selected managed remote tunnel")}},[]),P=l.useCallback(L=>{const I=n.find(T=>T.id===L);I&&(i(I.id),s(null),x(I,n))},[n,x,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 E={id:Rm(),name:L,hostname:I},U=[...n,E];a(U),i(E.id),o(_=>({..._,[E.id]:!0})),h(_=>({..._,[E.id]:T})),s(null),f(!1),g(""),w(""),N(""),await t({tunnelMode:"managed-remote",managedRemoteTunnelPresets:U,managedRemoteTunnelPresetTokens:{...d,[E.id]:T}}),await j({presetId:E.id,presetName:E.name,hostname:E.hostname,token:T}),B.success("Managed remote tunnel saved")},[n,b,v,k,j,t,d,s]),y=l.useCallback(async L=>{const I=n.find(O=>O.id===L);if(!I)return;const T=n.filter(O=>O.id!==I.id),E=T[0]?.id||"",U=c===I.id?E:c,_=Object.fromEntries(Object.entries(d).filter(([O,V])=>O!==I.id&&V.trim().length>0));a(T),i(U),o(O=>{const V={...O};return delete V[I.id],V}),h(O=>{const V={...O};return delete V[I.id],V}),m(O=>{const V=new Set(O);return V.delete(I.id),V}),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:o,selectedPresetId:c,setSelectedPresetId:i,sessionTokensByPresetId:d,setSessionTokensByPresetId:h,savedTokenPresetIds:p,setSavedTokenPresetIds:m,isAddingPreset:u,setIsAddingPreset:f,newPresetName:v,setNewPresetName:g,newPresetHostname:b,setNewPresetHostname:w,newPresetToken:k,setNewPresetToken:N,selectedPreset:A,persistManagedRemoteTunnelToken:j,handleSelectPreset:P,handleSaveNewPreset:C,handleRemovePreset:y}}function Vm({saveTunnelSettings:t}){const[s,n]=l.useState(null),a=Tm,r=l.useRef(null),o=l.useMemo(()=>s?!Ts(s):!1,[s]),c=l.useCallback(async()=>{const m=await pl({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(m.success&&typeof m.path=="string"&&m.path.trim().length>0){const u=m.path.trim();if(!Ts(u)){B.error(a);return}n(u),await t({managedLocalTunnelConfigPath:u});return}r.current?.click()},[a,t]),i=l.useCallback(m=>{const u=m.trim();n(u.length>0?u:null)},[]),d=l.useCallback(async()=>{if(s&&!Ts(s)){B.error(a);return}await t({managedLocalTunnelConfigPath:s})},[a,s,t]),h=l.useCallback(async()=>{n(null),await t({managedLocalTunnelConfigPath:null})},[t]),p=l.useCallback(async m=>{const u=m.target.files?.[0];if(!u)return;const f=u.name.trim();if(f.length!==0){if(!Ts(f)){B.error(a);return}n(f),await t({managedLocalTunnelConfigPath:f}),m.target.value=""}},[a,t]);return{managedLocalConfigPath:s,setManagedLocalConfigPath:n,managedLocalConfigExtensionError:a,managedLocalConfigFileInputRef:r,isManagedLocalConfigPathInvalid:o,handleBrowseManagedLocalConfig:c,handleManagedLocalConfigInputChange:i,handleManagedLocalConfigInputBlur:d,handleManagedLocalConfigClear:h,handleManagedLocalConfigFileSelected:p}}function Hm(){const[t,s]=l.useState(18e5),[n,a]=l.useState(480*60*1e3),[r,o]=l.useState(!1),c=l.useCallback(async(h,p)=>{o(!0);try{await Ke({tunnelBootstrapTtlMs:h,tunnelSessionTtlMs:p})}catch{B.error("Failed to save tunnel TTL settings")}finally{o(!1)}},[]),i=l.useCallback(async h=>{const p=rn.find(m=>m.value===h);p&&(s(p.ms),await c(p.ms,n))},[c,n]),d=l.useCallback(async h=>{const p=on.find(m=>m.value===h);!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:i,handleSessionTtlChange:d}}function Gm({tunnelInfo:t,state:s,setSessionRecords:n,setSavedTokenPresetIds:a,setLocalPort:r}){const[o,c]=l.useState(null),[i,d]=l.useState(""),[h,p]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t?.connectUrl){c(null);return}let m=!1;return fi.toDataURL(t.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(u=>{m||c(u)}).catch(()=>{m||c(null)}),()=>{m=!0}},[t?.connectUrl]),l.useEffect(()=>{if(!t?.bootstrapExpiresAt){d("No expiry");return}let m=null,u=Date.now();const f=()=>{const b=t.bootstrapExpiresAt?t.bootstrapExpiresAt-Date.now():0;b<=0?d("Expired"):d(wo(b))},v=()=>{const b=Date.now();b-u>=1e3&&(f(),u=b),m=requestAnimationFrame(v)};f(),(typeof document>"u"||document.visibilityState==="visible")&&(m=requestAnimationFrame(v));const g=()=>{document.visibilityState==="visible"&&m===null?m=requestAnimationFrame(v):document.visibilityState!=="visible"&&m!==null&&(cancelAnimationFrame(m),m=null)};return document.addEventListener("visibilitychange",g),()=>{document.removeEventListener("visibilitychange",g),m!==null&&cancelAnimationFrame(m)}},[t?.bootstrapExpiresAt]),l.useEffect(()=>{let m=null,u=Date.now();const f=()=>{const g=Date.now();g-u>=1e3&&(p(g),u=g),m=requestAnimationFrame(f)};(typeof document>"u"||document.visibilityState==="visible")&&(m=requestAnimationFrame(f));const v=()=>{document.visibilityState==="visible"&&m===null?m=requestAnimationFrame(f):document.visibilityState!=="visible"&&m!==null&&(cancelAnimationFrame(m),m=null)};return document.addEventListener("visibilitychange",v),()=>{document.removeEventListener("visibilitychange",v),m!==null&&cancelAnimationFrame(m)}},[]),l.useEffect(()=>{if(s==="starting"||s==="stopping"||s==="checking")return;let m=!1;const u=async()=>{try{const v=await Ee("/api/pichamber/tunnel/status");if(!v.ok||m)return;const g=await v.json();if(m)return;n(Array.isArray(g.activeSessions)?g.activeSessions:[]),a(()=>new Set(Array.isArray(g.managedRemoteTunnelTokenPresetIds)?g.managedRemoteTunnelTokenPresetIds:[])),r(typeof g.localPort=="number"?g.localPort:null)}catch{}},f=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||u()},5e3);return()=>{m=!0,window.clearInterval(f)}},[r,a,n,s]),{qrDataUrl:o,remainingText:i,nowTs:h}}function Wm(){const t=W(se=>se.timeFormatPreference),[s,n]=l.useState("checking"),[a,r]=l.useState(null),[o,c]=l.useState(null),[i,d]=l.useState(null),[h,p]=l.useState(null),[m,u]=l.useState(!1),[f,v]=l.useState(!1),[g,b]=l.useState("cloudflare"),[w,k]=l.useState(()=>la("cloudflare")),[N,A]=l.useState([]),[j,x]=l.useState("managed-remote"),[P,C]=l.useState([]),[y,L]=l.useState(null),{bootstrapTtlMs:I,setBootstrapTtlMs:T,sessionTtlMs:E,setSessionTtlMs:U,isSavingTtl:_,handleBootstrapTtlChange:O,handleSessionTtlChange:V}=Hm(),H=l.useCallback(async se=>{v(!0);try{await Ke(se),Object.prototype.hasOwnProperty.call(se,"tunnelMode")&&se.tunnelMode&&x(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=Km({saveTunnelSettings:H,setManagedRemoteValidationError:p}),{managedRemoteTunnelPresets:X,setManagedRemoteTunnelPresets:we,expandedManagedRemoteTunnels:ie,setExpandedManagedRemoteTunnels:ke,selectedPresetId:oe,setSelectedPresetId:ae,sessionTokensByPresetId:me,setSessionTokensByPresetId:le,savedTokenPresetIds:Q,setSavedTokenPresetIds:G,isAddingPreset:Pe,setIsAddingPreset:re,newPresetName:xe,setNewPresetName:ve,newPresetHostname:Ne,setNewPresetHostname:K,newPresetToken:ce,setNewPresetToken:z,selectedPreset:J,persistManagedRemoteTunnelToken:te,handleSelectPreset:et,handleSaveNewPreset:$,handleRemovePreset:Y}=ne,de=Vm({saveTunnelSettings:H}),{managedLocalConfigPath:Z,setManagedLocalConfigPath:fe,managedLocalConfigExtensionError:We,managedLocalConfigFileInputRef:jt,isManagedLocalConfigPathInvalid:Qe,handleBrowseManagedLocalConfig:at,handleManagedLocalConfigInputChange:Tt,handleManagedLocalConfigInputBlur:Ut,handleManagedLocalConfigClear:bs,handleManagedLocalConfigFileSelected:Hs}=de,En=l.useCallback(se=>{G(se)},[G]),{qrDataUrl:Ft,remainingText:An,nowTs:It}=Gm({tunnelInfo:a,state:s,setSessionRecords:C,setSavedTokenPresetIds:En,setLocalPort:L}),Ln=l.useMemo(()=>P.map(se=>{const Se=se.expiresAt<=It,Ye=se.status==="active"&&!Se,ge=Ye?wo(se.expiresAt-It):se.inactiveReason==="expired"||Se?"expired":"inactive",wt=ge==="expired"?"Expired":se.inactiveReason==="tunnel-revoked"?"Revoked":"Inactive",dt=Kt(se.mode);return{...se,isActive:Ye,mode:dt,remainingTextForSession:ge,inactiveLabel:wt}}),[It,P]),Mn=l.useMemo(()=>a?.connectUrl?a.bootstrapExpiresAt===null?!0:a.bootstrapExpiresAt>It:!1,[It,a?.bootstrapExpiresAt,a?.connectUrl]),Rn=l.useMemo(()=>!a||s!=="active"&&s!=="stopping"?!1:o===j,[o,s,a,j]),Dn=l.useMemo(()=>!a||s!=="active"||!o?!1:o!==j,[o,s,a,j]),as=l.useMemo(()=>{if(typeof y=="number"&&Number.isFinite(y)&&y>0)return y;if(typeof window>"u")return null;const Se=ht()||window.location.href;let Ye=0;try{Ye=Number(new URL(Se).port)}catch{Ye=Number(window.location.port)}return Number.isFinite(Ye)&&Ye>0?Ye:null},[y]),Et=l.useMemo(()=>N.find(se=>se.provider===g)??null,[N,g]),_n=l.useMemo(()=>{const se=new Set(Et?.modes?.map(Se=>Se.key).filter(Se=>Se==="managed-remote"||Se==="managed-local"));return se.size===0?ba:ba.filter(Se=>se.has(Se.value))},[Et]),zn=l.useMemo(()=>w.provider===g?w:la(g),[w,g]),On=l.useCallback(async se=>{await us(se)},[]),pe=l.useCallback((se,Se)=>(k(la(Se,se)),se.available===!0),[]),Bt=l.useCallback(async se=>{try{const[Se,Ye,ge,wt]=await Promise.all([Ee("/api/pichamber/tunnel/check",{signal:se}),Ee("/api/pichamber/tunnel/status",{signal:se}),Ee("/api/pi/ui-settings",{signal:se,headers:{Accept:"application/json"}}),Ee("/api/pichamber/tunnel/providers",{signal:se})]),dt=await Se.json(),be=await Ye.json(),tt=ge.ok?await ge.json():{},kt=wt.ok?await wt.json():{},ys=be.ttlConfig?.bootstrapTtlMs??(tt?.tunnelBootstrapTtlMs===null?null:typeof tt?.tunnelBootstrapTtlMs=="number"?tt.tunnelBootstrapTtlMs:1800*1e3),js=typeof be.ttlConfig?.sessionTtlMs=="number"?be.ttlConfig.sessionTtlMs:typeof tt?.tunnelSessionTtlMs=="number"?tt.tunnelSessionTtlMs:480*60*1e3,ws=Kt(be.mode??tt?.tunnelMode),Ws="cloudflare",$n=typeof tt?.managedLocalTunnelConfigPath=="string"&&tt.managedLocalTunnelConfigPath.trim()||null,Kn=pe(dt,Ws),qs=Mm(be?.managedRemoteTunnelPresets),rs=typeof be.managedRemoteTunnelHostname=="string"?be.managedRemoteTunnelHostname:"",Qs=qs.length>0?qs:rs?[{id:`legacy-${bn(rs)}`,name:rs,hostname:bn(rs)}]:[],ks=Qs[0]?.id||"";if(T(ys),U(js),b(Ws),A(Array.isArray(kt?.providers)?kt.providers:[]),x(ws),fe($n),we(Qs),ae(ks),C(Array.isArray(be.activeSessions)?be.activeSessions:[]),c(be.activeTunnelMode?Kt(be.activeTunnelMode):be.active&&be.mode?Kt(be.mode):null),G(new Set(Array.isArray(be.managedRemoteTunnelTokenPresetIds)?be.managedRemoteTunnelTokenPresetIds:[])),L(typeof be.localPort=="number"?be.localPort:null),be.active&&be.url){r({url:be.url,connectUrl:null,bootstrapExpiresAt:typeof be.bootstrapExpiresAt=="number"?be.bootstrapExpiresAt:null}),n("active");return}n(Kn?"idle":"not-available")}catch{se.aborted||(n("error"),d("Failed to check tunnel availability"))}},[pe,T,fe,we,G,ae,U]);l.useEffect(()=>{const se=new AbortController;return Bt(se.signal),()=>se.abort()},[Bt]);const Un=l.useCallback(async()=>{if(d(null),p(null),j==="managed-local"&&Z&&!Ts(Z)){d(We),B.error(We);return}n("starting");try{let se="",Se="";if(j==="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,Se=(me[J.id]||"").trim(),await H({tunnelMode:"managed-remote",managedRemoteTunnelPresets:X})}const Ye=await Ee("/api/pichamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:g,mode:j,...j==="managed-remote"&&J?{managedRemoteTunnelPresetId:J.id,managedRemoteTunnelPresetName:J.name}:{},...j==="managed-remote"&&se?{managedRemoteTunnelHostname:se}:{},...j==="managed-remote"&&Se?{managedRemoteTunnelToken:Se}:{},...j==="managed-local"&&Z?{configPath:Z}:{}})}),ge=await Ye.json();if(!Ye.ok||!ge.ok){if(j==="managed-remote"&&typeof ge.error=="string"&&ge.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(ge.error||"Failed to start tunnel"),B.error(ge.error||"Failed to start tunnel");return}const wt=typeof ge.url=="string"?ge.url:"";if(!wt){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:wt,connectUrl:typeof ge.connectUrl=="string"?ge.connectUrl:null,bootstrapExpiresAt:typeof ge.bootstrapExpiresAt=="number"?ge.bootstrapExpiresAt:null}),c(ge.activeTunnelMode?Kt(ge.activeTunnelMode):ge.mode?Kt(ge.mode):j),C(Array.isArray(ge.activeSessions)?ge.activeSessions:[]),Array.isArray(ge.managedRemoteTunnelTokenPresetIds)&&G(new Set(ge.managedRemoteTunnelTokenPresetIds)),typeof ge.localPort=="number"&&L(ge.localPort),typeof ge.mode=="string"&&x(Kt(ge.mode)),n("active"),ge.replacedTunnel){const dt=typeof ge.revokedBootstrapCount=="number"?ge.revokedBootstrapCount:0,be=typeof ge.invalidatedSessionCount=="number"?ge.invalidatedSessionCount:0;dt===1&&be===1?B.warning("Replaced previous tunnel: revoked 1 link, invalidated 1 session."):dt===1?B.warning(`Replaced previous tunnel: revoked 1 link, invalidated ${be} sessions.`):be===1?B.warning(`Replaced previous tunnel: revoked ${dt} links, invalidated 1 session.`):B.warning(`Replaced previous tunnel: revoked ${dt} links, invalidated ${be} sessions.`)}else B.success("Tunnel link ready")}catch{n("error"),d("Failed to start tunnel"),B.error("Failed to start tunnel")}},[We,Z,X,H,J,me,p,G,j,g]),Fn=l.useCallback(async()=>{n("stopping");try{await Ee("/api/pichamber/tunnel/stop",{method:"POST"});const se=await Ee("/api/pichamber/tunnel/status");if(se.ok){const Se=await se.json();C(Array.isArray(Se.activeSessions)?Se.activeSessions:[]),G(new Set(Array.isArray(Se.managedRemoteTunnelTokenPresetIds)?Se.managedRemoteTunnelTokenPresetIds:[])),L(typeof Se.localPort=="number"?Se.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]),Bn=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]),Gs=l.useCallback(async se=>{p(null),d(null),s!=="active"&&s!=="stopping"&&s!=="starting"&&n("idle"),await H({tunnelMode:se,managedRemoteTunnelPresets:X})},[X,H,p,s]);return{timeFormatPreference:t,state:s,tunnelInfo:a,activeTunnelMode:o,qrDataUrl:Ft,errorMessage:i,managedRemoteValidationError:h,setManagedRemoteValidationError:p,copied:m,isSavingTtl:_,isSavingMode:f,tunnelProvider:g,dependencyInstallInfo:w,providerCapabilities:N,tunnelMode:j,managedLocalConfigPath:Z,managedRemoteTunnelPresets:X,expandedManagedRemoteTunnels:ie,setExpandedManagedRemoteTunnels:ke,selectedPresetId:oe,sessionTokensByPresetId:me,setSessionTokensByPresetId:le,savedTokenPresetIds:Q,isAddingPreset:Pe,setIsAddingPreset:re,newPresetName:xe,setNewPresetName:ve,newPresetHostname:Ne,setNewPresetHostname:K,newPresetToken:ce,setNewPresetToken:z,bootstrapTtlMs:I,sessionTtlMs:E,remainingText:An,sessionRecords:P,nowTs:It,localPort:y,managedLocalConfigExtensionError:We,managedLocalConfigFileInputRef:jt,isManagedLocalConfigPathInvalid:Qe,selectedPreset:J,renderedSessionRecords:Ln,isConnectLinkLive:Mn,isSelectedModeTunnelReady:Rn,willReplaceActiveTunnel:Dn,suggestedConnectorPort:as,selectedProviderCapability:Et,tunnelModeOptions:_n,displayedDependencyInstallInfo:zn,openExternal:On,handleBrowseManagedLocalConfig:at,handleManagedLocalConfigInputChange:Tt,handleManagedLocalConfigInputBlur:Ut,handleManagedLocalConfigClear:bs,handleManagedLocalConfigFileSelected:Hs,handleStart:Un,handleStop:Fn,handleCopyUrl:Bn,handleBootstrapTtlChange:O,handleSessionTtlChange:V,handleModeChange:Gs,handleSelectPreset:et,handleSaveNewPreset:$,handleRemovePreset:Y,persistManagedRemoteTunnelToken:te}}const qm=()=>{const{timeFormatPreference:t,state:s,tunnelInfo:n,qrDataUrl:a,errorMessage:r,managedRemoteValidationError:o,setManagedRemoteValidationError:c,copied:i,isSavingTtl:d,isSavingMode:h,tunnelMode:p,managedLocalConfigPath:m,managedRemoteTunnelPresets:u,expandedManagedRemoteTunnels:f,setExpandedManagedRemoteTunnels:v,selectedPresetId:g,sessionTokensByPresetId:b,setSessionTokensByPresetId:w,savedTokenPresetIds:k,isAddingPreset:N,setIsAddingPreset:A,newPresetName:j,setNewPresetName:x,newPresetHostname:P,setNewPresetHostname:C,newPresetToken:y,setNewPresetToken:L,bootstrapTtlMs:I,sessionTtlMs:T,remainingText:E,managedLocalConfigExtensionError:U,managedLocalConfigFileInputRef:_,isManagedLocalConfigPathInvalid:O,selectedPreset:V,renderedSessionRecords:H,isConnectLinkLive:ne,isSelectedModeTunnelReady:X,willReplaceActiveTunnel:we,suggestedConnectorPort:ie,tunnelModeOptions:ke,displayedDependencyInstallInfo:oe,openExternal:ae,handleBrowseManagedLocalConfig:me,handleManagedLocalConfigInputChange:le,handleManagedLocalConfigInputBlur:Q,handleManagedLocalConfigClear:G,handleManagedLocalConfigFileSelected:Pe,handleStart:re,handleStop:xe,handleCopyUrl:ve,handleBootstrapTtlChange:Ne,handleSessionTtlChange:K,handleModeChange:ce,handleSelectPreset:z,handleSaveNewPreset:J,handleRemovePreset:te,persistManagedRemoteTunnelToken:et}=Wm(),$="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(_m,{records:H,timeFormatPreference:t}),s==="not-available"&&e.jsx(zm,{installInfo:oe}),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(Dm,{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:ke.map(Y=>e.jsxs(li,{children:[e.jsx(ci,{asChild:!0,children:e.jsx(S,{variant:"chip",size:"xs","aria-pressed":p===Y.value,className:"!font-normal",onClick:()=>{ce(Y.value)},disabled:h||s==="starting"||s==="stopping",children:Y.label})}),e.jsx(lc,{sideOffset:8,className:"max-w-xs",children:Y.tooltip})]},Y.value))})]})]}),e.jsx(Om,{bootstrapTtlMs:I,sessionTtlMs:T,disabled:d||h||s==="starting"||s==="stopping",onBootstrapTtlChange:Y=>{Ne(Y)},onSessionTtlChange:Y=>{K(Y)}}),p==="managed-remote"&&e.jsx(Um,{suggestedConnectorPort:ie,managedRemoteTunnelPresets:u,expandedManagedRemoteTunnels:f,sessionTokensByPresetId:b,savedTokenPresetIds:k,disabled:s==="starting"||s==="stopping"||h,isAddingPreset:N,newPresetName:j,newPresetHostname:P,newPresetToken:y,managedRemoteValidationError:o,selectedPreset:V,onToggleAddPreset:()=>A(Y=>!Y),onCancelAddPreset:()=>{A(!1),x(""),C(""),L("")},onNewPresetNameChange:x,onNewPresetHostnameChange:C,onNewPresetTokenChange:L,onSaveNewPreset:()=>{J()},onTogglePresetCollapse:(Y,de)=>{v(Z=>({...Z,[Y]:de})),de&&z(Y)},onRemovePreset:Y=>{te(Y)},onPresetTokenChange:(Y,de)=>{c(null),w(Z=>({...Z,[Y]:de}))},onPersistToken:Y=>{et(Y)}}),p==="managed-local"&&e.jsx(Fm,{managedLocalConfigPath:m,isManagedLocalConfigPathInvalid:O,managedLocalConfigExtensionError:U,disabled:s==="starting"||s==="stopping"||h,fileInputRef:_,onInputChange:le,onInputBlur:()=>{Q()},onBrowse:()=>{me()},onClear:()=>{G()},onFileSelected:Y=>{Pe(Y)}}),!X&&e.jsx(Bm,{tunnelMode:p,selectedPresetId:g,managedRemoteTunnelPresets:u,selectedPreset:V,willReplaceActiveTunnel:we,state:s,isSavingMode:h,isManagedLocalConfigPathInvalid:O,primaryCtaClass:$,onSelectPreset:Y=>{z(Y)},onStart:re,onOpenDocUrl:Y=>{ae(Y)}})]}),X&&n&&e.jsx($m,{tunnelInfo:n,isConnectLinkLive:ne,copied:i,onCopyUrl:ve,remainingText:E,qrDataUrl:a,onNewConnectLink:re,onStop:xe,stopping:s==="stopping",isSavingMode:h,isManagedLocalConfigPathInvalid:O,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"})]})]})})},ko=()=>{const t=Fe(),s=t&&ss(),n=s&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[a,r]=D.useState(!0),[o,c]=D.useState(!1),[i,d]=D.useState(!1),[h,p]=D.useState(!1),[m,u]=D.useState(!1),[f,v]=D.useState(!1),[g,b]=D.useState(!1),[w,k]=D.useState(!1),[N,A]=D.useState(!1),[j,x]=D.useState(!0),[P,C]=D.useState(!1),[y,L]=D.useState(!0),[I,T]=D.useState(!0),[E,U]=D.useState(!1),[_,O]=D.useState(!1),[V,H]=D.useState(!1),[ne,X]=D.useState(null);D.useEffect(()=>{if(!s){r(!1);return}let Q=!1;return(async()=>{try{const G=await Ee("/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),X(null)}catch(G){Q||X(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 ml();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 hl();Q||(v(G?.supported===!0),b(G?.enabled===!0))})(),()=>{Q=!0}},[t]),D.useEffect(()=>{if(!t){A(!1);return}let Q=!1;return(async()=>{const G=await fl();Q||(A(G?.supported===!0),x(G?.enabled===!0))})(),()=>{Q=!0}},[t]),D.useEffect(()=>{if(!t){U(!1);return}let Q=!1;return(async()=>{const G=await gl();Q||(U(G?.supported===!0),O(G?.enabled===!0))})(),()=>{Q=!0}},[t]);const we=I!==y,ie=a||o||!we,ke=D.useCallback(async()=>{if(!i||m)return;const Q=!h;p(Q),u(!0),X(null);try{const G=await xl(Q);if(!G?.supported)throw new Error("Launch at login is not supported on this system");p(G.enabled)}catch(G){p(!Q),X(G instanceof Error?G.message:"Failed to update launch at login setting")}finally{u(!1)}},[m,h,i]),oe=D.useCallback(async()=>{if(!f||w)return;const Q=!g;b(Q),k(!0),X(null);try{const G=await vl(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),X(G instanceof Error?G.message:"Failed to update system tray setting")}finally{k(!1)}},[w,g,f]),ae=D.useCallback(async()=>{if(!N||P)return;const Q=!j;x(Q),C(!0),X(null);try{const G=await bl(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");x(G.enabled)}catch(G){x(!Q),X(G instanceof Error?G.message:"Failed to update close behavior")}finally{C(!1)}},[j,N,P]),me=D.useCallback(async()=>{if(!E||V)return;const Q=!_;O(Q),H(!0),X(null);try{const G=await yl(Q);if(!G?.supported)throw new Error("Preventing sleep is not supported on this system");O(G.enabled)}catch(G){O(!Q),X(G instanceof Error?G.message:"Failed to update keep awake setting")}finally{H(!1)}},[V,_,E]),le=D.useCallback(async()=>{if(we){c(!0),X(null);try{if(!(await Ee("/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 Jr())throw new Error("Saved, but failed to restart app")}catch(Q){X(Q instanceof Error?Q.message:"Failed to save desktop settings"),c(!1)}}},[I,we]);return t?e.jsx(q,{title:"Desktop",children:e.jsxs("div",{className:"space-y-3",children:[i||n||f||N||E?e.jsxs("div",{className:ft,children:[i?e.jsx(Ce,{settingsItem:"sessions.desktop-launch-at-login",checked:h,onChange:Q=>{Q!==h&&ke()},disabled:m,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(Ce,{settingsItem:"sessions.desktop-mac-menu-bar",checked:I,onChange:T,disabled:a||o,label:"Show PiChamber in the menu bar",info:"Requires an app restart. When off, PiChamber does not create the menu bar item or run its session, approval, and usage updates.",ariaLabel:"Show PiChamber in the macOS menu bar"}):null,f?e.jsx(Ce,{settingsItem:"sessions.desktop-minimize-to-tray",checked:g,onChange:Q=>{Q!==g&&oe()},disabled:w,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,N?e.jsx(Ce,{settingsItem:"sessions.desktop-close-to-tray",checked:j,onChange:Q=>{Q!==j&&ae()},disabled:P,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,E?e.jsx(Ce,{settingsItem:"sessions.desktop-keep-awake",checked:_,onChange:Q=>{Q!==_&&me()},disabled:V,label:"Keep computer awake while PiChamber is running",info:"Prevents system sleep so phones can keep reaching this app. The screen can still turn off.",ariaLabel:"Keep computer awake while PiChamber is running"}):null]}):null,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:le,disabled:ie,className:"shrink-0 !font-normal",children:o?"Saving...":"Save + Restart"})}):null]})}):null},No=new Set(["shift","control","alt","meta"]),Qm=t=>{if(No.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),ut(s.join("+"))):null},Jm=t=>{const s=[];if((t.metaKey||t.ctrlKey)&&s.push("mod"),t.shiftKey&&s.push("shift"),t.altKey&&s.push("alt"),No.has(t.key.toLowerCase()))return s.length>0?ut(s.join("+")):null;const n=ka(t.key);return n?(s.push(n),s.length>0?ut(s.join("+")):null):null},Ym={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"},Xm=()=>{const t=W(j=>j.shortcutOverrides),s=W(j=>j.setShortcutOverride),n=W(j=>j.clearShortcutOverride),a=W(j=>j.resetAllShortcutOverrides),r=l.useMemo(()=>jl(),[]),o=l.useCallback((j,x)=>Ym[j]??x,[]),[c,i]=l.useState(null),[d,h]=l.useState({}),[p,m]=l.useState(""),[u,f]=l.useState(""),[v,g]=l.useState(null),b=l.useCallback(j=>{Ke({shortcutOverrides:j})},[]),w=l.useCallback((j,x)=>{const P=ut(x);for(const C of r){if(C.id===j)continue;const y=Ya(C.id,t);if(ut(y)===P)return C.id}return null},[r,t]),k=l.useCallback((j,x)=>{const P=ut(x),C=w(j,P);if(C){g({actionId:j,combo:P,conflictActionId:C}),m("");return}const y={...t,[j]:P};s(j,P),b(y),g(null),m(""),f(Xa(P)?"This shortcut can conflict with browser defaults. It is still saved.":""),h(L=>{const I={...L};return delete I[j],I})},[w,b,s,t]),N=l.useCallback(()=>{if(!v)return;const j={...t,[v.conflictActionId]:Hn,[v.actionId]:v.combo};s(v.conflictActionId,Hn),s(v.actionId,v.combo),b(j),g(null),m(""),f(Xa(v.combo)?"This shortcut can conflict with browser defaults. It is still saved.":""),h(x=>{const P={...x};return delete P[v.actionId],P})},[v,b,s,t]),A=l.useCallback(j=>{const x={...t};delete x[j],n(j),b(x),h(P=>{const C={...P};return delete C[j],C}),g(null),m(""),f("")},[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({}),h({}),g(null),m(""),f("")},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:N,children:"Overwrite"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>g(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((j,x)=>{const P=j.id==="switch_context_surface",C=P?wl(j.id,t):Ya(j.id,t),y=d[j.id],L=y??C,I=typeof y=="string"&&ut(y)!==ut(C),T=L===""||ut(L)===Hn,E=c===j.id?"Press keys...":P&&!T?`${Za(L)} + 1…0`:Za(L);return e.jsx("div",{className:F("py-1.5",x>0&&"border-t border-border/40"),children:e.jsxs(Ie,{label:o(j.id,j.label),alignEnd:!1,children:[e.jsx(ee,{readOnly:!0,value:E,onFocus:()=>{i(j.id),m("")},onBlur:()=>{c===j.id&&i(null)},onKeyDown:U=>{if(U.preventDefault(),U.stopPropagation(),U.key==="Escape"){i(null);return}const _=P?Jm(U):Qm(U);_&&(h(O=>({...O,[j.id]:_})),i(null),g(null),m(""))},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 U=d[j.id];if(!U){m("Capture a shortcut first.");return}k(j.id,U)},disabled:!I,children:"Save changes"}),e.jsx(S,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>A(j.id),children:"Reset"})]})},j.id)})})]})},Zm=new Set(["shift","control","alt","meta"]),eh=t=>{if(Zm.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=ut(s.join("+"));return s.length>1?a:null},th=({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:o=>n({...t,label:o.target.value}),className:F(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:o=>n({...t,command:o.target.value}),className:F(r,"w-40")})]}),e.jsx(ee,{value:t.args??"",placeholder:"Arguments (optional)","aria-label":`Trigger ${s+1} arguments`,onChange:o=>n({...t,args:o.target.value}),className:F(r,"flex-1")}),e.jsx("input",{value:t.combo?t.combo.replace(/\+/g,"+"):"",placeholder:"Keybinding","aria-label":`Trigger ${s+1} keybinding`,readOnly:!0,onKeyDown:o=>{const c=eh(o);c&&(o.preventDefault(),n({...t,combo:c}))},className:F(r,"w-32 rounded-md border")}),e.jsx(S,{variant:"ghost",size:"icon",onClick:a,"aria-label":`Remove trigger ${t.label}`,children:e.jsx(R,{name:"close",className:"size-4"})})]})},sh=()=>{const t=W(o=>o.commandTriggers),s=l.useCallback(async o=>{W.setState({commandTriggers:o});try{await Ke({commandTriggers:o})}catch{Te("error")}},[]),n=(o,c)=>{const i=t.map((d,h)=>h===o?c:d);s(kl(i)??[])},a=o=>{const c=t.filter((i,d)=>d!==o);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(Ie,{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((o,c)=>e.jsx(th,{trigger:o,index:c,onChange:i=>n(c,i),onRemove:()=>a(c)},o.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."})]})},nh=({section:t})=>{const{isMobile:s}=lt(),n=s&&Gt(),a=Fe();if(!t)return e.jsxs(ye,{className:"pichamber-page-body space-y-3 sm:space-y-6",children:[e.jsx(In,{}),e.jsx(yo,{}),a&&e.jsx(ko,{}),e.jsx(bo,{}),n&&e.jsx(Ki,{})]});const r=()=>{switch(t){case"general":return e.jsx(rh,{});case"visual":return e.jsx(ih,{});case"chat":return e.jsx(oh,{});case"sessions":return e.jsx(lh,{});case"shortcuts":return e.jsx(ah,{});case"git":return e.jsx(ch,{});case"github":return e.jsx(dh,{});case"notifications":return e.jsx(uh,{});case"tunnel":return e.jsx(ph,{});default:return null}},o={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(ye,{title:s?void 0:o,description:s?void 0:c,className:"pichamber-page-body",children:r()})},ah=()=>e.jsxs(e.Fragment,{children:[e.jsx(Xm,{}),e.jsx(sh,{})]}),rh=()=>{const t=Fe();return e.jsxs(e.Fragment,{children:[t&&e.jsx(ko,{}),e.jsx(In,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar","terminalQuickKeys","terminalShell","terminalLoginShell","perfHud"]}),e.jsx(vm,{})]})},ih=()=>e.jsx(In,{visibleSettings:["theme","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat","weekStart","sidebarViewMode","fontSize","terminalFontSize","editorFontSize","wrapLinesByDefault","spacing","inputBarOffset"]}),oh=()=>e.jsx(In,{visibleSettings:["diffLayout","followUpBehavior"]}),lh=()=>e.jsxs(e.Fragment,{children:[e.jsx(yo,{}),e.jsx(bo,{})]}),ch=()=>e.jsx(Ka,{}),dh=()=>e.jsx(Ka,{}),uh=()=>e.jsx(Nm,{}),ph=()=>e.jsx(qm,{}),Ss="openai-compatible",mh=t=>`${Math.round(t/1024/1024)} MB`;function hh(){const[t,s]=l.useState(null),[n,a]=l.useState(null),[r,o]=l.useState(""),[c,i]=l.useState(""),[d,h]=l.useState(""),[p,m]=l.useState(null),[u,f]=l.useState(!1),v=l.useCallback(async N=>{const A=await cc(N);s(A),s(A),a(null);const j=A.config.providers.find(x=>x.id===Ss);j&&(o(j.baseUrl),i(j.model))},[]);l.useEffect(()=>{v().catch(N=>a(N.message))},[v]),l.useEffect(()=>{if(!t?.models.some(A=>A.downloading))return;const N=window.setInterval(()=>{v({fresh:!0}).catch(()=>{})},1500);return()=>window.clearInterval(N)},[v,t?.models]);const g=l.useCallback(async N=>{Te("saving");try{const A=await Ee("/api/stt/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!A.ok)throw new Error((await A.json().catch(()=>null))?.error||"Could not save dictation settings");const j=await A.json();s(x=>x&&{...x,config:j.config}),Te("saved")}catch(A){throw Te("error"),A}},[]),b=async(N,A)=>{m(N);try{const j=A==="POST"?"/download":"",x=await Ee(`/api/stt/models/${encodeURIComponent(N)}${j}`,{method:A});if(!x.ok)throw new Error((await x.json().catch(()=>null))?.error||"Model action failed");await v({fresh:!0})}catch(j){a(j instanceof Error?j.message:String(j))}finally{m(null)}},w=async()=>{f(!0);try{await g({remoteProvider:{id:Ss,label:"OpenAI-compatible",baseUrl:r,model:c,apiKey:d||void 0},providerConfigId:Ss}),h("")}catch(N){a(N instanceof Error?N.message:String(N))}finally{f(!1)}};if(!t)return e.jsx(ye,{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(N=>N.id===Ss);return e.jsxs(ye,{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(Ce,{checked:t.config.enabled,onChange:N=>{g({enabled:N}).catch(A=>a(A.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(Ie,{label:"Transcription provider",settingsItem:"dictation.provider",children:e.jsxs(Re,{value:t.config.providerConfigId,onValueChange:N=>{g({providerConfigId:N}).catch(A=>a(A.message))},children:[e.jsx(De,{size:Be,className:hs,"aria-label":"Transcription provider",children:e.jsx(_e,{})}),e.jsxs(ze,{children:[e.jsx(je,{value:"local",children:"Local model"}),e.jsx(je,{value:Ss,disabled:!k,children:"OpenAI-compatible"})]})]})}),e.jsx(Ie,{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:N=>s(A=>A&&{...A,config:{...A.config,language:N.target.value}}),onBlur:()=>{g({language:t.config.language}).catch(N=>a(N.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(N=>e.jsxs("div",{className:"flex min-h-10 items-center gap-3 py-1.5",children:[e.jsx(dc,{checked:t.config.localModelId===N.id,onChange:()=>{g({localModelId:N.id,providerConfigId:"local"}).catch(A=>a(A.message))},ariaLabel:`Use ${N.description}`}),e.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>{g({localModelId:N.id,providerConfigId:"local"}).catch(A=>a(A.message))},children:[e.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:N.description}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:mh(N.sizeBytes)})]}),N.downloading?e.jsx("span",{className:"typography-meta tabular-nums text-muted-foreground",children:N.downloadProgress===null?"Downloading...":`Downloading ${N.downloadProgress}%`}):N.installed?e.jsxs(e.Fragment,{children:[e.jsx(R,{name:"check",className:"size-4 text-[var(--status-success)]","aria-label":"Installed"}),e.jsx(S,{className:nt,variant:"ghost",size:"icon",disabled:p===N.id,onClick:()=>{b(N.id,"DELETE")},title:"Delete model","aria-label":`Delete ${N.description}`,children:e.jsx(R,{name:"delete-bin",className:"size-4"})})]}):e.jsx(S,{variant:"outline",size:"sm",disabled:p===N.id,onClick:()=>{b(N.id,"POST")},children:N.corrupt||N.downloadError?"Retry":"Download"})]},N.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(Ae,{label:"Server URL",children:e.jsx(ee,{value:r,onChange:N=>o(N.target.value),placeholder:"https://api.openai.com/v1",className:"h-8"})}),e.jsx(Ae,{label:"Model",children:e.jsx(ee,{value:c,onChange:N=>i(N.target.value),placeholder:"whisper-1",className:"h-8"})}),e.jsx(Ae,{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:N=>h(N.target.value),placeholder:k?.apiKeyConfigured?"Stored key":"Optional",className:"h-8",autoComplete:"off"})}),e.jsx("div",{className:ps,children:e.jsx(S,{onClick:()=>{w()},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 Br=256,$r=280,fh=["general","appearance","chat","dictation","notifications","sessions","shortcuts","about","projects","remote-access","servers","tunnel","git","providers","behavior","snippets","prompt-templates","skills.installed","plugins"];function Co(t,s){return t.isAvailable?.(s)??!0}function gh(t,s,n=!1){return{isWeb:!t&&Gt(),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 xh(){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:vc,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 o=Is(t);if(o&&!Co(o,n))return e.jsx(xh,{});switch(t){case"projects":return e.jsx(Cu,{});case"remote-access":return e.jsx(Tr,{});case"servers":return e.jsx(gp,{onActiveConnectionDeleted:r});case"remote-instances":return e.jsx(Tr,{});case"behavior":return e.jsx(jd,{});case"skills.installed":return e.jsx(Nd,{});case"plugins":return e.jsx(fu,{});case"providers":return e.jsx(Kp,{});case"about":return e.jsx(ye,{title:s?void 0:"About",children:e.jsx(Ki,{})});case"snippets":return e.jsx(Gp,{});case"prompt-templates":return e.jsx(Yp,{});case"dictation":return e.jsx(hh,{});case"git":return e.jsx(ye,{title:s?void 0:"Git",children:e.jsx(Ka,{})});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"tunnel":{const c=a[t]??"visual";return e.jsx(nh,{section:c})}default:return null}}const vh=["general","projects","agent"];function bh({isMobile:t,isMobileSettingsSearchOpen:s,settingsSearchQuery:n,setSettingsSearchQuery:a,handleSettingsSearchKeyDown:r,settingsSearchResults:o,groupedSettingsSearchResults:c,activeSearchResultIndex:i,setActiveSearchResultIndex:d,searchResultRefs:h,keyboardSearchNavigationRef:p,openSearchResult:m,sortedFilteredPages:u,settingsSlug:f,mobileStage:v,openPage:g,getPageTitle:b,activeRemoteLabel:w,mobileAppActions:k}){const N=n.trim().length>0,A=t?s&&N:N;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[t?A?null:e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("button",{type:"button",onClick:()=>{if(k?.openInstances){k.openInstances();return}g("servers")},className:F("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",w?"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:w?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:w}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-[var(--status-success)] animate-pulse","aria-hidden":!0}),e.jsx("span",{className:"text-[var(--status-success)]",children:"Connected"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"typography-ui-label font-medium text-foreground truncate",children:"Not connected"}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0 typography-micro",children:[e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"text-muted-foreground",children:"Select a server"})]})]}),e.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:"Manage servers & pair devices"})]})}),e.jsx(R,{name:"arrow-right-s",className:"size-4 shrink-0 text-muted-foreground"})]})}):e.jsx("div",{className:"px-3 pt-3",children:e.jsxs("div",{className:"flex h-10 items-center gap-1.5 rounded-md border border-border bg-transparent px-2 text-muted-foreground focus-within:ring-2 focus-within:ring-primary/40 sm:h-8",children:[e.jsx(R,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{value:n,onChange:j=>a(j.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"}),N&&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(R,{name:"close",className:"h-3.5 w-3.5"})})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden",children:e.jsx("div",{className:"flex flex-col gap-0.5 px-3 pt-3 pb-2",children:A?o.length>0?(()=>{let j=0;return c.map(x=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"px-2 pb-0.5 pt-2 typography-micro font-medium text-subtle-foreground",children:x.pageTitle}),x.results.map(P=>{const C=j;j+=1;const y=C===i,L=!!P.description;return e.jsxs("button",{type:"button",ref:I=>{h.current[C]=I},onMouseMove:()=>{p.current=!1,d(C)},onClick:()=>m(P),className:F("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",y?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:P.title}),L&&e.jsx("span",{className:"typography-micro text-subtle-foreground line-clamp-2",children:P.description})]},P.id)})]},x.page))})():e.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:"No matching settings"}):(()=>{const j=new Map;for(const P of u){const C=P.group,y=j.get(C);y?y.push(P):j.set(C,[P])}return vh.map(P=>({group:P,pages:j.get(P)??[]})).filter(P=>P.pages.length>0).map(({group:P,pages:C},y)=>{const L=P==="projects"?"Workspace":P==="agent"?"Agent":null;return e.jsxs("div",{className:"space-y-0.5",children:[L?e.jsx("div",{className:F("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",y===0?"pt-1":"pt-4 sm:pt-3"),children:L}):null,C.map(I=>{const T=f===I.slug&&!(t&&v==="nav"),E=bc(I.slug);return E?e.jsx(li,{children:e.jsx(ci,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>g(I.slug),"aria-current":T?"page":void 0,className:F("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(R,{name:E,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})]},P)})})()})})]})}function yh(t){const[s,n]=l.useState(null);return l.useEffect(()=>{const a=async()=>{try{const{loadMobileConnections:c,isActiveRuntimeConnection:i}=await Yt(async()=>{const{loadMobileConnections:p,isActiveRuntimeConnection:m}=await Promise.resolve().then(()=>sd);return{loadMobileConnections:p,isActiveRuntimeConnection:m}},void 0),h=(await c().catch(()=>[])).find(p=>i(p));if(h){n(h.label);return}}catch{}if(t){n(t);return}try{const{desktopHostsGet:c}=await Yt(async()=>{const{desktopHostsGet:v}=await import("./index-CKKWVoND.js").then(g=>g.cL);return{desktopHostsGet:v}},__vite__mapDeps([4,5,1,6,2,7,8,9])),{buildLocalDesktopHost:i,getLocalDesktopOrigin:d,resolveCurrentDesktopHost:h}=await Yt(async()=>{const{buildLocalDesktopHost:v,getLocalDesktopOrigin:g,resolveCurrentDesktopHost:b}=await import("./index-CKKWVoND.js").then(w=>w.cM);return{buildLocalDesktopHost:v,getLocalDesktopOrigin:g,resolveCurrentDesktopHost:b}},__vite__mapDeps([4,5,1,6,2,7,8,9])),p=await c().catch(()=>({hosts:[]})),u=[i(d()),...p.hosts],f=h(u);if(f&&f.label&&f.label!=="Instance"){n(f.label);return}}catch{}const r=ht(),o=qe();if(o==="local"){n("Local");return}if(o.startsWith("relay:")){const c=o.split(":")[1]?.split("@")[0];n(c?`Relay ${c.slice(0,8)}`:"Private relay");return}if(o.startsWith("host:")){n(o.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 jh=[{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.light-theme",page:"appearance",title:"Light theme",keywords:["theme","color","light mode"]},{id:"appearance.dark-theme",page:"appearance",title:"Dark theme",keywords:["theme","color","dark mode"]},{id:"appearance.dock-badge",page:"appearance",title:"Dock badge",description:"Show a count of chats with unseen activity on the macOS dock icon.",keywords:["dock","badge","unread","unseen","counter","count","notification","macos"],isAvailable:t=>t.isMac},{id:"appearance.pwa-install-name",page:"appearance",title:"Install app name",description:"Used by PWA installation process.",keywords:["pwa","installed app"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.pwa-orientation",page:"appearance",title:"Install orientation",description:"Used by the installed web app. Reinstall the PWA after changing this.",keywords:["pwa","portrait","landscape"],isAvailable:t=>t.isWeb&&!t.isDesktop},{id:"appearance.mobile-keyboard-mode",page:"appearance",title:"Mobile keyboard behavior",description:"Default browser behavior is safest. Resize content asks supported browsers to shrink the app when the on-screen keyboard opens.",keywords:["mobile","keyboard","resize"],isAvailable:t=>t.isMobile&&t.isWeb&&!t.isDesktop},{id:"appearance.interface-font-size",page:"appearance",title:"Interface font size",keywords:["font","text size","ui scale"]},{id:"appearance.terminal-font-size",page:"appearance",title:"Terminal font size",keywords:["terminal","font","text size"]},{id:"appearance.terminal-shell",page:"general",title:"Terminal shell",description:"Restart the terminal to apply this change to the current session.",keywords:["terminal","shell","bash","zsh","fish","pwsh","powershell"]},{id:"appearance.editor-font-size",page:"appearance",title:"Editor font size",keywords:["editor","font","text size","code"]},{id:"appearance.spacing-density",page:"appearance",title:"Spacing density",keywords:["density","compact","comfortable","spacing"]},{id:"appearance.input-bar-offset",page:"appearance",title:"Input bar offset",description:"Raise input bar to avoid OS-level screen obstructions like home bars.",keywords:["input","home bar","offset"],isAvailable:t=>t.isMobile},{id:"appearance.auto-save-enabled",page:"general",title:"Auto-save files",description:"Automatically save file edits after you stop typing. Disable to require manual save.",keywords:["editor","autosave","auto-save","files","save"]},{id:"appearance.expanded-editor-toolbar",page:"general",title:"Always show editor toolbar (docked under the file tabs)",keywords:["editor","toolbar","tabs","docked","files"]},{id:"appearance.wrap-lines-by-default",page:"appearance",title:"Wrap long lines 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 Vr(t){return t.trim().toLocaleLowerCase()}function wh({query:t,runtimeCtx:s,visiblePageSlugs:n,getPageTitle:a}){const r=Vr(t);if(!r)return[];const o=n?new Set(n):null,c=r.split(/\s+/).filter(Boolean);return jh.flatMap(i=>{if(o&&!o.has(i.page))return[];const d=Is(i.page);if(!d||d.isAvailable&&!d.isAvailable(s)||i.isAvailable&&!i.isAvailable(s))return[];const h=i.title,p=i.description??null,m=Vr([h,p,a(i.page),...i.keywords??[]].filter(Boolean).join(" "));return c.every(u=>m.includes(u))?[{...i,title:h,description:p,pageTitle:a(i.page)}]:[]})}function kh({runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n,openPage:a,isMobile:r,setMobileStage:o,containerRef:c,settingsSlug:i}){const[d,h]=l.useState(""),[p,m]=l.useState(!1),u=l.useRef(null),[f,v]=l.useState(null),[g,b]=l.useState(0),w=l.useRef([]),k=l.useRef(0),N=l.useRef(!1),A=l.useMemo(()=>wh({query:d,runtimeCtx:t,visiblePageSlugs:s,getPageTitle:n}),[n,t,d,s]),j=l.useCallback(y=>{if(y.id.startsWith("snippets.")){const L=it.getState(),I=Kr("new-snippet",L.snippets.map(T=>T.name));return L.setSnippetDraft({name:I,scope:"global"}),L.setSelectedSnippet(null),y.id==="snippets.create"?"snippets.content":y.id}if(y.id.startsWith("prompt-templates.")){const L=ct.getState(),I=Kr("new-prompt",L.prompts.map(T=>T.name));return L.setPromptDraft({name:I,location:"global"}),L.setSelectedPrompt(null),y.id==="prompt-templates.create"?"prompt-templates.content":y.id}return y.id==="providers.connect"&&xa.getState().setSelectedProviderId(null),y.id},[]),x=l.useMemo(()=>{const y=[],L=new Map;for(const I of A){let T=L.get(I.page);T||(T={page:I.page,pageTitle:I.pageTitle,results:[]},L.set(I.page,T),y.push(T)),T.results.push(I)}return y},[A]);l.useEffect(()=>{b(0),k.current=0,N.current=!1},[d]),l.useEffect(()=>{k.current=g},[g]),l.useEffect(()=>{w.current[g]?.scrollIntoView({block:"nearest"})},[g]),l.useEffect(()=>{g>=A.length&&b(Math.max(0,A.length-1)),w.current.length=A.length},[g,A.length]);const P=l.useCallback(y=>{const L=j(y);v(L),a(y.page),r&&o("page-content")},[r,a,j,o]),C=l.useCallback(y=>{if(y.key==="Escape"){if(y.preventDefault(),d.trim()){h("");return}r&&p&&m(!1);return}if(d.trim()&&A.length!==0){if(y.key==="ArrowDown"){y.preventDefault(),N.current=!0,b(L=>(L+1)%A.length);return}if(y.key==="ArrowUp"){y.preventDefault(),N.current=!0,b(L=>(L-1+A.length)%A.length);return}if(y.key==="Enter"){y.preventDefault();const L=(k.current%A.length+A.length)%A.length,I=A[L]??A[0];I&&P(I)}}},[r,p,P,d,A]);return l.useEffect(()=>{const y=f;if(!y)return;let L=!1;const I=window.requestAnimationFrame(()=>{if(L)return;const T=typeof CSS<"u"&&CSS.escape?CSS.escape(y):y.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),E=c.current?.querySelector(`[data-settings-item="${T}"]`);if(E){v(null);for(let U=E.closest("details");U;U=U.parentElement?.closest("details")??null)U.open=!0;E.scrollIntoView({block:"center",behavior:"smooth"}),E.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{E.removeAttribute("data-settings-search-highlight")},1600)}});return()=>{L=!0,window.cancelAnimationFrame(I)}},[c,f,i]),{settingsSearchQuery:d,setSettingsSearchQuery:h,isMobileSettingsSearchOpen:p,setIsMobileSettingsSearchOpen:m,mobileSettingsSearchInputRef:u,activeSearchResultIndex:g,setActiveSearchResultIndex:b,searchResultRefs:w,keyboardSearchNavigationRef:N,settingsSearchResults:A,groupedSettingsSearchResults:x,openSearchResult:P,handleSettingsSearchKeyDown:C}}const Nh=({mobileStage:t,activePageMeta:s,getPageTitle:n,showBackButton:a,mobileBackButtonLabel:r,onBack:o,showOpenPageSidebarButton:c,onOpenPageSidebar:i,isMobileSettingsSearchOpen:d,setIsMobileSettingsSearchOpen:h,mobileSettingsSearchInputRef:p,settingsSearchQuery:m,setSettingsSearchQuery:u,handleSettingsSearchKeyDown:f,onClose:v,shortcutKey:g})=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:F("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:o,"aria-label":r,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):null,e.jsx("div",{className:"min-w-0 flex-1 px-2 typography-ui-label font-medium text-foreground truncate",children:t==="nav"?"Settings":s?n(s.slug):"Settings"}),c&&e.jsx("button",{type:"button",onClick:i,"aria-label":"Open section list",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"list-unordered",className:"h-5 w-5"})}),t==="nav"?e.jsx("button",{type:"button",onClick:()=>{const b=!d;h(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(R,{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 (${g}+,)`,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(R,{name:"close",className:"h-5 w-5"})})]}),t==="nav"&&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(R,{name:"search",className:"h-4 w-4 shrink-0"}),e.jsx("input",{ref:p,value:m,onChange:b=>u(b.target.value),onKeyDown:f,placeholder:"Search settings","aria-label":"Search settings",className:"typography-ui-label min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-subtle-foreground"}),m.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(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})}):null]}),Ch=({onClose:t,forceMobile:s,isWindowed:n,visiblePageSlugs:a,initialMobileStage:r="nav",onActiveConnectionDeleted:o})=>{const c=lt(),i=s??c.isMobile,d=uc(),h=yh(d?.instanceLabel),p=W(Z=>Z.settingsPage),m=W(Z=>Z.isSettingsDialogOpen),u=W(Z=>Z.setSettingsPage),f=yc(p),[v,g]=l.useState(r),b=l.useRef(r==="nav"?f:null);l.useEffect(()=>{!i&&f==="home"&&u("general")},[i,u,f]);const w=l.useRef(null),[k,N]=l.useState(0);l.useEffect(()=>yn(()=>{N(Z=>Z+1)}),[]);const A=l.useMemo(()=>Fe(),[]),j=l.useMemo(()=>Fe()&&ss(),[k]),x=l.useMemo(()=>Fe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="darwin",[]),P=l.useMemo(()=>Fe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="win32",[]),C=l.useMemo(()=>Fe()&&typeof window<"u"&&window.__PICHAMBER_PLATFORM__==="linux",[]),y=l.useMemo(()=>Nl(),[]),L=l.useMemo(()=>Me(),[]),I=l.useMemo(()=>gh(A,i,L),[A,i,L]),T=l.useMemo(()=>{const Z=a?new Set(a):null;return jc.filter(fe=>fe.slug!=="home").filter(fe=>!Z||Z.has(fe.slug)).filter(fe=>Co(fe,I)).filter(fe=>!(i&&(fe.slug==="remote-access"||fe.slug==="remote-instances"||fe.slug==="servers"&&!L)))},[L,i,I,a]),E=l.useMemo(()=>{const Z=new Map(fh.map((fe,We)=>[fe,We]));return T.slice().sort((fe,We)=>(Z.get(fe.slug)??999)-(Z.get(We.slug)??999))},[T]),U=dn(Z=>Z.activeProjectId);l.useEffect(()=>{!m&&!n||f==="skills.installed"&&Vt.getState().loadSkills()},[U,m,n,f]);const _=l.useCallback(Z=>{if(u(Z),b.current=Z,!i)return;const fe=Is(Z);if(!fe||fe.slug==="home"){g("nav");return}g(fe.kind==="split"?"page-sidebar":"page-content")},[i,u]),O=l.useMemo(()=>Is(f),[f]),V=l.useMemo(()=>({general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",tunnel:"tunnel"}),[]),H=l.useCallback(Z=>{switch(Z){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:j,isMac:x,isWindows:P,isLinux:C,isWindowsArm64:y}),[j,C,x,P,y,I]),{settingsSearchQuery:X,setSettingsSearchQuery:we,isMobileSettingsSearchOpen:ie,setIsMobileSettingsSearchOpen:ke,mobileSettingsSearchInputRef:oe,activeSearchResultIndex:ae,setActiveSearchResultIndex:me,searchResultRefs:le,keyboardSearchNavigationRef:Q,settingsSearchResults:G,groupedSettingsSearchResults:Pe,openSearchResult:re,handleSettingsSearchKeyDown:xe}=kh({runtimeCtx:ne,visiblePageSlugs:a,getPageTitle:H,openPage:_,isMobile:i,setMobileStage:g,containerRef:w,settingsSlug:f});l.useEffect(()=>{if(!i||v!=="nav"||f==="home"||b.current===f)return;const Z=Is(f);!Z||Z.slug==="home"||(b.current=f,g(Z.kind==="split"?"page-sidebar":"page-content"))},[i,v,f]);const ve=i&&v!=="nav",Ne=v==="page-content"&&O?.kind==="split",K=ve?"Back to settings":"Close settings",ce=Cl(),z=l.useCallback(()=>{g("page-content")},[]),J=l.useCallback(()=>{g("nav")},[]),te=l.useCallback(()=>{g("page-sidebar")},[]);l.useEffect(()=>{(!i||v!=="nav")&&ke(!1)},[i,v,ke]);const et=l.useCallback((Z,fe)=>null,[]),$=()=>e.jsx(bh,{isMobile:i,isMobileSettingsSearchOpen:ie,settingsSearchQuery:X,setSettingsSearchQuery:we,handleSettingsSearchKeyDown:xe,settingsSearchResults:G,groupedSettingsSearchResults:Pe,activeSearchResultIndex:ae,setActiveSearchResultIndex:me,searchResultRefs:le,keyboardSearchNavigationRef:Q,openSearchResult:re,sortedFilteredPages:E,settingsSlug:f,mobileStage:v,openPage:_,getPageTitle:H,activeRemoteLabel:h,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(At,{children:$()})})});if(!O)return e.jsx("div",{className:"flex-1 bg-background"});if(v==="page-sidebar"){if(O.kind!=="split"){const Z=e.jsx(nn,{slug:f,isMobile:i,runtimeCtx:I,openChamberSectionBySlug:V,onActiveConnectionDeleted:o});return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(At,{children:Z})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(At,{children:et(f,{onItemSelect:z})})})}return e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(At,{children:e.jsx(nn,{slug:f,isMobile:i,runtimeCtx:I,openChamberSectionBySlug:V,onActiveConnectionDeleted:o})})})},de=()=>!O||f==="home"?null:O.kind==="split"?e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[e.jsx("div",{className:F("border-r","bg-sidebar"),style:{width:$r,minWidth:$r,borderColor:"var(--interactive-border)"},children:e.jsx(At,{children:et(f,{})})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(At,{children:e.jsx(nn,{slug:f,isMobile:i,runtimeCtx:I,openChamberSectionBySlug:V,onActiveConnectionDeleted:o})})})]}):e.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:e.jsx(At,{children:e.jsx(nn,{slug:f,isMobile:i,runtimeCtx:I,openChamberSectionBySlug:V,onActiveConnectionDeleted:o})})});return e.jsxs("div",{ref:w,"data-settings-view":"true",className:F("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),children:[i?e.jsx(Nh,{mobileStage:v,activePageMeta:O,getPageTitle:H,showBackButton:ve,mobileBackButtonLabel:K,onBack:J,showOpenPageSidebarButton:!!Ne,onOpenPageSidebar:te,isMobileSettingsSearchOpen:ie,setIsMobileSettingsSearchOpen:ke,mobileSettingsSearchInputRef:oe,settingsSearchQuery:X,setSettingsSearchQuery:we,handleSettingsSearchKeyDown:xe,onClose:t,shortcutKey:ce}):e.jsx(e.Fragment,{children:ve&&e.jsx("div",{className:F("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(R,{name:"arrow-left-s",className:"h-5 w-5"})})})}),e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:i?Y():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("relative flex h-full min-h-0 flex-col overflow-hidden border-r","bg-sidebar"),style:{width:`${Br}px`,minWidth:`${Br}px`,borderColor:"var(--interactive-border)"},children:e.jsx(At,{children:$()})}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:de()})]})})]})},zh=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:Ch},Symbol.toStringTag,{value:"Module"}));export{Ki as A,dd as M,Ch as S,ud as a,cd as b,Xt as c,Yn as d,hp as e,Yc as f,Jc as g,zh as h,rd as i,ld as m,Oi as p,Li as r,id as s,Di as u};
|