@pi-chamber/web 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/assets/{CommitSection-DLIvjYbM.js → CommitSection-BAYzLtBf.js} +1 -1
  2. package/dist/assets/{DiagramEditor-Tw3ZWHML.js → DiagramEditor-D1yc4joK.js} +1 -1
  3. package/dist/assets/{DiagramView-CK6R7taL.js → DiagramView-CAlJiG11.js} +1 -1
  4. package/dist/assets/{DiffView-vrxi5oWp.js → DiffView-DGD9DMS7.js} +1 -1
  5. package/dist/assets/{FilesView-BD_h3EVr.js → FilesView-DB5VI7EN.js} +1 -1
  6. package/dist/assets/{GitView-BwNKqK0K.js → GitView-CFlPcSn9.js} +3 -3
  7. package/dist/assets/{JsonTreeView-CmY7QgEX.js → JsonTreeView-CoX1ZscV.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-CpI-25Xk.js → MarkdownRendererImpl-V1HMFCjr.js} +1 -1
  9. package/dist/assets/{PatchDiff-CrIWbYj7.js → PatchDiff-D6Gs7K5B.js} +1 -1
  10. package/dist/assets/{PierreDiffViewer-B410mdbq.js → PierreDiffViewer-COYd5Qr-.js} +1 -1
  11. package/dist/assets/{SessionSwitcherDropdown-DROjbyIu.js → SessionSwitcherDropdown-o1RjhCfF.js} +8 -8
  12. package/dist/assets/{SettingsView-CsJItYZh.js → SettingsView-BYqvfMTS.js} +3 -3
  13. package/dist/assets/{SettingsWindow-C9s4AX72.js → SettingsWindow-CtNS0tQn.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-b_R4tAZu.js → ToolOutputDialog-2zKUdGYL.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-CfnliaE9.js → ToolPartDiffPreview-CBFC9min.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-CQz2fSZI.js → VirtualizedFileDiff-UMgLcO4Q.js} +1 -1
  17. package/dist/assets/{collapsible-CR4U9tjw.js → collapsible-Kx4bmsQM.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-C7vXPUYT.js → computeVirtualFileMetrics-DdOCbMyK.js} +1 -1
  19. package/dist/assets/{contextFileOpenGuard-DtTHRnq1.js → contextFileOpenGuard-BRldMp0d.js} +1 -1
  20. package/dist/assets/{index-DZG82DE1.js → index-CuSNEV7s.js} +1 -1
  21. package/dist/assets/{isDiffPlainText-zTq-4A04.js → isDiffPlainText-CGIf0q8p.js} +1 -1
  22. package/dist/assets/{isFilePlainText-CLgIdzE5.js → isFilePlainText-D4hgTRxT.js} +1 -1
  23. package/dist/assets/{main-BVWtJYSk.js → main-By_pvk90.js} +2 -2
  24. package/dist/assets/{main-DXYHsqzA.js → main-CmkRaMOR.js} +4 -4
  25. package/dist/assets/{markdownCore-CN0pApQE.js → markdownCore-CAVCyFnI.js} +1 -1
  26. package/dist/assets/{miniChat-BrbRq5NQ.js → miniChat-_XK2gGZE.js} +2 -2
  27. package/dist/assets/{mobile-DTPtCn5N.js → mobile-B4E4JqAf.js} +2 -2
  28. package/dist/assets/{renderElectronMiniChatApp-CM8qBaye.js → renderElectronMiniChatApp-Ca4hZgIz.js} +1 -1
  29. package/dist/assets/{renderMobileApp-KS_pt-qc.js → renderMobileApp-ClA5Cnmw.js} +4 -4
  30. package/dist/assets/{useInlineCommentController-CwNNjgc7.js → useInlineCommentController-DD31jQNC.js} +1 -1
  31. package/dist/assets/{usePanelSlide-DkorgQJ5.js → usePanelSlide-a4c67FIY.js} +2 -2
  32. package/dist/assets/{useWindowTitle-B9wt_3ZQ.js → useWindowTitle-DoHrUC5r.js} +1 -1
  33. package/dist/assets/{vendor-codemirror-language-data-x89A7Wy0.js → vendor-codemirror-language-data-Dp_Z-0GD.js} +2 -2
  34. package/dist/assets/{web-components-BEPfE4kU.js → web-components-Cct1r-wn.js} +1 -1
  35. package/dist/index.html +1 -1
  36. package/dist/mini-chat.html +1 -1
  37. package/dist/mobile.html +1 -1
  38. package/package.json +1 -1
  39. package/server/lib/pi/session-daemon/session-daemon.js +1 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DZG82DE1.js","assets/SessionSwitcherDropdown-DROjbyIu.js","assets/index-BAqpUCjs.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-riABQmQ_.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-CkHYYg0E.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-x89A7Wy0.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-CW8w438f.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/computeVirtualFileMetrics-C7vXPUYT.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-CLgIdzE5.js","assets/isDiffPlainText-zTq-4A04.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
- import{_ as $s}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ye,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{bd as _s,be as yc,ao as vc,o as qi,D as is,w as as,y as hs,I as k,ay as Cs,bf as Bo,f as B,B as Qe,av as cn,T as et,q as tt,s as st,bg as Ji,bh as wc,bi as Sc,bj as jc,bk as Cc,h as Le,bl as kc,bm as _o,bn as Nc,bo as Ac,bp as zo,bq as Ic,br as Dc,bs as Pc,bt as Ec,bu as Ar,bv as Tc,t as ae,as as Yt,at as Vt,au as Qt,Y as Hs,bw as Rc,bx as Mc,by as Fc,bz as Lc,bA as $o,a5 as Bt,bB as Oc,bC as Bc,bD as _c,bE as zc,bF as $c,bG as Uc,bH as Ir,bI as Xi,bJ as Zi,bK as Gc,bL as Kc,bM as Hc,bN as Wc,bO as Yc,bP as Vc,aY as Dr,r as Us,bQ as As,bR as Qc,a_ as Is,b3 as qc,b4 as Jc,b5 as Xc,b6 as Zc,b7 as ir,b8 as Js,bS as Uo,az as St,b as zt,aQ as Ps,bT as ea,x as bs,z as Es,A as Ts,bU as ed,bV as Xs,bW as ar,bX as Go,bY as Ko,bZ as nn,aC as td,aS as ta,aH as Ho,aF as sd,aE as nd,aW as sa,g as eo,b_ as rd,b$ as na,c0 as od,c1 as ra,e as to,c2 as id,C as Wn,K as oa,c3 as ad,c4 as Gt,aM as ia,c as Pr,c5 as ld,c6 as cd,c7 as Yn,c8 as Rn,c9 as aa,_ as dn,$ as un,Z as dd,ca as ud,cb as Wo,aZ as la,cc as fd,cd as ca,b1 as so,b2 as rn,ce as Yo,cf as Vn,aw as hd,cg as da,H as pd,ch as no,ci as md,cj as gd,j as ua,l as xd,ck as bd,cl as yd,k as vd,cm as Er,n as wd,S as Sd,cn as fa,co as jd,cp as Cd,m as kd,d as Nd,cq as Ad,a as Id,ax as Dd,b0 as Pd,cr as Ed,a$ as Td,cs as Rd,ct as Md,cu as Fd,cv as Ld,af as Od,cw as Vo,cx as Bd,aN as _d,cy as zd,cz as $d,cA as wn,cB as Qo,cC as Ud,cD as qo,cE as Jo,cF as Gd,aL as ha,a3 as Kd,E as Hd,cG as pa,u as Wd,cH as Yd,cI as Vd,aA as Ws,p as Qd,cJ as qd,cK as ma,cL as Jd,cM as Xd,cN as Zd,cO as eu,cP as tu,cQ as su,cR as Xo,cS as nu,cT as ga,cU as ru,cV as ou}from"./SessionSwitcherDropdown-DROjbyIu.js";import{L as Zo,M as iu,N as ei,O as au,i as lu,P as cu,K as du,r as Jt,Q as fn,b as uu,J as fs,u as ce,R as fu,S as cs,T as ro,q as oo,m as Ds,U as bt,V as io,W as ao,X as hu,Y as pu,D as mu,Z as gu,_ as xu,$ as bu,a0 as yu,a1 as ss,a2 as Tr,a as Qn,a3 as vu,a4 as wu,a5 as Su,a6 as ju,a7 as xa,I as ba,E as on,a8 as Rr,e as Mr,d as Sn,a9 as Cu,aa as ku,ab as Zs,ac as lr,ad as ya,C as Nu,o as Au,ae as Fr,af as ks,ag as ti,ah as Lr,ai as va,aj as Or,ak as Iu,al as Du,am as Pu,w as Eu,an as Tu}from"./index-BAqpUCjs.js";import{C as wa,a as Sa,M as Br,b as _r,c as zr,d as ja,S as Ca,D as Ru,e as Mu,f as Fu,g as Lu,h as Ou,i as Bu,j as _u,k as zu,l as $u}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as ka,p as lo,u as $r,a as Uu}from"./vendor-zustand-CnsBKjP5.js";import{u as Gu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as qn,d as hn,P as co,D as Jn,e as Xn,f as Na,b as Ku,a as Hu,T as Wu,M as Yu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as uo,v as Aa,u as Zn,a as Vu,h as Qu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as er}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as qu}from"./permissionStore-BRcQ9Jgt.js";const Ju=3;let zn=0;const Ia=[],Xu=()=>zn<Ju?(zn+=1,Promise.resolve()):new Promise(e=>{Ia.push(e)}),Zu=()=>{const e=Ia.shift();if(e){e();return}zn=Math.max(0,zn-1)},ef=async e=>{await Xu();try{return await e()}finally{Zu()}},tf="chat";function Da(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(_s.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(_s.SETTINGS,n),s}return e.tab!==tf&&s.set(_s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(_s.FILE,e.diffFile),s}function sf(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=e.toString();return i?`${r}?${i}`:r}function nf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Da(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(_s.SESSION)&&s.set(_s.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Ur(e,s={}){if(!(typeof window>"u")&&!(!s.force&&nf(e)))try{const n=Da(e),r=sf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const rf=["typescript","javascript","tsx","jsx","json","markdown"],Pa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let si=null;const Ea=()=>(si??=Promise.all([$s(()=>import("./index-DZG82DE1.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),$s(()=>import("./workerFactory-tw7cIdmV.js"),[]),$s(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,8,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),si),pn={},ni=new Set,Gr=new Set;let Mn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of Gr)e()},Ta=(e,s)=>{s.setRenderOptions({theme:Mn,lineDiffType:Pa[e].lineDiffType})},Kr=e=>{typeof window>"u"||ni.has(e)||(ni.add(e),Ea().then(s=>{if(pn[e])return;const n=Pa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:rf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,Ta(e,r),of()}))},af=e=>(Gr.add(e),()=>Gr.delete(e)),lf=e=>{if(!(Mn.light===e.light&&Mn.dark===e.dark)){Mn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&Ta(s,n)}}},tx=({children:e})=>{const s=yc(),n=Zo(!1),r=Zo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ye.useEffect(()=>{let d=!1;return Ea().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ye.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Kr("unified"),Kr("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},sx=(e="unified")=>{const s=Ye.useSyncExternalStore(af,()=>pn[e],()=>{});return Ye.useEffect(()=>{Kr(e)},[e]),s};function cf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=vc();return e}catch{return"unknown"}}function df(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function uf(){const e=uu();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function ff(e){const s=new URLSearchParams;return s.set("deviceClass",cf()),s.set("arch",df()),s.set("platform",uf()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",fn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function cr(e,s){try{const n=ff(e);s&&n.set("currentVersion",s);const r=await Jt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function hf(){return lu()?"mobile":cu()?"desktop":du()?"web":null}const ri={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Fn=ps()((e,s)=>({...ri,checkForUpdates:async()=>{const n=hf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.3.2",[l,c]=await Promise.allSettled([ei(),cr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await cr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await cr("mobile","0.3.2"),i=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const i=await ei();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await au(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await iu())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ri)}})),oi="https://github.com/RyderAsKing/PiChamber/releases";function pf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function mf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ii(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function gf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function xf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ai=2e3,bf=600*1e3;async function yf(){try{const e=await Jt("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function vf(){try{return(await Jt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function wf(e,s=Math.ceil(bf/ai),n=ai){for(let r=0;r<s;r++){try{const i=await Jt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await vf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ra=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,b]=Ye.useState(!1),[y,x]=Ye.useState("idle"),[h,m]=Ye.useState(null),j=n?.version?n.releaseUrl||`${oi}/tag/v${n.version}`:oi,C=n?.downloadUrl||j,N=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",g=u==="mobile",p=n?.updateCommand||"pichamber update";Ye.useEffect(()=>{e||(x("idle"),m(null))},[e]);const A=async()=>{(await cn(p)).ok&&(b(!0),setTimeout(()=>b(!1),2e3))},D=Ye.useCallback(async H=>{await qi(H)},[]),I=Ye.useCallback(async()=>{x("updating"),m(null);const H=await yf();if(!H.success){x("error"),m(H.error||"Update failed");return}H.autoRestart&&(x("restarting"),await new Promise(te=>setTimeout(te,2e3))),x("reconnecting"),await wf(n?.currentVersion)?window.location.reload():(x("error"),m("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),E=Ye.useCallback(()=>{D(C)},[D,C]),M=y!=="idle"&&y!=="error",P=Ye.useMemo(()=>{if(!n?.body)return null;const H=n.body.trim();if(!H)return null;const ee=xf(H);return ee.length===0?{kind:"raw",title:"What's new",content:ii(H)}:{kind:"sections",title:"What's new",sections:[...ee].sort((se,_)=>gf(se.version,_.version)).map(se=>({version:se.version,dateLabel:pf(se.date),content:ii(mf(se.raw)||H)}))}},[n?.body]);return t.jsx(is,{open:e,onOpenChange:M?void 0:s,children:t.jsxs(as,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(hs,{className:"flex items-center gap-2.5",children:[t.jsx(k,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:y==="restarting"||y==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&M&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(k,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[y==="updating"&&"Installing update...",y==="restarting"&&"Server restarting...",y==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),P&&!M&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Cs,{className:"max-h-[400px] p-0",fillContainer:!1,children:P.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:H=>{const te=H.target.closest("a");te&&te.href&&(H.preventDefault(),H.stopPropagation(),D(te.href))},children:t.jsx(Bo,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(H=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",H.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:H.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:ee=>{const se=ee.target.closest("a");se&&se.href&&(ee.preventDefault(),ee.stopPropagation(),D(se.href))},children:t.jsx(Bo,{content:H.content,disableLinkSafety:!0,enableFileReferences:!1})})]},H.version))})})}),v&&y==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:p}),t.jsx("button",{onClick:A,className:B("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(k,{name:"check",className:"h-4 w-4"}):t.jsx(k,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!g&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[N,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${N}%`}})})]}),(l||h)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||h})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!g&&!i&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!g&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!g&&i&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),g&&t.jsxs(Qe,{onClick:E,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!M&&t.jsxs("button",{onClick:I,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&M&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Sf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:B("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:B("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),mn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(et,{open:r,onOpenChange:i,children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:B("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(k,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(st,{sideOffset:8,className:B("max-w-sm",n),children:e})]})},nx="w-full min-w-40 max-w-48",jf="settings",Cf="w-full min-w-40 max-w-48",rx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",kf="w-full max-w-[24rem]",ox="min-w-0 flex-1",ix="flex w-full min-w-0 items-center gap-2",ax="typography-meta shrink-0 text-muted-foreground tabular-nums",Ma="space-y-3.5",Nf="space-y-1.5",lx="typography-settings-page-title text-muted-foreground",Af="typography-settings-section-title text-foreground",cx="typography-settings-section-title text-foreground",Fa="typography-settings-group-title text-foreground",fo="typography-settings-field-label text-foreground",If="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",dx="typography-meta font-medium text-foreground",ux="typography-settings-section-title text-foreground",Df=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:B("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Af,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:If,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:B(d),children:a})]})},fx=({children:e,className:s})=>t.jsx("div",{className:B("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Pf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:B(Fa,s),children:e}),hx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:B("space-y-2",i),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Pf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:B(a),children:r})]}),zs=({label:e,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:gn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:B("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:B("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},px=({label:e,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":i,className:B("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:B(gn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:B("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),mx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:B("pt-4",s),children:e}),Ef=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{i||s(!e)},b=r!=null;return t.jsxs("div",{"data-settings-item":l,className:B("group flex cursor-pointer gap-2 py-0.5",b?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:f,onKeyDown:y=>{(y.key===" "||y.key==="Enter")&&(y.preventDefault(),f())},children:[t.jsx(Ji,{checked:e,onChange:s,disabled:i,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:fo,children:n}),d,u!=null?t.jsx(mn,{children:u}):null]}),b?t.jsx("span",{className:gn,children:r}):null]})]})},gx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:B("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Sf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:B("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),xx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:B(Nf,n),children:s});function bx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:B("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Qe,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Tf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(wc,{className:"w-full max-w-md",children:[t.jsx(Sc,{className:"text-center",children:t.jsxs(jc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(k,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Cc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Qe,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(k,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Rf(e){return t.jsx(Tf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const yx=({active:e=!0,readOnly:s=!1})=>{const n=Le(r=>r.currentSessionId);return t.jsx(Rf,{sessionId:n||void 0,children:t.jsx(kc,{active:e,readOnly:s},n??"no-session")})};function Mf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ho=Ye.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:b,...y},x)=>{const h=Ye.useRef(null),m=Ye.useRef(null),[j,C]=Ye.useState(null),N=c??j,v=Ye.useCallback(p=>{const A=h.current;if(!A)return;m.current={startY:p.clientY,startHeight:A.getBoundingClientRect().height};const D=p.currentTarget;D.setPointerCapture(p.pointerId);const I=M=>{const P=m.current;if(!P)return;const H=P.startHeight+(M.clientY-P.startY),ee=Math.max(82,H);d?d(ee):C(ee)},E=()=>{m.current=null,D.removeEventListener("pointermove",I),D.removeEventListener("pointerup",E),D.removeEventListener("pointercancel",E)};D.addEventListener("pointermove",I),D.addEventListener("pointerup",E),D.addEventListener("pointercancel",E),p.preventDefault()},[d]),g=Ye.useCallback(p=>{if(p.target.closest('textarea, button, [role="separator"]'))return;const D=h.current?.querySelector("textarea");D&&document.activeElement!==D&&(p.preventDefault(),D.focus())},[]);return f?t.jsx(Cs,{as:"textarea",ref:x,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:B("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}):t.jsx("div",{ref:h,onPointerDown:g,style:N!==null?{height:`${N}px`}:void 0,className:B("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:x,className:B("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[b,t.jsx(Mf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ho.displayName="Textarea";const li=(e,s)=>s.updatedAtMs-e.updatedAtMs,$n=ps((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([Dc(),zo()]),i={};for(const a of r.sort(li))i[a.id]=a;s().listenerReady||await Pc(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){e({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){e({isImportsLoading:!0,error:null});try{const n=await Ic();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await zo(),r={};for(const i of n.sort(li))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Ac({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Ec(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await _o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),e(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await Nc(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{e({error:null});try{await _o(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>e({error:null})})),La=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],an=Object.fromEntries(La.map(e=>[e.key,e.Icon])),Hr="pichamber:project-actions-updated",Oa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ds=(e,s)=>`${Oa(e)}::${s}`,Ff=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ci=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Lf=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ci(s.localPort),r=ci(s.remotePort);if(!n||!r)return null;const i=Ff(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},Ba=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Lf(n,r);i&&s.push(i)}return s},Of=(e,s)=>{const n=(e||"").trim();return n&&Ba(s).find(a=>a.id===n)?.url||null},Bf=kf,_a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Df,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Wr=e=>e.name.trim().length>0&&e.command.trim().length>0,_f=e=>e.name.trim().length===0&&e.command.trim().length===0,zf=e=>!Wr(e)&&!_f(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!Wr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Wr)},Uf=450,Gf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kf=()=>({id:Gf(),name:"",command:"",icon:"play"}),Hf=({projectRef:e})=>{const s=o.useMemo(()=>fs(),[]),n=$n(p=>p.instances),r=$n(p=>p.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[f,b]=o.useState(new Set),y=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let p=!1;return c(!0),(async()=>{try{const A=await Ar(e);if(p)return;a(A.actions),u(JSON.stringify({actions:A.actions})),b(new Set(A.actions.map(D=>D.id)))}catch{if(p)return;a([]),u(JSON.stringify({actions:[]})),b(new Set)}finally{p||c(!1)}})(),()=>{p=!0}},[e]);const x=o.useMemo(()=>s?Ba(n):[],[n,s]),h=o.useMemo(()=>$f(i,f),[i,f]),m=o.useMemo(()=>JSON.stringify({actions:h.actions}),[h.actions]),j=d!==null&&h.canPersist&&m!==d,C=o.useCallback(async p=>await Tc(e,{actions:p,primaryActionId:null})?(u(JSON.stringify({actions:p})),b(new Set(p.map(D=>D.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Hr,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!j||l||y.current)return;const p=window.setTimeout(()=>{y.current||(y.current=!0,(async()=>{try{await C(h.actions)}finally{y.current=!1}})())},Uf);return()=>{window.clearTimeout(p)}},[j,l,C,h.actions]);const N=o.useCallback(()=>{const p=Kf();a(A=>[...A,p])},[]),v=o.useCallback(p=>{a(A=>A.filter(D=>D.id!==p))},[]),g=o.useCallback((p,A)=>{a(D=>D.map(I=>I.id===p?A(I):I))},[]);return t.jsx(_a,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Qe,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:N,children:[t.jsx(k,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:B("space-y-6",Bf),children:i.map((p,A)=>{const D=p.icon||"play",I=an[D]||"play",E=p.name.trim()||`Action ${A+1}`,M=zf(p);return t.jsxs("div",{className:Ma,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Fa,children:E}),t.jsx(Qe,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>v(p.id),"aria-label":`Delete ${E}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(zs,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(k,{name:I,className:"h-4 w-4"})})}),t.jsx(Qt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:La.map(P=>{const H=P.Icon,ee=(p.icon||"play")===P.key;return t.jsx("button",{type:"button",onClick:()=>g(p.id,te=>({...te,icon:P.key})),className:B("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",ee&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${P.label}`,children:t.jsx(k,{name:H,className:"h-4 w-4"})},P.key)})})})]}),t.jsx(Hs,{value:p.name,onChange:P=>g(p.id,H=>({...H,name:P.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(zs,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ho,{value:p.command,onChange:P=>g(p.id,H=>({...H,command:P.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),M?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Ef,{checked:p.autoOpenUrl===!0,onChange:P=>g(p.id,H=>({...H,...P?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${E}`}),p.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(zs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Hs,{value:p.openUrl||"",onChange:P=>g(p.id,H=>({...H,openUrl:P.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(zs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:x.length>0?t.jsxs(Rc,{value:p.desktopOpenSshForward&&x.some(P=>P.id===p.desktopOpenSshForward)?p.desktopOpenSshForward:"__none__",onValueChange:P=>{g(p.id,H=>({...H,...P==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:P}}))},children:[t.jsx(Mc,{size:jf,className:"w-full",children:t.jsx(Fc,{placeholder:"Use output/manual URL"})}),t.jsxs(Lc,{children:[t.jsx($o,{value:"__none__",children:"Use output/manual URL"}),x.map(P=>t.jsx($o,{value:P.id,children:P.label},P.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},p.id)})})})},Wf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=Bt(M=>M.providers),d=Bt(M=>M.modelsMetadata),u=ce(M=>M.hiddenModels),f=ce(M=>M.providerOrder),b=ce(M=>M.setProviderOrder),y=ce(M=>M.isFavoriteModel),x=ce(M=>M.toggleFavoriteModel),h=ce(M=>M.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:j}=Oc(),[C,N]=o.useState(!1),[v,g]=o.useState("");o.useEffect(()=>{C||g("")},[C]);const p=e?c.find(M=>M.id===e.providerId):void 0,A=e&&p?(Array.isArray(p.models)?p.models:[]).find(M=>M.id===e.modelId):void 0,D=e?Bc(A,e.modelId):s,I=o.useMemo(()=>e?u.filter(M=>!(M.providerID===e.providerId&&M.modelID===e.modelId)):u,[u,e]),E=o.useCallback(M=>{l({providerId:M.providerID,modelId:M.modelID}),N(!1)},[l]);return t.jsxs(Yt,{modal:!1,open:C,onOpenChange:M=>{r||N(M)},children:[t.jsx(Vt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:B(zc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(_c,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:B("truncate",e?"text-foreground":"text-muted-foreground"),children:D})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx($c,{providers:c,favoriteModels:m,recentModels:j,modelsMetadata:d,searchQuery:v,onSearchQueryChange:g,onSelect:E,labels:{...Wf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:I,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),N(!1)},disabled:r,autoFocus:!0,onEscape:()=>N(!1),isFavorite:M=>y(M.providerID,M.modelID),onToggleFavorite:M=>x(M.providerID,M.modelID),onReorderFavorite:(M,P)=>h(M.providerID,M.modelID,P.providerID,P.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:f,onReorderProvider:b,reorderProviderTitle:"Drag to reorder provider"})})]})},dr="w-full max-w-none",Vf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=Bt(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(_a,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ma,children:[t.jsx(zs,{label:"Name",settingsItem:"projects.name",controlClassName:dr,children:t.jsx(Hs,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(zs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:dr,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:dr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},Qf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Uc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,f)=>{i(u&&f?`${u}/${f}`:void 0)},[]),d=o.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},qf=450,Jf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},qf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Xf=({project:e,onIdentitySave:s})=>{const n=Qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Jf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Vf,{form:n}),t.jsx(Hf,{projectRef:r})]})};function Zf({...e}){return t.jsx(wa,{...e})}function eh({...e}){return t.jsx(Sa,{...e})}function th({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(Br,{children:t.jsx(_r,{className:B("app-region-no-drag z-50",s),children:t.jsx(zr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:B(Ir,e),...i,children:n})})})}function di({className:e,...s}){return t.jsx(ja,{className:B(Xi,e),...s})}function sh({className:e,...s}){return t.jsx(Ca,{className:B(Zi,e),...s})}const js=ps()(ka(lo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=await Vc();return e({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Yc();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:r})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Wc();return e({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=oo()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await Jt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await ro({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return cs("saving"),await Hc(r),cs("saved"),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return cs("saving"),await Kc(n,a),cs("saved"),await s().loadProfiles(),!0}catch(i){return cs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return cs("saving"),await Gc(n),cs("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:fu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=js);const nh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],rh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function oh(e){const s=e.trim().toLowerCase();return nh.find(n=>n.slug===s)??null}function ih(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=rh[s];if(n)return n;const r=oh(s);return r?r.slug:"home"}function vx(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const jn=100;function wx(){const e=ce(I=>I.isArchivePageOpen),s=ce(I=>I.setArchivePageOpen),n=ce(I=>I.setActiveMainTab),r=Le(I=>I.setCurrentSession),i=Le(I=>I.unarchiveSession),a=Ds(I=>I.homeDirectory),l=Dr({archived:!0}),[c,d]=o.useState(""),[u,f]=o.useState(null),[b,y]=o.useState(jn),x=c.trim().toLowerCase(),h=o.useMemo(()=>e?[...l].sort((I,E)=>(E.time?.archived??0)-(I.time?.archived??0)):[],[l,e]),m=o.useMemo(()=>{const I=new Map;for(const E of h){const M=bt(Us(E))??"",P=I.get(M);if(P){P.sessions.push(E);continue}I.set(M,{directory:M,label:M?As(M,a)||M:"other projects",sessions:[E]})}return[...I.values()].sort((E,M)=>M.sessions.length-E.sessions.length)},[a,h]),j=o.useMemo(()=>x?h.filter(I=>(I.title??"").toLowerCase().includes(x)):u===null?h:m.find(I=>I.directory===u)?.sessions??[],[m,x,u,h]),C=j.slice(0,b),N=j.length-C.length,v=l.length,g=o.useCallback(I=>{f(I),y(jn)},[]),p=o.useCallback(I=>{const E=bt(Us(I));r(I.id,E??void 0),n("chat"),s(!1)},[n,r,s]),A=o.useCallback(I=>{i(I.id).then(E=>{E?ae.success("Session restored"):ae.error("Failed to restore session")})},[i]);if(!e)return null;const D=(I,E,M,P,H,ee,te)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:H,title:ee,className:B("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",te?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:E}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),te?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Is.requestDelete({sessions:te,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${E}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},I);return t.jsx(Ru,{open:e,onOpenChange:s,children:t.jsxs(Mu,{children:[t.jsx(Fu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Lu,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Ou,{className:"sr-only",children:"Archived sessions"}),t.jsx(Bu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(_u,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(k,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[D("__all__","All directories",v,u===null,()=>g(null)),m.map(I=>D(I.directory||"__none__",I.label,I.sessions.length,u===I.directory,()=>g(I.directory),I.directory||void 0,I.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:I=>{d(I.target.value),y(jn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:j.length===1?`${j.length} archived session`:`${j.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[C.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:x?"No matching archived sessions":"No archived sessions"})}):C.map(I=>{const E=bt(Us(I))??"",M=E?As(E,a)||E:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>p(I),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),p(I))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:I.title||"Untitled Session"}),x&&M?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:E,children:M}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Qc(I.time?.archived??I.time?.updated??I.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),A(I)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${I.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),Is.requestDelete({sessions:[I],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${I.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},I.id)}),N>0?t.jsx("button",{type:"button",onClick:()=>y(I=>I+jn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const ah=()=>{const[e,s]=Ye.useState(!1),[n,r]=Ye.useState(!1);Ye.useEffect(()=>{s(fs()),r(io())},[]);const i=Ye.useCallback(async c=>e?await ao(c):{success:!0,path:c},[e]),a=Ye.useCallback(async c=>e?await hu():{success:!0},[e]),l=Ye.useCallback(async c=>e?await pu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},lh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ch=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[f,b]=o.useState(""),[y,x]=o.useState(!1),[h,m]=o.useState(!1),[j,C]=o.useState(""),[N,v]=o.useState(!1),g=o.useRef(null),p=o.useCallback(_=>{_.stopPropagation()},[]),A=l.length>1,D=o.useMemo(()=>lh(j),[j]),I=o.useMemo(()=>{const _=f.toLowerCase();return _?s.filter(K=>K.toLowerCase().includes(_)):s},[f,s]),E=o.useMemo(()=>{const _=f.toLowerCase();return _?n.filter(K=>K.toLowerCase().includes(_)):n},[f,n]),M=_=>{if(_===e){u(!1);return}i(_),u(!1),b("")},P=()=>{x(!0),setTimeout(()=>g.current?.focus(),50)},H=async()=>{if(!(!D||N)){if(A){m(!0);return}v(!0);try{await a(D,l[0]),C(""),x(!1),u(!1)}finally{v(!1)}}},ee=async _=>{if(!(!D||N)){v(!0);try{await a(D,_),C(""),x(!1),m(!1),u(!1)}finally{v(!1)}}},te=()=>{m(!1)},se=()=>{C(""),x(!1),m(!1)};return o.useEffect(()=>{d||(b(""),x(!1),m(!1),C(""))},[d]),t.jsxs(Yt,{open:d,onOpenChange:u,children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Current branch"})]}),t.jsx(Qt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(qc,{className:"h-full min-h-0",children:[t.jsx(Jc,{placeholder:"Search branches...",value:f,onValueChange:b,onKeyDown:p}),t.jsxs(Xc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Zc,{children:"No branches found."}),t.jsx(ir,{children:h?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:te,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:D})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(_=>t.jsxs("button",{type:"button",onClick:()=>ee(_),disabled:N,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[N?t.jsx(k,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,_.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:_.pushUrl})]},_.name))})]}):y?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:g,placeholder:"New branch name",value:j,onChange:_=>C(_.target.value),onClick:_=>_.stopPropagation(),onKeyDown:_=>{p(_),_.key==="Enter"?(_.preventDefault(),H()):_.key==="Escape"&&(_.preventDefault(),se())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:H,disabled:!D||N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:N?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:se,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(Js,{onSelect:P,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Uo,{}),t.jsxs(ir,{heading:"Local branches",children:[I.map(_=>t.jsxs(Js,{onSelect:()=>M(_),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:_}),(r?.[_]?.ahead||r?.[_]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[_].ahead||0," ahead ·"," ",r[_].behind||0," behind"]})]}),e===_&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${_}`)),I.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Uo,{}),t.jsxs(ir,{heading:"Remote branches",children:[E.map(_=>t.jsx(Js,{onSelect:()=>M(_),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:_})},`remote-${_}`)),E.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},dh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),uh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),f=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},b=async()=>{if(!e||!s||!a.trim())return;const h=dh(a);if(h===e){i(!1);return}d(!0);try{await s(e,h),i(!1),l("")}finally{d(!1)}},y=()=>{i(!1),l("")},x=h=>{h.key==="Enter"?(h.preventDefault(),b()):h.key==="Escape"&&(h.preventDefault(),y())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),b()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:h=>l(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:x,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:y,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Qe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},fh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const b=o.useRef(!1),y=!!l,x=s.find(p=>p.name===u)??s[0],h=d>0&&f,m=a||e!==null||y||!x||h,j=a||e!==null||y||s.length===0,C=c>0||d>0,N=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=h?"Commit or stash your changes before syncing":x?C?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",g=()=>{x&&r(x)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:h?0:void 0,children:t.jsxs("button",{type:"button",onClick:g,disabled:m,className:B("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:N})]})})}),t.jsx(st,{sideOffset:8,children:v})]}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:j,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Qt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(p=>t.jsx(St,{onSelect:A=>{if(b.current){A.preventDefault(),b.current=!1;return}n(p)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(k,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${p.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:p.fetchUrl})]})}),i&&p.name!==u?t.jsx(Qe,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||y,onPointerDown:A=>{b.current=!0,A.preventDefault(),A.stopPropagation()},onClick:A=>{b.current=!0,A.preventDefault(),A.stopPropagation(),i(p)},"aria-label":`Remove remote ${p.name}`,title:`Remove remote ${p.name}`,children:l===p.name?t.jsx(k,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(k,{name:"close",className:"size-3.5"})}):null]})},p.name))})]})]})},hh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ph={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function za(e){return e&&ph[e]||"var(--primary)"}const ui=({icon:e,className:s,colorToken:n})=>{const r=hh[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:za(n)}})},$a=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:za(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(ui,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Git identity"})]}),t.jsx(Qt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(St,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(ui,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(k,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},mh=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(et,{delayDuration:n,children:[t.jsx(tt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(st,{sideOffset:8,children:a})]})},Sx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:b,onRenameBranch:y,activeIdentityProfile:x,availableIdentities:h,onSelectIdentity:m,isApplyingIdentity:j,isWorktreeMode:C,onOpenHistory:N,onOpenGraph:v,onOpenStashes:g,onOpenUpdateBranch:p,onOpenReintegrateCommits:A,pullRequest:D,prChecks:I,onOpenPullRequest:E})=>{if(!e)return null;const M=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:N||v||g||p?t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsx(Qe,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(k,{name:"more-fill",className:"size-4"})})})}),t.jsx(st,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Qt,{align:"end",children:[N?t.jsxs(St,{onSelect:N,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(St,{onSelect:v,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,g?t.jsxs(St,{onSelect:g,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,p?t.jsxs(St,{onSelect:p,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,A?t.jsxs(St,{onSelect:A,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),P=I?I.state==="success"?"var(--status-success)":I.state==="failure"?"var(--status-error)":"var(--status-warning)":null,H=D?D.state==="merged"?"merged":D.state==="closed"?"closed":D.draft?"draft":I?.state==="failure"||D.mergeable===!1||D.mergeableState==="blocked"||D.mergeableState==="dirty"?"blocked":"open":null,ee=D&&E?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",onClick:E,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(k,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${H})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${D.number}`}),P?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:P}}):null]})}),t.jsx(st,{sideOffset:8,children:"Open pull request"})]}):null,te=t.jsx(fh,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),se=e.upstreamComparison?t.jsx(mh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,_=t.jsx($a,{activeProfile:x,identities:h,onSelect:m,isApplying:j,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:C?t.jsx(uh,{currentBranch:e.current,onRename:y}):t.jsx(ch,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:b,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:_})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[ee?t.jsx("div",{className:"shrink-0",children:ee}):null,t.jsx("div",{className:"min-w-0 flex-1"}),se?t.jsx("div",{className:"min-w-0 shrink",children:se}):null,M,t.jsx("div",{className:"shrink-0",children:te})]})]})},gh=e=>e==="/",Gs=e=>e.replace(/\\/g,"/"),Ys=e=>{if(!e||gh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Ks=e=>e.endsWith("/"),Un=e=>{const s=e.trim();return!s||Ks(s)?s:`${s}/`},po=e=>e.lastIndexOf("/"),Ua=e=>{if(Ks(e))return e;const s=po(e);return s<0?e:e.slice(0,s+1)},Ga=e=>{const s=po(e);return e.slice(s+1)},Ka=e=>{const s=Ys(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=po(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ha=e=>Ks(e)&&Ka(e)!==null,xh=e=>{if(!Ha(e))return null;const s=Ys(e.trim());return Ga(s)||s},bh=(e,s)=>`${Ua(e)}${s}/`,ws=e=>{if(!e)return null;const s=Ys(Gs(e.trim()));return s?s.toLowerCase():null},fi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},yh=(e,s)=>{const n=Ys(Gs(e.trim())),r=Ys(Gs(s.trim()));if(!n)return"";if(!r)return Un(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Un(n)},vh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,ur=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},wh=async()=>bu(),Sh=({open:e,onOpenChange:s})=>{const n=Ds(F=>F.homeDirectory),r=zt(F=>F.projects),i=zt(F=>F.addProject),a=ce(F=>F.setActiveMainTab),l=ce(F=>F.setSessionSwitcherOpen),c=Le(F=>F.openNewSessionDraft),d=js(F=>F.profiles),u=js(F=>F.globalIdentity),f=js(F=>F.defaultGitIdentityId),b=js(F=>F.loadProfiles),y=js(F=>F.loadGlobalIdentity),x=js(F=>F.loadDefaultGitIdentityId),{canRequestAccess:h,startAccessing:m}=ah(),{isMobile:j,isTablet:C}=Ps(),N=j||C,v=o.useRef(null),g=o.useRef(new Map),[p,A]=o.useState(""),[D,I]=o.useState("~/"),[E,M]=o.useState([]),[P,H]=o.useState(!1),[ee,te]=o.useState(!1),[se,_]=o.useState(null),[K,L]=o.useState(0),[z,Y]=o.useState(0),[re,U]=o.useState(!1),[Te,Re]=o.useState(!1),[Ge,Ke]=o.useState(!1),[Ue,De]=o.useState(""),[X,ge]=o.useState(null),[We,ke]=o.useState(!1),[je,$e]=o.useState("right"),nt=o.useRef("~/"),_e=p||n,Q=o.useMemo(()=>new Set(r.map(F=>ws(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;I("~/"),M([]),Y(0),U(!1),Re(!1),Ke(!1),De(""),ge(null),ke(!1),nt.current="~/",$e("right"),N||requestAnimationFrame(()=>ur(v.current));let F=!1;return(async()=>{const Be=await wh();F||(A(Be||n||""),N||requestAnimationFrame(()=>ur(v.current)))})(),()=>{F=!0}},[n,e,N]),o.useEffect(()=>{e&&(b(),y(),x())},[x,b,y,e]);const V=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Ie of d)F.set(Ie.id,Ie);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!Ge||X!==null)return;const F=typeof f=="string"?f.trim():"";if(F&&V.some(Be=>Be.id===F)){ge(F);return}const Ie=V.find(Be=>Be.authType==="ssh"||Be.sshKey);Ie&&ge(Ie.id)},[V,f,Ge,e,X]);const xe=o.useMemo(()=>V.find(F=>F.id===X)??null,[V,X]),q=o.useMemo(()=>Ua(D),[D]),Se=o.useMemo(()=>Ks(D)?"":Ga(D),[D]),be=o.useMemo(()=>_e?fi(q,_e):"",[q,_e]);o.useEffect(()=>{const F=nt.current;F!==q&&($e(q.length>=F.length?"right":"left"),nt.current=q)},[q]),o.useEffect(()=>{if(!e||!be){M([]),_(null);return}let F=!1;return H(!0),te(!1),_(null),mu(be).then(Ie=>{if(F)return;te(!1),_(null);const Be=Ie.filter(ot=>ot.isDirectory).map(ot=>({name:ot.name,path:Gs(ot.path)})).sort((ot,O)=>ot.name.localeCompare(O.name));M(Be)}).catch(Ie=>{if(!F){M([]);const Be=gu(Ie)?Ie.reason:"unknown";_(Be),te(Be==="not-found")}}).finally(()=>{F||H(!1)}),()=>{F=!0}},[be,K,e]);const Pe=o.useMemo(()=>{const F=Se.toLowerCase(),Ie=We||Se.startsWith(".");return E.filter(Be=>Be.name.toLowerCase().startsWith(F)&&(Ie||!Be.name.startsWith(".")))},[Se,E,We]),lt=o.useMemo(()=>xh(D),[D]),pt=o.useMemo(()=>Ka(D),[D]),Ve=o.useMemo(()=>{const F=[],Ie=ws(be);Ha(D)&&lt&&pt&&F.push({type:"parent",value:"browse:up",name:lt,path:pt,alreadyAdded:!!(Ie&&Q.has(Ie))});for(const Be of Pe){const ot=ws(Be.path);F.push({type:"directory",value:`browse:${Be.path}`,name:Be.name,path:Be.path,alreadyAdded:!!(ot&&Q.has(ot))})}return F},[Q,be,lt,Pe,pt,D]);o.useEffect(()=>{Y(0)},[D,Ve.length]);const Me=o.useMemo(()=>_e?Ys(fi(D,_e)):"",[_e,D]),Ne=ws(Me),Fe=!!(Ne&&Q.has(Ne)),ft=o.useMemo(()=>Se?Pe.find(F=>F.name===Se)??null:null,[Se,Pe]),wt=!!(Me&&!Fe&&(se===null||se==="not-found")&&(Ks(D)&&ee||!Ks(D)&&Se.trim().length>0&&ft===null)),rt=!re&&!Te&&!Fe&&se!=="os-permission"&&se!=="invalid-response"&&se!=="unknown"&&!!Me,$=rt&&Ue.trim().length>0,pe=Ve[z]??null,Ce=!!pe,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",W=Fe?"Already added":Ge?re?"Cloning...":"Clone & add":re?"Adding...":wt?"Create & add":"Add folder",J=Ge?$:rt;o.useLayoutEffect(()=>{const F=v.current;F&&(F.scrollLeft=F.scrollWidth)},[D]),o.useLayoutEffect(()=>{!e||N||ur(v.current)},[e,N]),o.useLayoutEffect(()=>{const F=Ve[z];F&&g.current.get(F.value)?.scrollIntoView({block:"nearest"})},[z,Ve]);const he=o.useCallback(()=>{s(!1)},[s]),we=o.useCallback((F,Ie)=>{a("chat"),j&&l(!1),c({selectedProjectId:F,directoryOverride:Ie}),he()},[he,j,c,a,l]),Ae=o.useCallback(async F=>{if(!F||re)return;const Ie=ws(F);if(Ie&&Q.has(Ie))return;let Be=F;U(!0);try{const ot=!Ge&&wt&&ws(F)===ws(Me);if(Ge){const ne=Ue.trim();if(!ne){ae.error("Enter a repository URL before cloning.");return}const fe=await Jt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ne,destinationPath:F,gitIdentityId:xe?.id??null})});if(!fe.ok)throw new Error("Failed to clone git repository");Be=(await fe.json()).path||F}else if(ot&&!(await Jt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:be?{directory:be}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const O=i(Be);if(!O){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}we(O.id,O.path)}catch(ot){ae.error("Failed to select directory",{description:ot instanceof Error?ot.message:"Unknown error occurred."})}finally{U(!1)}},[i,Q,be,Ue,Ge,re,we,xe?.id,wt,Me]),He=o.useCallback(F=>{I(Un(F))},[]),ct=o.useCallback(F=>{I(bh(D,F.name))},[D]),yt=o.useCallback(F=>{if(F){if(F.type==="parent"){He(F.path);return}ct(F)}},[He,ct]),qe=o.useCallback(async F=>{const Ie=await m(F);if(!Ie.success)return ae.error("Failed to open directory",{description:Ie.error||"Desktop could not grant file access."}),!1;const Be=_e?yh(F,_e):Un(Gs(F));return He(Be),!0},[He,_e,m]),ht=o.useCallback(async()=>{if(!Te){Re(!0);try{if(io()){const Ie=await ao(Me);if(!Ie.success||!Ie.path){Ie.error&&Ie.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:Ie.error});return}await qe(Ie.path);return}const F=await xu(Me);if(F.status==="cancelled")return;if(F.status!=="picked"){ae.error("Couldn't open a folder picker",{description:F.error});return}await qe(F.path)}catch(F){ae.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Re(!1)}}},[qe,Te,Me]),gt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),Y(Ie=>Math.min(Ve.length-1,Ie+1));return}if(F.key==="ArrowUp"){F.preventDefault(),Y(Ie=>Math.max(0,Ie-1));return}if(F.key==="Enter"){if(F.preventDefault(),vh(F)){Ae(Me);return}Ce&&yt(pe);return}F.key==="Backspace"&&D===""&&(F.preventDefault(),he())},[yt,Ae,he,Ce,pe,D,Ve.length,Me]),Oe=t.jsxs("button",{type:"button",onClick:()=>ke(F=>!F),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[We?t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ze=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(Hs,{ref:v,value:D,onChange:F=>I(Gs(F.target.value)),onKeyDown:gt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Qe,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:re||Te,onMouseDown:F=>F.preventDefault(),onClick:()=>{ht()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),Te?"Opening...":"Browse"]})]})}),xt=Ve.some(F=>F.type==="parent"),At=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Qe,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ge,disabled:re||Te,onClick:()=>Ke(F=>!F),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ge?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Hs,{value:Ue,onChange:F=>De(F.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx($a,{activeProfile:xe,identities:V,onSelect:F=>ge(F.id),isApplying:re,iconOnly:!0})]})]}):null,Fe?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:B("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",je==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:P?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):se&&se!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:se==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[se==="os-permission"&&h?t.jsx(Qe,{size:"xs",onClick:()=>{ht()},disabled:Te,children:"Grant access"}):null,t.jsx(Qe,{variant:"outline",size:"xs",onClick:()=>L(F=>F+1),children:"Try again"})]})]}):Ve.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:Ve.map((F,Ie)=>{const Be=Ie===z,ot=F.type==="directory"&&xt;return t.jsxs("button",{ref:O=>{O?g.current.set(F.value,O):g.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>Y(Ie),onMouseDown:O=>O.preventDefault(),onClick:()=>yt(F),className:B("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Be&&"bg-interactive-selection text-interactive-selection-foreground",!Be&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:B("flex min-w-0 flex-1 items-center gap-2",ot&&"pl-4"),children:[F.type==="parent"?t.jsx(k,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(k,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:F.name})]}),F.alreadyAdded?t.jsx("span",{className:B("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Be?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(k,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(k,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},q)]})}),$t=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ze,At]}),Rt=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(k,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:w}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),jt=t.jsx(Qe,{size:j?"xs":"default",onClick:()=>{Ae(Me)},disabled:!J,className:B(j&&"w-full flex-1"),children:W}),kt=()=>t.jsxs(t.Fragment,{children:[j?null:Rt,t.jsx("div",{className:B("flex w-full flex-row justify-end gap-2 sm:w-auto",j&&"justify-stretch"),children:jt})]});return j?t.jsx(ea,{open:e,onClose:he,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:kt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Oe}),$t]})}):t.jsx(is,{open:e,onOpenChange:s,children:t.jsxs(as,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(bs,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Es,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Oe]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:$t}),t.jsx(Ts,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:kt()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,jx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=ed,c=Le(A=>A.deleteSessions),d=ce(A=>A.showDeletionDialog),u=ce(A=>A.setShowDeletionDialog),{isMobile:f,isTablet:b,hasTouchInput:y}=Ps(),x=f||b||y;o.useEffect(()=>yu(()=>{s(!1)}),[]);const h=o.useCallback(A=>{r({sessions:A.sessions,dateLabel:A.dateLabel})},[]),m=o.useCallback(()=>{r(null),a(!1)},[]),j=o.useCallback(async A=>{if(A.sessions.length===0)return;if(A.sessions.length===1){const M=A.sessions[0];await l(M.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const D=A.sessions.map(M=>M.id),{deletedIds:I,failedIds:E}=await c(D);if(I.length>0){const M=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:A.dateLabel?`Removed all sessions from ${A.dateLabel}.`:void 0;ae.success(I.length===1?"Deleted {count} session":`Deleted ${I.length} sessions`,{description:Cn(M)})}E.length>0&&ae.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Is.onDeleteRequest(A=>{if(!d){j(A);return}h(A)}),[h,d,j]),o.useEffect(()=>Is.onDirectoryRequest(()=>{s(!0)}),[]);const C=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const A=n.sessions[0];if(!await l(A.id)){ae.error("Failed to delete session"),a(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const A=n.sessions.map(M=>M.id),D=await c(A),I=D.deletedIds,E=D.failedIds;if(I.length>0){const M=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(I.length===1?"Deleted {count} session":`Deleted ${I.length} sessions`,{description:Cn(M),action:{label:"OK",onClick:()=>{}}})}if(E.length>0&&(ae.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:Cn("Please try again in a moment.")}),I.length===0)){a(!1);return}}m()}finally{a(!1)}}},[n,l,c,m]),N=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(A=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:A.title||"Untitled Session"})},A.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,g=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(k,{name:"checkbox-blank",className:"size-4"}):t.jsx(k,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Qe,{variant:"ghost",onClick:m,disabled:i,children:"Cancel"}),t.jsx(Qe,{variant:"destructive",onClick:C,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),p=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[x?t.jsx(ea,{open:!!n,onClose:()=>{i||m()},title:p,footer:t.jsx("div",{className:"flex justify-end gap-2",children:g}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[N&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:N}),v]})}):t.jsx(is,{open:!!n,onOpenChange:A=>{if(!A){if(i)return;m()}},children:t.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(bs,{children:[t.jsx(hs,{children:p}),N&&t.jsx(Es,{children:N})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ts,{className:"mt-2 gap-2 pt-1 pb-1",children:g})]})}),t.jsx(Sh,{open:e,onOpenChange:s})]})};function Cx(){const e=o.useRef(!1),s=o.useRef(!1),n=Le(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),i=ce(f=>f.setSettingsDialogOpen),a=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=o.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const b=Le.getState().currentSessionId,y=Xs().getState().selectedSessionId;if(f.sessionId!==b||f.sessionId!==y){const x=Le.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,x)}}if(f.settingsPath){a(ih(f.settingsPath)),i(!0);return}ce.getState().isSettingsDialogOpen&&i(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const f=Le.getState(),b=Xs().getState(),y=ce.getState();return{sessionId:ar({currentSessionId:f.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:f.newSessionDraft}),tab:y.activeMainTab,isSettingsOpen:y.isSettingsDialogOpen,settingsPath:y.settingsPage,diffFile:y.pendingDiffFile}},[]),u=o.useCallback((f={})=>{if(s.current)return;const b=d();Ur(b,f)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Go()))return;const f=Ko();(async()=>(await c(f),Ur({...d(),sessionId:f.sessionId??ar({currentSessionId:Le.getState().currentSessionId,piSelectedSessionId:Xs().getState().selectedSessionId,draft:Le.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const f=()=>{const j=Le.getState(),C=Xs().getState();return ar({currentSessionId:j.currentSessionId,piSelectedSessionId:C.selectedSessionId,draft:j.newSessionDraft})};let b=f(),y=Le.getState().newSessionDraft?.open===!0;const x=()=>{const j=Le.getState(),C=f(),N=j.newSessionDraft?.open===!0;C===b&&N===y||s.current||(b=C,y=N,u({replace:!0}))},h=Le.subscribe(()=>{x()}),m=Xs().subscribe(()=>{x()});return()=>{h(),m()}},[u]),o.useEffect(()=>{let f=ce.getState().activeMainTab,b=ce.getState().isSettingsDialogOpen,y=ce.getState().settingsPage,x=ce.getState().pendingDiffFile;return ce.subscribe(m=>{if(s.current)return;const j=m.activeMainTab!==f,C=m.isSettingsDialogOpen!==b,N=m.settingsPage!==y,v=m.pendingDiffFile!==x&&m.activeMainTab==="diff";f=m.activeMainTab,b=m.isSettingsDialogOpen,y=m.settingsPage,x=m.pendingDiffFile,(j||C||N||v)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const b=Ko();if(Go())c(b);else{const y=ce.getState();y.isSettingsDialogOpen&&i(!1),y.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,i])}function jh(e=!0){const s=Fn(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!e)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=b=>{const y=Math.round(b*1e3);return Math.max(a,Math.min(l,y))},f=b=>{c||(d=window.setTimeout(async()=>{const y=await n.current(),x=typeof y=="number"&&Number.isFinite(y)?u(y):i;f(x)},b))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function kx(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return jh(e),null}const hi=12,Ch=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],kh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Ch,onComplete:a})=>{const l=Ye.useRef(!1);Ye.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ye.useMemo(()=>Array.from({length:hi},(d,u)=>{const f=Math.PI*2*u/hi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:B("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((f,b)=>{const y=f.x*d.radius,x=f.y*d.radius,h={"--translate-x":`${y}px`,"--translate-y":`${x}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:h},`${d.id}-${b}-${s}`)})},`${d.id}-${s}`)})}):null},Nh=({durationMs:e=3400}={})=>{const[s,n]=Ye.useState({isActive:!1,cycle:0}),r=Ye.useRef(null),i=Ye.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ye.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Ye.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return Ye.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Wa=o.createContext(void 0),Nx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Nh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Wa.Provider,{value:a,children:[e,t.jsx(kh,{isActive:s,burstKey:n})]})},Ah={triggerFireworks:()=>{},dismissFireworks:()=>{}},Ax=()=>o.useContext(Wa)??Ah,pi=380,mi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Gn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),kn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(k,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ih=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),f=o.useRef(null),[b,y]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const h=()=>{const C=n.current?.getBoundingClientRect(),N=f.current?.getBoundingClientRect();if(!C||!N){y(null);return}const v=C.left-N.left,g=Math.min(Math.max(v,8),Math.max(8,N.width-pi-8));y(g)};h();const m=f.current;if(typeof ResizeObserver>"u"||!m)return;const j=new ResizeObserver(h);return j.observe(m),()=>j.disconnect()},[n,u,e,a]);const x=u&&b!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const h=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(h)},[e,a]),o.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),o.useEffect(()=>{if(!e)return;const h=m=>{const j=m.target;if(!(j instanceof Node)){s();return}i.current?.contains(j)||n.current?.contains(j)||s()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("wheel",h,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("wheel",h,!0)}},[n,s,e]),a?t.jsxs("div",{ref:f,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:B("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",x?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...x?{top:8,left:b??8,width:`min(${pi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(kn,{iconNode:t.jsx(sa,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:B("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(kn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheRead)})}),t.jsx(kn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(kn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CuSNEV7s.js","assets/SessionSwitcherDropdown-o1RjhCfF.js","assets/index-BAqpUCjs.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-riABQmQ_.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-CkHYYg0E.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-Dp_Z-0GD.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-CW8w438f.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/computeVirtualFileMetrics-DdOCbMyK.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-D4hgTRxT.js","assets/isDiffPlainText-CGIf0q8p.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
+ import{_ as $s}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ye,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{bd as _s,be as yc,ao as vc,o as qi,D as is,w as as,y as hs,I as k,ay as Cs,bf as Bo,f as B,B as Qe,av as cn,T as et,q as tt,s as st,bg as Ji,bh as wc,bi as Sc,bj as jc,bk as Cc,h as Le,bl as kc,bm as _o,bn as Nc,bo as Ac,bp as zo,bq as Ic,br as Dc,bs as Pc,bt as Ec,bu as Ar,bv as Tc,t as ae,as as Yt,at as Vt,au as Qt,Y as Hs,bw as Rc,bx as Mc,by as Fc,bz as Lc,bA as $o,a5 as Bt,bB as Oc,bC as Bc,bD as _c,bE as zc,bF as $c,bG as Uc,bH as Ir,bI as Xi,bJ as Zi,bK as Gc,bL as Kc,bM as Hc,bN as Wc,bO as Yc,bP as Vc,aY as Dr,r as Us,bQ as As,bR as Qc,a_ as Is,b3 as qc,b4 as Jc,b5 as Xc,b6 as Zc,b7 as ir,b8 as Js,bS as Uo,az as St,b as zt,aQ as Ps,bT as ea,x as bs,z as Es,A as Ts,bU as ed,bV as Xs,bW as ar,bX as Go,bY as Ko,bZ as nn,aC as td,aS as ta,aH as Ho,aF as sd,aE as nd,aW as sa,g as eo,b_ as rd,b$ as na,c0 as od,c1 as ra,e as to,c2 as id,C as Wn,K as oa,c3 as ad,c4 as Gt,aM as ia,c as Pr,c5 as ld,c6 as cd,c7 as Yn,c8 as Rn,c9 as aa,_ as dn,$ as un,Z as dd,ca as ud,cb as Wo,aZ as la,cc as fd,cd as ca,b1 as so,b2 as rn,ce as Yo,cf as Vn,aw as hd,cg as da,H as pd,ch as no,ci as md,cj as gd,j as ua,l as xd,ck as bd,cl as yd,k as vd,cm as Er,n as wd,S as Sd,cn as fa,co as jd,cp as Cd,m as kd,d as Nd,cq as Ad,a as Id,ax as Dd,b0 as Pd,cr as Ed,a$ as Td,cs as Rd,ct as Md,cu as Fd,cv as Ld,af as Od,cw as Vo,cx as Bd,aN as _d,cy as zd,cz as $d,cA as wn,cB as Qo,cC as Ud,cD as qo,cE as Jo,cF as Gd,aL as ha,a3 as Kd,E as Hd,cG as pa,u as Wd,cH as Yd,cI as Vd,aA as Ws,p as Qd,cJ as qd,cK as ma,cL as Jd,cM as Xd,cN as Zd,cO as eu,cP as tu,cQ as su,cR as Xo,cS as nu,cT as ga,cU as ru,cV as ou}from"./SessionSwitcherDropdown-o1RjhCfF.js";import{L as Zo,M as iu,N as ei,O as au,i as lu,P as cu,K as du,r as Jt,Q as fn,b as uu,J as fs,u as ce,R as fu,S as cs,T as ro,q as oo,m as Ds,U as bt,V as io,W as ao,X as hu,Y as pu,D as mu,Z as gu,_ as xu,$ as bu,a0 as yu,a1 as ss,a2 as Tr,a as Qn,a3 as vu,a4 as wu,a5 as Su,a6 as ju,a7 as xa,I as ba,E as on,a8 as Rr,e as Mr,d as Sn,a9 as Cu,aa as ku,ab as Zs,ac as lr,ad as ya,C as Nu,o as Au,ae as Fr,af as ks,ag as ti,ah as Lr,ai as va,aj as Or,ak as Iu,al as Du,am as Pu,w as Eu,an as Tu}from"./index-BAqpUCjs.js";import{C as wa,a as Sa,M as Br,b as _r,c as zr,d as ja,S as Ca,D as Ru,e as Mu,f as Fu,g as Lu,h as Ou,i as Bu,j as _u,k as zu,l as $u}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as ka,p as lo,u as $r,a as Uu}from"./vendor-zustand-CnsBKjP5.js";import{u as Gu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as qn,d as hn,P as co,D as Jn,e as Xn,f as Na,b as Ku,a as Hu,T as Wu,M as Yu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as uo,v as Aa,u as Zn,a as Vu,h as Qu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as er}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as qu}from"./permissionStore-BRcQ9Jgt.js";const Ju=3;let zn=0;const Ia=[],Xu=()=>zn<Ju?(zn+=1,Promise.resolve()):new Promise(e=>{Ia.push(e)}),Zu=()=>{const e=Ia.shift();if(e){e();return}zn=Math.max(0,zn-1)},ef=async e=>{await Xu();try{return await e()}finally{Zu()}},tf="chat";function Da(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(_s.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(_s.SETTINGS,n),s}return e.tab!==tf&&s.set(_s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(_s.FILE,e.diffFile),s}function sf(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=e.toString();return i?`${r}?${i}`:r}function nf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Da(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(_s.SESSION)&&s.set(_s.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Ur(e,s={}){if(!(typeof window>"u")&&!(!s.force&&nf(e)))try{const n=Da(e),r=sf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const rf=["typescript","javascript","tsx","jsx","json","markdown"],Pa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let si=null;const Ea=()=>(si??=Promise.all([$s(()=>import("./index-CuSNEV7s.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),$s(()=>import("./workerFactory-tw7cIdmV.js"),[]),$s(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,8,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),si),pn={},ni=new Set,Gr=new Set;let Mn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of Gr)e()},Ta=(e,s)=>{s.setRenderOptions({theme:Mn,lineDiffType:Pa[e].lineDiffType})},Kr=e=>{typeof window>"u"||ni.has(e)||(ni.add(e),Ea().then(s=>{if(pn[e])return;const n=Pa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:rf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,Ta(e,r),of()}))},af=e=>(Gr.add(e),()=>Gr.delete(e)),lf=e=>{if(!(Mn.light===e.light&&Mn.dark===e.dark)){Mn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&Ta(s,n)}}},tx=({children:e})=>{const s=yc(),n=Zo(!1),r=Zo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ye.useEffect(()=>{let d=!1;return Ea().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ye.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Kr("unified"),Kr("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},sx=(e="unified")=>{const s=Ye.useSyncExternalStore(af,()=>pn[e],()=>{});return Ye.useEffect(()=>{Kr(e)},[e]),s};function cf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=vc();return e}catch{return"unknown"}}function df(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function uf(){const e=uu();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function ff(e){const s=new URLSearchParams;return s.set("deviceClass",cf()),s.set("arch",df()),s.set("platform",uf()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",fn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function cr(e,s){try{const n=ff(e);s&&n.set("currentVersion",s);const r=await Jt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function hf(){return lu()?"mobile":cu()?"desktop":du()?"web":null}const ri={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Fn=ps()((e,s)=>({...ri,checkForUpdates:async()=>{const n=hf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.3.3",[l,c]=await Promise.allSettled([ei(),cr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await cr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await cr("mobile","0.3.3"),i=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const i=await ei();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await au(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await iu())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ri)}})),oi="https://github.com/RyderAsKing/PiChamber/releases";function pf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function mf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ii(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function gf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function xf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ai=2e3,bf=600*1e3;async function yf(){try{const e=await Jt("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function vf(){try{return(await Jt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function wf(e,s=Math.ceil(bf/ai),n=ai){for(let r=0;r<s;r++){try{const i=await Jt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await vf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ra=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,b]=Ye.useState(!1),[y,x]=Ye.useState("idle"),[h,m]=Ye.useState(null),j=n?.version?n.releaseUrl||`${oi}/tag/v${n.version}`:oi,C=n?.downloadUrl||j,N=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",g=u==="mobile",p=n?.updateCommand||"pichamber update";Ye.useEffect(()=>{e||(x("idle"),m(null))},[e]);const A=async()=>{(await cn(p)).ok&&(b(!0),setTimeout(()=>b(!1),2e3))},D=Ye.useCallback(async H=>{await qi(H)},[]),I=Ye.useCallback(async()=>{x("updating"),m(null);const H=await yf();if(!H.success){x("error"),m(H.error||"Update failed");return}H.autoRestart&&(x("restarting"),await new Promise(te=>setTimeout(te,2e3))),x("reconnecting"),await wf(n?.currentVersion)?window.location.reload():(x("error"),m("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),E=Ye.useCallback(()=>{D(C)},[D,C]),M=y!=="idle"&&y!=="error",P=Ye.useMemo(()=>{if(!n?.body)return null;const H=n.body.trim();if(!H)return null;const ee=xf(H);return ee.length===0?{kind:"raw",title:"What's new",content:ii(H)}:{kind:"sections",title:"What's new",sections:[...ee].sort((se,_)=>gf(se.version,_.version)).map(se=>({version:se.version,dateLabel:pf(se.date),content:ii(mf(se.raw)||H)}))}},[n?.body]);return t.jsx(is,{open:e,onOpenChange:M?void 0:s,children:t.jsxs(as,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(hs,{className:"flex items-center gap-2.5",children:[t.jsx(k,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:y==="restarting"||y==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&M&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(k,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[y==="updating"&&"Installing update...",y==="restarting"&&"Server restarting...",y==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),P&&!M&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Cs,{className:"max-h-[400px] p-0",fillContainer:!1,children:P.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:H=>{const te=H.target.closest("a");te&&te.href&&(H.preventDefault(),H.stopPropagation(),D(te.href))},children:t.jsx(Bo,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(H=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",H.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:H.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:ee=>{const se=ee.target.closest("a");se&&se.href&&(ee.preventDefault(),ee.stopPropagation(),D(se.href))},children:t.jsx(Bo,{content:H.content,disableLinkSafety:!0,enableFileReferences:!1})})]},H.version))})})}),v&&y==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:p}),t.jsx("button",{onClick:A,className:B("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(k,{name:"check",className:"h-4 w-4"}):t.jsx(k,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!g&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[N,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${N}%`}})})]}),(l||h)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||h})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!g&&!i&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!g&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!g&&i&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),g&&t.jsxs(Qe,{onClick:E,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!M&&t.jsxs("button",{onClick:I,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&M&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Sf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:B("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:B("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),mn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(et,{open:r,onOpenChange:i,children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:B("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(k,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(st,{sideOffset:8,className:B("max-w-sm",n),children:e})]})},nx="w-full min-w-40 max-w-48",jf="settings",Cf="w-full min-w-40 max-w-48",rx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",kf="w-full max-w-[24rem]",ox="min-w-0 flex-1",ix="flex w-full min-w-0 items-center gap-2",ax="typography-meta shrink-0 text-muted-foreground tabular-nums",Ma="space-y-3.5",Nf="space-y-1.5",lx="typography-settings-page-title text-muted-foreground",Af="typography-settings-section-title text-foreground",cx="typography-settings-section-title text-foreground",Fa="typography-settings-group-title text-foreground",fo="typography-settings-field-label text-foreground",If="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",dx="typography-meta font-medium text-foreground",ux="typography-settings-section-title text-foreground",Df=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:B("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Af,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:If,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:B(d),children:a})]})},fx=({children:e,className:s})=>t.jsx("div",{className:B("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Pf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:B(Fa,s),children:e}),hx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:B("space-y-2",i),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Pf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:B(a),children:r})]}),zs=({label:e,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:gn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:B("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:B("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},px=({label:e,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":i,className:B("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:B(gn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:B("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),mx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:B("pt-4",s),children:e}),Ef=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{i||s(!e)},b=r!=null;return t.jsxs("div",{"data-settings-item":l,className:B("group flex cursor-pointer gap-2 py-0.5",b?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:f,onKeyDown:y=>{(y.key===" "||y.key==="Enter")&&(y.preventDefault(),f())},children:[t.jsx(Ji,{checked:e,onChange:s,disabled:i,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:fo,children:n}),d,u!=null?t.jsx(mn,{children:u}):null]}),b?t.jsx("span",{className:gn,children:r}):null]})]})},gx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:B("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Sf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:B("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),xx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:B(Nf,n),children:s});function bx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:B("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Qe,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Tf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(wc,{className:"w-full max-w-md",children:[t.jsx(Sc,{className:"text-center",children:t.jsxs(jc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(k,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Cc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Qe,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(k,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Rf(e){return t.jsx(Tf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const yx=({active:e=!0,readOnly:s=!1})=>{const n=Le(r=>r.currentSessionId);return t.jsx(Rf,{sessionId:n||void 0,children:t.jsx(kc,{active:e,readOnly:s},n??"no-session")})};function Mf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ho=Ye.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:b,...y},x)=>{const h=Ye.useRef(null),m=Ye.useRef(null),[j,C]=Ye.useState(null),N=c??j,v=Ye.useCallback(p=>{const A=h.current;if(!A)return;m.current={startY:p.clientY,startHeight:A.getBoundingClientRect().height};const D=p.currentTarget;D.setPointerCapture(p.pointerId);const I=M=>{const P=m.current;if(!P)return;const H=P.startHeight+(M.clientY-P.startY),ee=Math.max(82,H);d?d(ee):C(ee)},E=()=>{m.current=null,D.removeEventListener("pointermove",I),D.removeEventListener("pointerup",E),D.removeEventListener("pointercancel",E)};D.addEventListener("pointermove",I),D.addEventListener("pointerup",E),D.addEventListener("pointercancel",E),p.preventDefault()},[d]),g=Ye.useCallback(p=>{if(p.target.closest('textarea, button, [role="separator"]'))return;const D=h.current?.querySelector("textarea");D&&document.activeElement!==D&&(p.preventDefault(),D.focus())},[]);return f?t.jsx(Cs,{as:"textarea",ref:x,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:B("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}):t.jsx("div",{ref:h,onPointerDown:g,style:N!==null?{height:`${N}px`}:void 0,className:B("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:x,className:B("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[b,t.jsx(Mf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ho.displayName="Textarea";const li=(e,s)=>s.updatedAtMs-e.updatedAtMs,$n=ps((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([Dc(),zo()]),i={};for(const a of r.sort(li))i[a.id]=a;s().listenerReady||await Pc(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){e({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){e({isImportsLoading:!0,error:null});try{const n=await Ic();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await zo(),r={};for(const i of n.sort(li))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Ac({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Ec(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await _o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),e(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await Nc(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{e({error:null});try{await _o(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>e({error:null})})),La=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],an=Object.fromEntries(La.map(e=>[e.key,e.Icon])),Hr="pichamber:project-actions-updated",Oa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ds=(e,s)=>`${Oa(e)}::${s}`,Ff=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ci=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Lf=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ci(s.localPort),r=ci(s.remotePort);if(!n||!r)return null;const i=Ff(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},Ba=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Lf(n,r);i&&s.push(i)}return s},Of=(e,s)=>{const n=(e||"").trim();return n&&Ba(s).find(a=>a.id===n)?.url||null},Bf=kf,_a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Df,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Wr=e=>e.name.trim().length>0&&e.command.trim().length>0,_f=e=>e.name.trim().length===0&&e.command.trim().length===0,zf=e=>!Wr(e)&&!_f(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!Wr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Wr)},Uf=450,Gf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kf=()=>({id:Gf(),name:"",command:"",icon:"play"}),Hf=({projectRef:e})=>{const s=o.useMemo(()=>fs(),[]),n=$n(p=>p.instances),r=$n(p=>p.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[f,b]=o.useState(new Set),y=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let p=!1;return c(!0),(async()=>{try{const A=await Ar(e);if(p)return;a(A.actions),u(JSON.stringify({actions:A.actions})),b(new Set(A.actions.map(D=>D.id)))}catch{if(p)return;a([]),u(JSON.stringify({actions:[]})),b(new Set)}finally{p||c(!1)}})(),()=>{p=!0}},[e]);const x=o.useMemo(()=>s?Ba(n):[],[n,s]),h=o.useMemo(()=>$f(i,f),[i,f]),m=o.useMemo(()=>JSON.stringify({actions:h.actions}),[h.actions]),j=d!==null&&h.canPersist&&m!==d,C=o.useCallback(async p=>await Tc(e,{actions:p,primaryActionId:null})?(u(JSON.stringify({actions:p})),b(new Set(p.map(D=>D.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Hr,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!j||l||y.current)return;const p=window.setTimeout(()=>{y.current||(y.current=!0,(async()=>{try{await C(h.actions)}finally{y.current=!1}})())},Uf);return()=>{window.clearTimeout(p)}},[j,l,C,h.actions]);const N=o.useCallback(()=>{const p=Kf();a(A=>[...A,p])},[]),v=o.useCallback(p=>{a(A=>A.filter(D=>D.id!==p))},[]),g=o.useCallback((p,A)=>{a(D=>D.map(I=>I.id===p?A(I):I))},[]);return t.jsx(_a,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Qe,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:N,children:[t.jsx(k,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:B("space-y-6",Bf),children:i.map((p,A)=>{const D=p.icon||"play",I=an[D]||"play",E=p.name.trim()||`Action ${A+1}`,M=zf(p);return t.jsxs("div",{className:Ma,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Fa,children:E}),t.jsx(Qe,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>v(p.id),"aria-label":`Delete ${E}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(zs,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(k,{name:I,className:"h-4 w-4"})})}),t.jsx(Qt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:La.map(P=>{const H=P.Icon,ee=(p.icon||"play")===P.key;return t.jsx("button",{type:"button",onClick:()=>g(p.id,te=>({...te,icon:P.key})),className:B("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",ee&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${P.label}`,children:t.jsx(k,{name:H,className:"h-4 w-4"})},P.key)})})})]}),t.jsx(Hs,{value:p.name,onChange:P=>g(p.id,H=>({...H,name:P.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(zs,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ho,{value:p.command,onChange:P=>g(p.id,H=>({...H,command:P.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),M?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Ef,{checked:p.autoOpenUrl===!0,onChange:P=>g(p.id,H=>({...H,...P?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${E}`}),p.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(zs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Hs,{value:p.openUrl||"",onChange:P=>g(p.id,H=>({...H,openUrl:P.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(zs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:x.length>0?t.jsxs(Rc,{value:p.desktopOpenSshForward&&x.some(P=>P.id===p.desktopOpenSshForward)?p.desktopOpenSshForward:"__none__",onValueChange:P=>{g(p.id,H=>({...H,...P==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:P}}))},children:[t.jsx(Mc,{size:jf,className:"w-full",children:t.jsx(Fc,{placeholder:"Use output/manual URL"})}),t.jsxs(Lc,{children:[t.jsx($o,{value:"__none__",children:"Use output/manual URL"}),x.map(P=>t.jsx($o,{value:P.id,children:P.label},P.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},p.id)})})})},Wf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=Bt(M=>M.providers),d=Bt(M=>M.modelsMetadata),u=ce(M=>M.hiddenModels),f=ce(M=>M.providerOrder),b=ce(M=>M.setProviderOrder),y=ce(M=>M.isFavoriteModel),x=ce(M=>M.toggleFavoriteModel),h=ce(M=>M.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:j}=Oc(),[C,N]=o.useState(!1),[v,g]=o.useState("");o.useEffect(()=>{C||g("")},[C]);const p=e?c.find(M=>M.id===e.providerId):void 0,A=e&&p?(Array.isArray(p.models)?p.models:[]).find(M=>M.id===e.modelId):void 0,D=e?Bc(A,e.modelId):s,I=o.useMemo(()=>e?u.filter(M=>!(M.providerID===e.providerId&&M.modelID===e.modelId)):u,[u,e]),E=o.useCallback(M=>{l({providerId:M.providerID,modelId:M.modelID}),N(!1)},[l]);return t.jsxs(Yt,{modal:!1,open:C,onOpenChange:M=>{r||N(M)},children:[t.jsx(Vt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:B(zc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(_c,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:B("truncate",e?"text-foreground":"text-muted-foreground"),children:D})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx($c,{providers:c,favoriteModels:m,recentModels:j,modelsMetadata:d,searchQuery:v,onSearchQueryChange:g,onSelect:E,labels:{...Wf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:I,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),N(!1)},disabled:r,autoFocus:!0,onEscape:()=>N(!1),isFavorite:M=>y(M.providerID,M.modelID),onToggleFavorite:M=>x(M.providerID,M.modelID),onReorderFavorite:(M,P)=>h(M.providerID,M.modelID,P.providerID,P.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:f,onReorderProvider:b,reorderProviderTitle:"Drag to reorder provider"})})]})},dr="w-full max-w-none",Vf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=Bt(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(_a,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ma,children:[t.jsx(zs,{label:"Name",settingsItem:"projects.name",controlClassName:dr,children:t.jsx(Hs,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(zs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:dr,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:dr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},Qf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Uc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,f)=>{i(u&&f?`${u}/${f}`:void 0)},[]),d=o.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},qf=450,Jf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},qf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Xf=({project:e,onIdentitySave:s})=>{const n=Qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Jf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Vf,{form:n}),t.jsx(Hf,{projectRef:r})]})};function Zf({...e}){return t.jsx(wa,{...e})}function eh({...e}){return t.jsx(Sa,{...e})}function th({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(Br,{children:t.jsx(_r,{className:B("app-region-no-drag z-50",s),children:t.jsx(zr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:B(Ir,e),...i,children:n})})})}function di({className:e,...s}){return t.jsx(ja,{className:B(Xi,e),...s})}function sh({className:e,...s}){return t.jsx(Ca,{className:B(Zi,e),...s})}const js=ps()(ka(lo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=await Vc();return e({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Yc();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:r})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Wc();return e({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=oo()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await Jt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await ro({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return cs("saving"),await Hc(r),cs("saved"),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return cs("saving"),await Kc(n,a),cs("saved"),await s().loadProfiles(),!0}catch(i){return cs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return cs("saving"),await Gc(n),cs("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:fu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=js);const nh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],rh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function oh(e){const s=e.trim().toLowerCase();return nh.find(n=>n.slug===s)??null}function ih(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=rh[s];if(n)return n;const r=oh(s);return r?r.slug:"home"}function vx(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const jn=100;function wx(){const e=ce(I=>I.isArchivePageOpen),s=ce(I=>I.setArchivePageOpen),n=ce(I=>I.setActiveMainTab),r=Le(I=>I.setCurrentSession),i=Le(I=>I.unarchiveSession),a=Ds(I=>I.homeDirectory),l=Dr({archived:!0}),[c,d]=o.useState(""),[u,f]=o.useState(null),[b,y]=o.useState(jn),x=c.trim().toLowerCase(),h=o.useMemo(()=>e?[...l].sort((I,E)=>(E.time?.archived??0)-(I.time?.archived??0)):[],[l,e]),m=o.useMemo(()=>{const I=new Map;for(const E of h){const M=bt(Us(E))??"",P=I.get(M);if(P){P.sessions.push(E);continue}I.set(M,{directory:M,label:M?As(M,a)||M:"other projects",sessions:[E]})}return[...I.values()].sort((E,M)=>M.sessions.length-E.sessions.length)},[a,h]),j=o.useMemo(()=>x?h.filter(I=>(I.title??"").toLowerCase().includes(x)):u===null?h:m.find(I=>I.directory===u)?.sessions??[],[m,x,u,h]),C=j.slice(0,b),N=j.length-C.length,v=l.length,g=o.useCallback(I=>{f(I),y(jn)},[]),p=o.useCallback(I=>{const E=bt(Us(I));r(I.id,E??void 0),n("chat"),s(!1)},[n,r,s]),A=o.useCallback(I=>{i(I.id).then(E=>{E?ae.success("Session restored"):ae.error("Failed to restore session")})},[i]);if(!e)return null;const D=(I,E,M,P,H,ee,te)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:H,title:ee,className:B("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",te?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:E}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),te?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Is.requestDelete({sessions:te,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${E}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},I);return t.jsx(Ru,{open:e,onOpenChange:s,children:t.jsxs(Mu,{children:[t.jsx(Fu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Lu,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Ou,{className:"sr-only",children:"Archived sessions"}),t.jsx(Bu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(_u,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(k,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[D("__all__","All directories",v,u===null,()=>g(null)),m.map(I=>D(I.directory||"__none__",I.label,I.sessions.length,u===I.directory,()=>g(I.directory),I.directory||void 0,I.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:I=>{d(I.target.value),y(jn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:j.length===1?`${j.length} archived session`:`${j.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[C.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:x?"No matching archived sessions":"No archived sessions"})}):C.map(I=>{const E=bt(Us(I))??"",M=E?As(E,a)||E:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>p(I),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),p(I))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:I.title||"Untitled Session"}),x&&M?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:E,children:M}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Qc(I.time?.archived??I.time?.updated??I.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),A(I)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${I.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),Is.requestDelete({sessions:[I],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${I.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},I.id)}),N>0?t.jsx("button",{type:"button",onClick:()=>y(I=>I+jn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const ah=()=>{const[e,s]=Ye.useState(!1),[n,r]=Ye.useState(!1);Ye.useEffect(()=>{s(fs()),r(io())},[]);const i=Ye.useCallback(async c=>e?await ao(c):{success:!0,path:c},[e]),a=Ye.useCallback(async c=>e?await hu():{success:!0},[e]),l=Ye.useCallback(async c=>e?await pu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},lh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ch=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[f,b]=o.useState(""),[y,x]=o.useState(!1),[h,m]=o.useState(!1),[j,C]=o.useState(""),[N,v]=o.useState(!1),g=o.useRef(null),p=o.useCallback(_=>{_.stopPropagation()},[]),A=l.length>1,D=o.useMemo(()=>lh(j),[j]),I=o.useMemo(()=>{const _=f.toLowerCase();return _?s.filter(K=>K.toLowerCase().includes(_)):s},[f,s]),E=o.useMemo(()=>{const _=f.toLowerCase();return _?n.filter(K=>K.toLowerCase().includes(_)):n},[f,n]),M=_=>{if(_===e){u(!1);return}i(_),u(!1),b("")},P=()=>{x(!0),setTimeout(()=>g.current?.focus(),50)},H=async()=>{if(!(!D||N)){if(A){m(!0);return}v(!0);try{await a(D,l[0]),C(""),x(!1),u(!1)}finally{v(!1)}}},ee=async _=>{if(!(!D||N)){v(!0);try{await a(D,_),C(""),x(!1),m(!1),u(!1)}finally{v(!1)}}},te=()=>{m(!1)},se=()=>{C(""),x(!1),m(!1)};return o.useEffect(()=>{d||(b(""),x(!1),m(!1),C(""))},[d]),t.jsxs(Yt,{open:d,onOpenChange:u,children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Current branch"})]}),t.jsx(Qt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(qc,{className:"h-full min-h-0",children:[t.jsx(Jc,{placeholder:"Search branches...",value:f,onValueChange:b,onKeyDown:p}),t.jsxs(Xc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Zc,{children:"No branches found."}),t.jsx(ir,{children:h?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:te,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:D})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(_=>t.jsxs("button",{type:"button",onClick:()=>ee(_),disabled:N,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[N?t.jsx(k,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,_.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:_.pushUrl})]},_.name))})]}):y?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:g,placeholder:"New branch name",value:j,onChange:_=>C(_.target.value),onClick:_=>_.stopPropagation(),onKeyDown:_=>{p(_),_.key==="Enter"?(_.preventDefault(),H()):_.key==="Escape"&&(_.preventDefault(),se())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:H,disabled:!D||N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:N?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:se,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(Js,{onSelect:P,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Uo,{}),t.jsxs(ir,{heading:"Local branches",children:[I.map(_=>t.jsxs(Js,{onSelect:()=>M(_),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:_}),(r?.[_]?.ahead||r?.[_]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[_].ahead||0," ahead ·"," ",r[_].behind||0," behind"]})]}),e===_&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${_}`)),I.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Uo,{}),t.jsxs(ir,{heading:"Remote branches",children:[E.map(_=>t.jsx(Js,{onSelect:()=>M(_),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:_})},`remote-${_}`)),E.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},dh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),uh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),f=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},b=async()=>{if(!e||!s||!a.trim())return;const h=dh(a);if(h===e){i(!1);return}d(!0);try{await s(e,h),i(!1),l("")}finally{d(!1)}},y=()=>{i(!1),l("")},x=h=>{h.key==="Enter"?(h.preventDefault(),b()):h.key==="Escape"&&(h.preventDefault(),y())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),b()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:h=>l(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:x,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:y,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Qe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},fh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const b=o.useRef(!1),y=!!l,x=s.find(p=>p.name===u)??s[0],h=d>0&&f,m=a||e!==null||y||!x||h,j=a||e!==null||y||s.length===0,C=c>0||d>0,N=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=h?"Commit or stash your changes before syncing":x?C?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",g=()=>{x&&r(x)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:h?0:void 0,children:t.jsxs("button",{type:"button",onClick:g,disabled:m,className:B("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:N})]})})}),t.jsx(st,{sideOffset:8,children:v})]}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:j,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Qt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(p=>t.jsx(St,{onSelect:A=>{if(b.current){A.preventDefault(),b.current=!1;return}n(p)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(k,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${p.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:p.fetchUrl})]})}),i&&p.name!==u?t.jsx(Qe,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||y,onPointerDown:A=>{b.current=!0,A.preventDefault(),A.stopPropagation()},onClick:A=>{b.current=!0,A.preventDefault(),A.stopPropagation(),i(p)},"aria-label":`Remove remote ${p.name}`,title:`Remove remote ${p.name}`,children:l===p.name?t.jsx(k,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(k,{name:"close",className:"size-3.5"})}):null]})},p.name))})]})]})},hh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ph={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function za(e){return e&&ph[e]||"var(--primary)"}const ui=({icon:e,className:s,colorToken:n})=>{const r=hh[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:za(n)}})},$a=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:za(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(ui,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Git identity"})]}),t.jsx(Qt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(St,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(ui,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(k,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},mh=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(et,{delayDuration:n,children:[t.jsx(tt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(st,{sideOffset:8,children:a})]})},Sx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:b,onRenameBranch:y,activeIdentityProfile:x,availableIdentities:h,onSelectIdentity:m,isApplyingIdentity:j,isWorktreeMode:C,onOpenHistory:N,onOpenGraph:v,onOpenStashes:g,onOpenUpdateBranch:p,onOpenReintegrateCommits:A,pullRequest:D,prChecks:I,onOpenPullRequest:E})=>{if(!e)return null;const M=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:N||v||g||p?t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsx(Qe,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(k,{name:"more-fill",className:"size-4"})})})}),t.jsx(st,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Qt,{align:"end",children:[N?t.jsxs(St,{onSelect:N,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(St,{onSelect:v,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,g?t.jsxs(St,{onSelect:g,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,p?t.jsxs(St,{onSelect:p,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,A?t.jsxs(St,{onSelect:A,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),P=I?I.state==="success"?"var(--status-success)":I.state==="failure"?"var(--status-error)":"var(--status-warning)":null,H=D?D.state==="merged"?"merged":D.state==="closed"?"closed":D.draft?"draft":I?.state==="failure"||D.mergeable===!1||D.mergeableState==="blocked"||D.mergeableState==="dirty"?"blocked":"open":null,ee=D&&E?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",onClick:E,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(k,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${H})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${D.number}`}),P?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:P}}):null]})}),t.jsx(st,{sideOffset:8,children:"Open pull request"})]}):null,te=t.jsx(fh,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),se=e.upstreamComparison?t.jsx(mh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,_=t.jsx($a,{activeProfile:x,identities:h,onSelect:m,isApplying:j,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:C?t.jsx(uh,{currentBranch:e.current,onRename:y}):t.jsx(ch,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:b,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:_})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[ee?t.jsx("div",{className:"shrink-0",children:ee}):null,t.jsx("div",{className:"min-w-0 flex-1"}),se?t.jsx("div",{className:"min-w-0 shrink",children:se}):null,M,t.jsx("div",{className:"shrink-0",children:te})]})]})},gh=e=>e==="/",Gs=e=>e.replace(/\\/g,"/"),Ys=e=>{if(!e||gh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Ks=e=>e.endsWith("/"),Un=e=>{const s=e.trim();return!s||Ks(s)?s:`${s}/`},po=e=>e.lastIndexOf("/"),Ua=e=>{if(Ks(e))return e;const s=po(e);return s<0?e:e.slice(0,s+1)},Ga=e=>{const s=po(e);return e.slice(s+1)},Ka=e=>{const s=Ys(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=po(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ha=e=>Ks(e)&&Ka(e)!==null,xh=e=>{if(!Ha(e))return null;const s=Ys(e.trim());return Ga(s)||s},bh=(e,s)=>`${Ua(e)}${s}/`,ws=e=>{if(!e)return null;const s=Ys(Gs(e.trim()));return s?s.toLowerCase():null},fi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},yh=(e,s)=>{const n=Ys(Gs(e.trim())),r=Ys(Gs(s.trim()));if(!n)return"";if(!r)return Un(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Un(n)},vh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,ur=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},wh=async()=>bu(),Sh=({open:e,onOpenChange:s})=>{const n=Ds(F=>F.homeDirectory),r=zt(F=>F.projects),i=zt(F=>F.addProject),a=ce(F=>F.setActiveMainTab),l=ce(F=>F.setSessionSwitcherOpen),c=Le(F=>F.openNewSessionDraft),d=js(F=>F.profiles),u=js(F=>F.globalIdentity),f=js(F=>F.defaultGitIdentityId),b=js(F=>F.loadProfiles),y=js(F=>F.loadGlobalIdentity),x=js(F=>F.loadDefaultGitIdentityId),{canRequestAccess:h,startAccessing:m}=ah(),{isMobile:j,isTablet:C}=Ps(),N=j||C,v=o.useRef(null),g=o.useRef(new Map),[p,A]=o.useState(""),[D,I]=o.useState("~/"),[E,M]=o.useState([]),[P,H]=o.useState(!1),[ee,te]=o.useState(!1),[se,_]=o.useState(null),[K,L]=o.useState(0),[z,Y]=o.useState(0),[re,U]=o.useState(!1),[Te,Re]=o.useState(!1),[Ge,Ke]=o.useState(!1),[Ue,De]=o.useState(""),[X,ge]=o.useState(null),[We,ke]=o.useState(!1),[je,$e]=o.useState("right"),nt=o.useRef("~/"),_e=p||n,Q=o.useMemo(()=>new Set(r.map(F=>ws(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;I("~/"),M([]),Y(0),U(!1),Re(!1),Ke(!1),De(""),ge(null),ke(!1),nt.current="~/",$e("right"),N||requestAnimationFrame(()=>ur(v.current));let F=!1;return(async()=>{const Be=await wh();F||(A(Be||n||""),N||requestAnimationFrame(()=>ur(v.current)))})(),()=>{F=!0}},[n,e,N]),o.useEffect(()=>{e&&(b(),y(),x())},[x,b,y,e]);const V=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Ie of d)F.set(Ie.id,Ie);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!Ge||X!==null)return;const F=typeof f=="string"?f.trim():"";if(F&&V.some(Be=>Be.id===F)){ge(F);return}const Ie=V.find(Be=>Be.authType==="ssh"||Be.sshKey);Ie&&ge(Ie.id)},[V,f,Ge,e,X]);const xe=o.useMemo(()=>V.find(F=>F.id===X)??null,[V,X]),q=o.useMemo(()=>Ua(D),[D]),Se=o.useMemo(()=>Ks(D)?"":Ga(D),[D]),be=o.useMemo(()=>_e?fi(q,_e):"",[q,_e]);o.useEffect(()=>{const F=nt.current;F!==q&&($e(q.length>=F.length?"right":"left"),nt.current=q)},[q]),o.useEffect(()=>{if(!e||!be){M([]),_(null);return}let F=!1;return H(!0),te(!1),_(null),mu(be).then(Ie=>{if(F)return;te(!1),_(null);const Be=Ie.filter(ot=>ot.isDirectory).map(ot=>({name:ot.name,path:Gs(ot.path)})).sort((ot,O)=>ot.name.localeCompare(O.name));M(Be)}).catch(Ie=>{if(!F){M([]);const Be=gu(Ie)?Ie.reason:"unknown";_(Be),te(Be==="not-found")}}).finally(()=>{F||H(!1)}),()=>{F=!0}},[be,K,e]);const Pe=o.useMemo(()=>{const F=Se.toLowerCase(),Ie=We||Se.startsWith(".");return E.filter(Be=>Be.name.toLowerCase().startsWith(F)&&(Ie||!Be.name.startsWith(".")))},[Se,E,We]),lt=o.useMemo(()=>xh(D),[D]),pt=o.useMemo(()=>Ka(D),[D]),Ve=o.useMemo(()=>{const F=[],Ie=ws(be);Ha(D)&&lt&&pt&&F.push({type:"parent",value:"browse:up",name:lt,path:pt,alreadyAdded:!!(Ie&&Q.has(Ie))});for(const Be of Pe){const ot=ws(Be.path);F.push({type:"directory",value:`browse:${Be.path}`,name:Be.name,path:Be.path,alreadyAdded:!!(ot&&Q.has(ot))})}return F},[Q,be,lt,Pe,pt,D]);o.useEffect(()=>{Y(0)},[D,Ve.length]);const Me=o.useMemo(()=>_e?Ys(fi(D,_e)):"",[_e,D]),Ne=ws(Me),Fe=!!(Ne&&Q.has(Ne)),ft=o.useMemo(()=>Se?Pe.find(F=>F.name===Se)??null:null,[Se,Pe]),wt=!!(Me&&!Fe&&(se===null||se==="not-found")&&(Ks(D)&&ee||!Ks(D)&&Se.trim().length>0&&ft===null)),rt=!re&&!Te&&!Fe&&se!=="os-permission"&&se!=="invalid-response"&&se!=="unknown"&&!!Me,$=rt&&Ue.trim().length>0,pe=Ve[z]??null,Ce=!!pe,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",W=Fe?"Already added":Ge?re?"Cloning...":"Clone & add":re?"Adding...":wt?"Create & add":"Add folder",J=Ge?$:rt;o.useLayoutEffect(()=>{const F=v.current;F&&(F.scrollLeft=F.scrollWidth)},[D]),o.useLayoutEffect(()=>{!e||N||ur(v.current)},[e,N]),o.useLayoutEffect(()=>{const F=Ve[z];F&&g.current.get(F.value)?.scrollIntoView({block:"nearest"})},[z,Ve]);const he=o.useCallback(()=>{s(!1)},[s]),we=o.useCallback((F,Ie)=>{a("chat"),j&&l(!1),c({selectedProjectId:F,directoryOverride:Ie}),he()},[he,j,c,a,l]),Ae=o.useCallback(async F=>{if(!F||re)return;const Ie=ws(F);if(Ie&&Q.has(Ie))return;let Be=F;U(!0);try{const ot=!Ge&&wt&&ws(F)===ws(Me);if(Ge){const ne=Ue.trim();if(!ne){ae.error("Enter a repository URL before cloning.");return}const fe=await Jt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ne,destinationPath:F,gitIdentityId:xe?.id??null})});if(!fe.ok)throw new Error("Failed to clone git repository");Be=(await fe.json()).path||F}else if(ot&&!(await Jt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:be?{directory:be}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const O=i(Be);if(!O){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}we(O.id,O.path)}catch(ot){ae.error("Failed to select directory",{description:ot instanceof Error?ot.message:"Unknown error occurred."})}finally{U(!1)}},[i,Q,be,Ue,Ge,re,we,xe?.id,wt,Me]),He=o.useCallback(F=>{I(Un(F))},[]),ct=o.useCallback(F=>{I(bh(D,F.name))},[D]),yt=o.useCallback(F=>{if(F){if(F.type==="parent"){He(F.path);return}ct(F)}},[He,ct]),qe=o.useCallback(async F=>{const Ie=await m(F);if(!Ie.success)return ae.error("Failed to open directory",{description:Ie.error||"Desktop could not grant file access."}),!1;const Be=_e?yh(F,_e):Un(Gs(F));return He(Be),!0},[He,_e,m]),ht=o.useCallback(async()=>{if(!Te){Re(!0);try{if(io()){const Ie=await ao(Me);if(!Ie.success||!Ie.path){Ie.error&&Ie.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:Ie.error});return}await qe(Ie.path);return}const F=await xu(Me);if(F.status==="cancelled")return;if(F.status!=="picked"){ae.error("Couldn't open a folder picker",{description:F.error});return}await qe(F.path)}catch(F){ae.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Re(!1)}}},[qe,Te,Me]),gt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),Y(Ie=>Math.min(Ve.length-1,Ie+1));return}if(F.key==="ArrowUp"){F.preventDefault(),Y(Ie=>Math.max(0,Ie-1));return}if(F.key==="Enter"){if(F.preventDefault(),vh(F)){Ae(Me);return}Ce&&yt(pe);return}F.key==="Backspace"&&D===""&&(F.preventDefault(),he())},[yt,Ae,he,Ce,pe,D,Ve.length,Me]),Oe=t.jsxs("button",{type:"button",onClick:()=>ke(F=>!F),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[We?t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ze=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(Hs,{ref:v,value:D,onChange:F=>I(Gs(F.target.value)),onKeyDown:gt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Qe,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:re||Te,onMouseDown:F=>F.preventDefault(),onClick:()=>{ht()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),Te?"Opening...":"Browse"]})]})}),xt=Ve.some(F=>F.type==="parent"),At=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Qe,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ge,disabled:re||Te,onClick:()=>Ke(F=>!F),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ge?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Hs,{value:Ue,onChange:F=>De(F.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx($a,{activeProfile:xe,identities:V,onSelect:F=>ge(F.id),isApplying:re,iconOnly:!0})]})]}):null,Fe?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:B("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",je==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:P?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):se&&se!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:se==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[se==="os-permission"&&h?t.jsx(Qe,{size:"xs",onClick:()=>{ht()},disabled:Te,children:"Grant access"}):null,t.jsx(Qe,{variant:"outline",size:"xs",onClick:()=>L(F=>F+1),children:"Try again"})]})]}):Ve.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:Ve.map((F,Ie)=>{const Be=Ie===z,ot=F.type==="directory"&&xt;return t.jsxs("button",{ref:O=>{O?g.current.set(F.value,O):g.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>Y(Ie),onMouseDown:O=>O.preventDefault(),onClick:()=>yt(F),className:B("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Be&&"bg-interactive-selection text-interactive-selection-foreground",!Be&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:B("flex min-w-0 flex-1 items-center gap-2",ot&&"pl-4"),children:[F.type==="parent"?t.jsx(k,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(k,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:F.name})]}),F.alreadyAdded?t.jsx("span",{className:B("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Be?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(k,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(k,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},q)]})}),$t=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ze,At]}),Rt=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(k,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:w}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),jt=t.jsx(Qe,{size:j?"xs":"default",onClick:()=>{Ae(Me)},disabled:!J,className:B(j&&"w-full flex-1"),children:W}),kt=()=>t.jsxs(t.Fragment,{children:[j?null:Rt,t.jsx("div",{className:B("flex w-full flex-row justify-end gap-2 sm:w-auto",j&&"justify-stretch"),children:jt})]});return j?t.jsx(ea,{open:e,onClose:he,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:kt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Oe}),$t]})}):t.jsx(is,{open:e,onOpenChange:s,children:t.jsxs(as,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(bs,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Es,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Oe]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:$t}),t.jsx(Ts,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:kt()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,jx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=ed,c=Le(A=>A.deleteSessions),d=ce(A=>A.showDeletionDialog),u=ce(A=>A.setShowDeletionDialog),{isMobile:f,isTablet:b,hasTouchInput:y}=Ps(),x=f||b||y;o.useEffect(()=>yu(()=>{s(!1)}),[]);const h=o.useCallback(A=>{r({sessions:A.sessions,dateLabel:A.dateLabel})},[]),m=o.useCallback(()=>{r(null),a(!1)},[]),j=o.useCallback(async A=>{if(A.sessions.length===0)return;if(A.sessions.length===1){const M=A.sessions[0];await l(M.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const D=A.sessions.map(M=>M.id),{deletedIds:I,failedIds:E}=await c(D);if(I.length>0){const M=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:A.dateLabel?`Removed all sessions from ${A.dateLabel}.`:void 0;ae.success(I.length===1?"Deleted {count} session":`Deleted ${I.length} sessions`,{description:Cn(M)})}E.length>0&&ae.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Is.onDeleteRequest(A=>{if(!d){j(A);return}h(A)}),[h,d,j]),o.useEffect(()=>Is.onDirectoryRequest(()=>{s(!0)}),[]);const C=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const A=n.sessions[0];if(!await l(A.id)){ae.error("Failed to delete session"),a(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const A=n.sessions.map(M=>M.id),D=await c(A),I=D.deletedIds,E=D.failedIds;if(I.length>0){const M=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(I.length===1?"Deleted {count} session":`Deleted ${I.length} sessions`,{description:Cn(M),action:{label:"OK",onClick:()=>{}}})}if(E.length>0&&(ae.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:Cn("Please try again in a moment.")}),I.length===0)){a(!1);return}}m()}finally{a(!1)}}},[n,l,c,m]),N=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(A=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:A.title||"Untitled Session"})},A.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,g=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(k,{name:"checkbox-blank",className:"size-4"}):t.jsx(k,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Qe,{variant:"ghost",onClick:m,disabled:i,children:"Cancel"}),t.jsx(Qe,{variant:"destructive",onClick:C,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),p=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[x?t.jsx(ea,{open:!!n,onClose:()=>{i||m()},title:p,footer:t.jsx("div",{className:"flex justify-end gap-2",children:g}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[N&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:N}),v]})}):t.jsx(is,{open:!!n,onOpenChange:A=>{if(!A){if(i)return;m()}},children:t.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(bs,{children:[t.jsx(hs,{children:p}),N&&t.jsx(Es,{children:N})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ts,{className:"mt-2 gap-2 pt-1 pb-1",children:g})]})}),t.jsx(Sh,{open:e,onOpenChange:s})]})};function Cx(){const e=o.useRef(!1),s=o.useRef(!1),n=Le(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),i=ce(f=>f.setSettingsDialogOpen),a=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=o.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const b=Le.getState().currentSessionId,y=Xs().getState().selectedSessionId;if(f.sessionId!==b||f.sessionId!==y){const x=Le.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,x)}}if(f.settingsPath){a(ih(f.settingsPath)),i(!0);return}ce.getState().isSettingsDialogOpen&&i(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const f=Le.getState(),b=Xs().getState(),y=ce.getState();return{sessionId:ar({currentSessionId:f.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:f.newSessionDraft}),tab:y.activeMainTab,isSettingsOpen:y.isSettingsDialogOpen,settingsPath:y.settingsPage,diffFile:y.pendingDiffFile}},[]),u=o.useCallback((f={})=>{if(s.current)return;const b=d();Ur(b,f)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Go()))return;const f=Ko();(async()=>(await c(f),Ur({...d(),sessionId:f.sessionId??ar({currentSessionId:Le.getState().currentSessionId,piSelectedSessionId:Xs().getState().selectedSessionId,draft:Le.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const f=()=>{const j=Le.getState(),C=Xs().getState();return ar({currentSessionId:j.currentSessionId,piSelectedSessionId:C.selectedSessionId,draft:j.newSessionDraft})};let b=f(),y=Le.getState().newSessionDraft?.open===!0;const x=()=>{const j=Le.getState(),C=f(),N=j.newSessionDraft?.open===!0;C===b&&N===y||s.current||(b=C,y=N,u({replace:!0}))},h=Le.subscribe(()=>{x()}),m=Xs().subscribe(()=>{x()});return()=>{h(),m()}},[u]),o.useEffect(()=>{let f=ce.getState().activeMainTab,b=ce.getState().isSettingsDialogOpen,y=ce.getState().settingsPage,x=ce.getState().pendingDiffFile;return ce.subscribe(m=>{if(s.current)return;const j=m.activeMainTab!==f,C=m.isSettingsDialogOpen!==b,N=m.settingsPage!==y,v=m.pendingDiffFile!==x&&m.activeMainTab==="diff";f=m.activeMainTab,b=m.isSettingsDialogOpen,y=m.settingsPage,x=m.pendingDiffFile,(j||C||N||v)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const b=Ko();if(Go())c(b);else{const y=ce.getState();y.isSettingsDialogOpen&&i(!1),y.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,i])}function jh(e=!0){const s=Fn(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!e)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=b=>{const y=Math.round(b*1e3);return Math.max(a,Math.min(l,y))},f=b=>{c||(d=window.setTimeout(async()=>{const y=await n.current(),x=typeof y=="number"&&Number.isFinite(y)?u(y):i;f(x)},b))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function kx(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return jh(e),null}const hi=12,Ch=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],kh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Ch,onComplete:a})=>{const l=Ye.useRef(!1);Ye.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ye.useMemo(()=>Array.from({length:hi},(d,u)=>{const f=Math.PI*2*u/hi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:B("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((f,b)=>{const y=f.x*d.radius,x=f.y*d.radius,h={"--translate-x":`${y}px`,"--translate-y":`${x}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:h},`${d.id}-${b}-${s}`)})},`${d.id}-${s}`)})}):null},Nh=({durationMs:e=3400}={})=>{const[s,n]=Ye.useState({isActive:!1,cycle:0}),r=Ye.useRef(null),i=Ye.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ye.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Ye.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return Ye.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Wa=o.createContext(void 0),Nx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Nh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Wa.Provider,{value:a,children:[e,t.jsx(kh,{isActive:s,burstKey:n})]})},Ah={triggerFireworks:()=>{},dismissFireworks:()=>{}},Ax=()=>o.useContext(Wa)??Ah,pi=380,mi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Gn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),kn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(k,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ih=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),f=o.useRef(null),[b,y]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const h=()=>{const C=n.current?.getBoundingClientRect(),N=f.current?.getBoundingClientRect();if(!C||!N){y(null);return}const v=C.left-N.left,g=Math.min(Math.max(v,8),Math.max(8,N.width-pi-8));y(g)};h();const m=f.current;if(typeof ResizeObserver>"u"||!m)return;const j=new ResizeObserver(h);return j.observe(m),()=>j.disconnect()},[n,u,e,a]);const x=u&&b!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const h=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(h)},[e,a]),o.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),o.useEffect(()=>{if(!e)return;const h=m=>{const j=m.target;if(!(j instanceof Node)){s();return}i.current?.contains(j)||n.current?.contains(j)||s()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("wheel",h,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("wheel",h,!0)}},[n,s,e]),a?t.jsxs("div",{ref:f,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:B("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",x?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...x?{top:8,left:b??8,width:`min(${pi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(kn,{iconNode:t.jsx(sa,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:B("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(kn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheRead)})}),t.jsx(kn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(kn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
3
3
  @keyframes session-metadata-in {
4
4
  from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
5
  to { opacity: 1; transform: translateY(0) scale(1); }