@pi-chamber/web 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bin/cli.test.js +6 -8
  2. package/bin/lib/cli-tunnel-capabilities.js +0 -2
  3. package/dist/assets/{CommitSection-DPjTv8fA.js → CommitSection-BpbMC0et.js} +1 -1
  4. package/dist/assets/{DiagramEditor-ChOor9l9.js → DiagramEditor-dFTMKHuO.js} +1 -1
  5. package/dist/assets/{DiagramView-3hAT86v_.js → DiagramView-DVw_8Px1.js} +1 -1
  6. package/dist/assets/{DiffView-D1dyOiw2.js → DiffView-CkoY1oAM.js} +1 -1
  7. package/dist/assets/{FilesView-BCzghrc7.js → FilesView-C0hyg2pa.js} +6 -6
  8. package/dist/assets/{GitView-CYF1E1p4.js → GitView-D36hpDsb.js} +4 -4
  9. package/dist/assets/{JsonTreeView-CrJO6LNu.js → JsonTreeView-BF8S-bPN.js} +1 -1
  10. package/dist/assets/{MarkdownRendererImpl-BmKjrkGD.js → MarkdownRendererImpl-BVNChdig.js} +1 -1
  11. package/dist/assets/{PatchDiff-DgvPLx6x.js → PatchDiff-B--OaNB1.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-InnT0JVA.js → PierreDiffViewer-0Qkp9ICt.js} +1 -1
  13. package/dist/assets/{SessionSwitcherDropdown-C0OdvirK.js → SessionSwitcherDropdown-cFWgy1td.js} +101 -102
  14. package/dist/assets/SettingsView-D3ZZyjU3.js +4 -0
  15. package/dist/assets/SettingsWindow-BuJCvYoR.js +1 -0
  16. package/dist/assets/{ToolOutputDialog-gzwcb8nI.js → ToolOutputDialog-Bi9BoEe7.js} +4 -4
  17. package/dist/assets/{ToolPartDiffPreview-C45V5bhy.js → ToolPartDiffPreview-DGX7N4zr.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-uKfnkQWb.js → VirtualizedFileDiff-CxraYoDZ.js} +1 -1
  19. package/dist/assets/{collapsible-Bq8sDiKS.js → collapsible-d4-HChej.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-BPgZ_RSe.js → computeVirtualFileMetrics-BuD14qFL.js} +2 -2
  21. package/dist/assets/{contextFileOpenGuard-CydO7PkI.js → contextFileOpenGuard-DirV-hCs.js} +1 -1
  22. package/dist/assets/{index-BSuNNtBh.js → index-BWmmf5yJ.js} +1 -1
  23. package/dist/assets/{index-CH7o4-_q.js → index-DEYblXCW.js} +7 -7
  24. package/dist/assets/index-DLKBsLKY.css +1 -0
  25. package/dist/assets/{isDiffPlainText-f9b4cKNo.js → isDiffPlainText-LoMmNzmX.js} +1 -1
  26. package/dist/assets/{isFilePlainText-BjESb-gU.js → isFilePlainText-3Hj9i02t.js} +1 -1
  27. package/dist/assets/{main-B508FBXr.js → main-BsszlAdQ.js} +2 -2
  28. package/dist/assets/main-CUvZIN16.js +133 -0
  29. package/dist/assets/{markdownCore-BFmf8a-O.js → markdownCore-sGxk8jrc.js} +2 -2
  30. package/dist/assets/{miniChat-BTlz8IPL.js → miniChat-C6SDQL4G.js} +2 -2
  31. package/dist/assets/{mobile-DBkrRt80.js → mobile-DBW3XDmZ.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-B1_fTdN-.js +1 -0
  33. package/dist/assets/renderMobileApp-CFxZc_1a.js +14 -0
  34. package/dist/assets/{runtimeSurface-Bec4O8FD.js → runtimeSurface-9aJdtQbh.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-CHmIm0Rr.js → useInlineCommentController-Cl--s6vE.js} +2 -2
  36. package/dist/assets/usePanelSlide-D5ffPTGM.js +56 -0
  37. package/dist/assets/{useWindowTitle-CE5N_NeU.js → useWindowTitle-C-AZD713.js} +3 -3
  38. package/dist/assets/{vendor-base-ui-DwfTg5wD.js → vendor-base-ui-DL8r2fgQ.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-q1yHU1R9.js → vendor-codemirror-language-data-HC9JT4I3.js} +2 -2
  40. package/dist/assets/{web-components-CLirSfwt.js → web-components-skJ_VpnT.js} +4 -4
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/lib/package-manager.js +0 -34
  46. package/server/lib/pi/routes.js +32 -2
  47. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  48. package/server/lib/pi/session-daemon/runtime-registry.js +3 -0
  49. package/server/lib/pi/session-daemon/session-daemon.js +150 -10
  50. package/server/lib/pi/session-daemon/session-daemon.test.js +22 -0
  51. package/server/lib/tunnels/DOCUMENTATION.md +6 -7
  52. package/server/lib/tunnels/executable-search.test.js +4 -4
  53. package/server/lib/tunnels/install-help.js +0 -10
  54. package/server/lib/tunnels/install-help.test.js +0 -9
  55. package/server/lib/tunnels/types.js +0 -1
  56. package/dist/assets/SettingsView-JAfC_cBL.js +0 -3
  57. package/dist/assets/SettingsWindow-BBEsjcJE.js +0 -1
  58. package/dist/assets/index-o4Eea60G.css +0 -1
  59. package/dist/assets/main-nG4uFyAy.js +0 -133
  60. package/dist/assets/renderElectronMiniChatApp-DW3fSR5w.js +0 -1
  61. package/dist/assets/renderMobileApp-9qkroKty.js +0 -14
  62. package/dist/assets/usePanelSlide-DCX8qQ4K.js +0 -56
  63. package/server/lib/ngrok-tunnel.js +0 -343
  64. package/server/lib/ngrok-tunnel.test.js +0 -50
  65. package/server/lib/tunnels/providers/ngrok.js +0 -32
@@ -1,56 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BSuNNtBh.js","assets/SessionSwitcherDropdown-C0OdvirK.js","assets/index-CH7o4-_q.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-o4Eea60G.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-Bec4O8FD.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-base-ui-DwfTg5wD.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/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-q1yHU1R9.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-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/computeVirtualFileMetrics-BPgZ_RSe.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-BjESb-gU.js","assets/isDiffPlainText-f9b4cKNo.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 Qs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ke,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{bg as ia,bh as Vs,bi as yc,ao as vc,o as aa,D as fs,w as hs,y as vs,I as k,ay as Fs,bj as Wo,f as F,B as Qe,av as gn,T as st,q as nt,s as rt,bk as la,bl as wc,bm as Sc,bn as jc,bo as Cc,h as _e,bp as kc,bq as Yo,br as Nc,bs as Ac,bt as Vo,bu as Ic,bv as Dc,bw as Pc,bx as Tc,by as zr,bz as Ec,t as le,as as Wt,at as Yt,au as Vt,Y as en,bA as Rc,bB as Mc,bC as Fc,bD as Lc,bE as qo,a5 as Lt,bF as Oc,bG as Bc,bH as _c,bI as zc,bJ as Uc,bK as $c,bL as Ur,bM as ca,bN as da,bO as Gc,bP as Kc,bQ as Hc,bR as Wc,bS as Yc,bT as Vc,a$ as $r,r as Js,bU as Bs,bV as qc,b1 as _s,b6 as Qc,b7 as Jc,b8 as Xc,b9 as Zc,ba as vr,bb as an,bW as Qo,az as Ct,b as Ut,aV as Us,bX as ua,x as Is,z as $s,A as Gs,bY as ed,bZ as Hs,b_ as Jo,b$ as Xo,c0 as un,aC as td,c1 as fa,aH as Zo,aF as sd,g as ha,c2 as nd,c3 as pa,c4 as rd,c5 as ma,e as Jn,c6 as od,C as nr,K as ga,c7 as id,c8 as $t,aQ as xa,c as Gr,c9 as ad,ca as ld,cb as rr,cc as Kn,cd as ba,_ as xn,$ as bn,Z as cd,ce as dd,cf as ei,b0 as ya,cg as ud,ch as va,b4 as po,b5 as fn,ci as ti,cj as or,aw as fd,ck as wa,H as hd,cl as mo,cm as pd,cn as md,j as Sa,l as gd,co as xd,cp as bd,k as yd,cq as Kr,n as vd,S as wd,aT as ja,cr as Sd,cs as jd,m as Cd,d as kd,ct as Nd,a as Ad,ax as Id,b3 as Dd,cu as Pd,b2 as Td,cv as Ed,cw as Rd,cx as Md,cy as Fd,af as Ld,cz as si,cA as Od,aR as Bd,cB as _d,cC as zd,cD as En,cE as ni,cF as Ud,cG as ri,cH as oi,cI as $d,aJ as Ca,a3 as Gd,E as Kd,cJ as ka,u as Hd,cK as Wd,cL as Yd,aA as tn,p as Vd,cM as qd,cN as Na,cO as Qd,cP as Jd,cQ as Xd,cR as Zd,cS as eu,cT as tu,cU as su,cV as ii,cW as nu,cX as ru,cY as Aa,cZ as ou,c_ as iu}from"./SessionSwitcherDropdown-C0OdvirK.js";import{M as ai,N as au,O as li,P as lu,i as cu,Q as du,L as uu,r as Xt,u as re,R as yn,b as fu,K as ys,S as hu,T as gs,U as go,o as xo,l as zs,V as yt,W as bo,X as yo,Y as pu,Z as mu,B as gu,_ as xu,$ as bu,a0 as yu,a1 as vu,a2 as as,a3 as Hr,a as ir,a4 as wu,a5 as Su,a6 as ju,a7 as Cu,a8 as Ia,J as Da,C as hn,F as Wr,e as Yr,d as Rn,a9 as ku,aa as Nu,ab as ln,ac as wr,ad as Pa,A as Au,n as Iu,ae as Vr,af as Ls,ag as ci,ah as qr,ai as Ta,aj as Qr,ak as Du,al as Pu,am as Tu,t as Eu,an as Ru}from"./index-CH7o4-_q.js";import{C as Ea,a as Ra,M as Jr,b as Xr,c as Zr,d as Ma,S as Fa,D as Mu,e as Fu,f as Lu,g as Ou,h as Bu,i as _u,j as zu,k as Uu}from"./vendor-base-ui-DwfTg5wD.js";import{c as ws,d as La,p as vo,u as eo,a as $u}from"./vendor-zustand-CnsBKjP5.js";import{u as Gu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as ar,d as vn,P as wo,D as lr,e as cr,f as Oa,b as Ku,a as Hu,T as Wu,M as Yu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as So,v as Ba,u as dr,a as Vu,h as qu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as ur}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as Qu}from"./permissionStore-BRcQ9Jgt.js";const Ju=3;let Xn=0;const _a=[],Xu=()=>Xn<Ju?(Xn+=1,Promise.resolve()):new Promise(e=>{_a.push(e)}),Zu=()=>{const e=_a.shift();if(e){e();return}Xn=Math.max(0,Xn-1)},ef=async e=>{await Xu();try{return await e()}finally{Zu()}},tf="chat";function za(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Vs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Vs.SETTINGS,n),s}return e.tab!==tf&&s.set(Vs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Vs.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=za(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(Vs.SESSION)&&s.set(Vs.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 to(e,s={}){if(!(typeof window>"u")&&!ia()&&!(!s.force&&nf(e)))try{const n=za(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"],Ua={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let di=null;const $a=()=>(di??=Promise.all([Qs(()=>import("./index-BSuNNtBh.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])),Qs(()=>import("./workerFactory-tw7cIdmV.js"),[]),Qs(()=>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})),di),wn={},ui=new Set,so=new Set;let Hn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of so)e()},Ga=(e,s)=>{s.setRenderOptions({theme:Hn,lineDiffType:Ua[e].lineDiffType})},no=e=>{typeof window>"u"||ui.has(e)||(ui.add(e),$a().then(s=>{if(wn[e])return;const n=Ua[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(),wn[e]=r,Ga(e,r),of()}))},af=e=>(so.add(e),()=>so.delete(e)),lf=e=>{if(!(Hn.light===e.light&&Hn.dark===e.dark)){Hn=e;for(const s of Object.keys(wn)){const n=wn[s];n&&Ga(s,n)}}},sx=({children:e})=>{const s=yc(),n=ai(!1),r=ai(!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 Ke.useEffect(()=>{let d=!1;return $a().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ke.useEffect(()=>{if(typeof window>"u")return;const d=()=>{no("unified"),no("split")};if(typeof window.requestIdleCallback=="function"){const b=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(b)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},nx=(e="unified")=>{const s=Ke.useSyncExternalStore(af,()=>wn[e],()=>{});return Ke.useEffect(()=>{no(e)},[e]),s},fi="pichamber.update-install-id";function cf(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const e=window.localStorage.getItem(fi)?.trim();if(e)return e;const s=crypto.randomUUID();return window.localStorage.setItem(fi,s),s}catch{return}}function df(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=vc();return e}catch{return"unknown"}}function uf(){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 ff(){const e=fu();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 hf(e){const s=re.getState().reportUsage,n=new URLSearchParams({reportUsage:s?"true":"false"});if(n.set("deviceClass",df()),n.set("arch",uf()),n.set("platform",ff()),s&&(e==="desktop"||e==="mobile")){const r=cf();r&&n.set("installId",r)}return e==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",yn()?"local":"remote"),n):e==="mobile"?(n.set("appType","mobile-capacitor"),n.set("instanceMode","remote"),n):(n.set("appType","web"),n.set("instanceMode","unknown"),n)}async function Sr(e,s){try{const n=hf(e);s&&n.set("currentVersion",s);const r=await Xt(`/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 pf(){return cu()?"mobile":du()?"desktop":uu()?"web":null}const hi={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Wn=ws()((e,s)=>({...hi,checkForUpdates:async()=>{const n=pf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.2.2",[l,c]=await Promise.allSettled([li(),Sr("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 Sr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await Sr("mobile","0.2.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 li();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 lu(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 au())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(hi)}})),pi="https://github.com/RyderAsKing/PiChamber/releases";function mf(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 gf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function mi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function xf(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 bf(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 gi=2e3,yf=600*1e3;async function vf(){try{const e=await Xt("/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 wf(){try{return(await Xt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Sf(e,s=Math.ceil(yf/gi),n=gi){for(let r=0;r<s;r++){try{const i=await Xt("/api/pi/update-check?reportUsage=false",{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 wf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ka=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[b,h]=Ke.useState(!1),[x,y]=Ke.useState("idle"),[f,g]=Ke.useState(null),w=n?.version?n.releaseUrl||`${pi}/tag/v${n.version}`:pi,v=n?.downloadUrl||w,D=a?.total?Math.round(a.downloaded/a.total*100):0,S=u==="web",m=u==="mobile",p=n?.updateCommand||"pichamber update";Ke.useEffect(()=>{e||(y("idle"),g(null))},[e]);const N=async()=>{(await gn(p)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},T=Ke.useCallback(async L=>{await aa(L)},[]),A=Ke.useCallback(async()=>{y("updating"),g(null);const L=await vf();if(!L.success){y("error"),g(L.error||"Update failed");return}L.autoRestart&&(y("restarting"),await new Promise(X=>setTimeout(X,2e3))),y("reconnecting"),await Sf(n?.currentVersion)?window.location.reload():(y("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),P=Ke.useCallback(()=>{T(v)},[T,v]),E=x!=="idle"&&x!=="error",R=Ke.useMemo(()=>{if(!n?.body)return null;const L=n.body.trim();if(!L)return null;const Y=bf(L);return Y.length===0?{kind:"raw",title:"What's new",content:mi(L)}:{kind:"sections",title:"What's new",sections:[...Y].sort((oe,$)=>xf(oe.version,$.version)).map(oe=>({version:oe.version,dateLabel:mf(oe.date),content:mi(gf(oe.raw)||L)}))}},[n?.body]);return t.jsx(fs,{open:e,onOpenChange:E?void 0:s,children:t.jsxs(hs,{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(vs,{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:x==="restarting"||x==="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:[S&&E&&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:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="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."})]}),R&&!E&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Fs,{className:"max-h-[400px] p-0",fillContainer:!1,children:R.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:L=>{const X=L.target.closest("a");X&&X.href&&(L.preventDefault(),L.stopPropagation(),T(X.href))},children:t.jsx(Wo,{content:R.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:R.sections.map(L=>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",L.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:L.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:Y=>{const oe=Y.target.closest("a");oe&&oe.href&&(Y.preventDefault(),Y.stopPropagation(),T(oe.href))},children:t.jsx(Wo,{content:L.content,disableLinkSafety:!0,enableFileReferences:!1})})]},L.version))})})}),S&&x==="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:N,className:F("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",b&&"text-[var(--status-success)]"),title:b?"Copied!":"Copy command",children:b?t.jsx(k,{name:"check",className:"h-4 w-4"}):t.jsx(k,{name:"clipboard",className:"h-4 w-4"})})]})]}),!S&&!m&&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:[D,"%"]})]}),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:`${D}%`}})})]}),(l||f)&&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||f})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:w,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:[!S&&!m&&!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"]}),!S&&!m&&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..."]}),!S&&!m&&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"]}),m&&t.jsxs(Qe,{onClick:P,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),S&&!E&&t.jsxs("button",{onClick:A,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"]}),S&&E&&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..."]})]})]})]})})},jf=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:F("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:F("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),Sn=({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(st,{open:r,onOpenChange:i,children:[t.jsx(nt,{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:F("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(rt,{sideOffset:8,className:F("max-w-sm",n),children:e})]})},rx="w-full min-w-40 max-w-48",Cf="settings",kf="w-full min-w-40 max-w-48",ox="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nf="w-full max-w-[24rem]",ix="min-w-0 flex-1",ax="flex w-full min-w-0 items-center gap-2",lx="typography-meta shrink-0 text-muted-foreground tabular-nums",Ha="space-y-3.5",Af="space-y-1.5",cx="typography-settings-page-title text-muted-foreground",If="typography-settings-section-title text-foreground",dx="typography-settings-section-title text-foreground",Wa="typography-settings-group-title text-foreground",jo="typography-settings-field-label text-foreground",Df="typography-settings-description text-muted-foreground",jn="typography-meta text-muted-foreground",ux="typography-meta font-medium text-foreground",fx="typography-settings-section-title text-foreground",Pf=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const b=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:F("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[b?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:If,children:e}):e,n,r!=null?t.jsx(Sn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Df,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:F(d),children:a})]})},hx=({children:e,className:s})=>t.jsx("div",{className:F("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Tf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:F(Wa,s),children:e}),px=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:F("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(Tf,{children:e}),n!=null?t.jsx(Sn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:jn,children:s}):null]}):null,t.jsx("div",{className:F(a),children:r})]}),qs=({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:jn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:F("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:jo,children:e}),n!=null?t.jsx(Sn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:F("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},mx=({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:F("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:jo,children:e}),n!=null?t.jsx(Sn,{children:n}):null]}),s!=null?t.jsx("p",{className:F(jn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:F("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),gx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:F("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 b=()=>{i||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:F("group flex cursor-pointer gap-2 py-0.5",h?"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:b,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),b())},children:[t.jsx(la,{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:jo,children:n}),d,u!=null?t.jsx(Sn,{children:u}):null]}),h?t.jsx("span",{className:jn,children:r}):null]})]})},xx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:F("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(jf,{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:F("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:jn,children:r}):null]})]}),bx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:F(Af,n),children:s});function yx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:F("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 Rf 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 Mf(e){return t.jsx(Rf,{...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 vx=({active:e=!0,readOnly:s=!1})=>{const n=_e(r=>r.currentSessionId);return t.jsx(Mf,{sessionId:n||void 0,children:t.jsx(kc,{active:e,readOnly:s},n??"no-session")})};function Ff({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 Co=Ke.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:b,endSlot:h,...x},y)=>{const f=Ke.useRef(null),g=Ke.useRef(null),[w,v]=Ke.useState(null),D=c??w,S=Ke.useCallback(p=>{const N=f.current;if(!N)return;g.current={startY:p.clientY,startHeight:N.getBoundingClientRect().height};const T=p.currentTarget;T.setPointerCapture(p.pointerId);const A=E=>{const R=g.current;if(!R)return;const L=R.startHeight+(E.clientY-R.startY),Y=Math.max(82,L);d?d(Y):v(Y)},P=()=>{g.current=null,T.removeEventListener("pointermove",A),T.removeEventListener("pointerup",P),T.removeEventListener("pointercancel",P)};T.addEventListener("pointermove",A),T.addEventListener("pointerup",P),T.addEventListener("pointercancel",P),p.preventDefault()},[d]),m=Ke.useCallback(p=>{if(p.target.closest('textarea, button, [role="separator"]'))return;const T=f.current?.querySelector("textarea");T&&document.activeElement!==T&&(p.preventDefault(),T.focus())},[]);return b?t.jsx(Fs,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:F("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,...x}):t.jsx("div",{ref:f,onPointerDown:m,style:D!==null?{height:`${D}px`}:void 0,className:F("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:y,className:F("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,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(Ff,{onResizeStart:S,ariaLabel:"Resize textarea"})]})]})})});Co.displayName="Textarea";const xi=(e,s)=>s.updatedAtMs-e.updatedAtMs,Zn=ws((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(),Vo()]),i={};for(const a of r.sort(xi))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 Vo(),r={};for(const i of n.sort(xi))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=Tc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await Yo(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 Yo(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})})),Ya=[{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"}],pn=Object.fromEntries(Ya.map(e=>[e.key,e.Icon])),ro="pichamber:project-actions-updated",Va=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},xs=(e,s)=>`${Va(e)}::${s}`,Lf=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},bi=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Of=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=bi(s.localPort),r=bi(s.remotePort);if(!n||!r)return null;const i=Lf(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}`}},qa=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Of(n,r);i&&s.push(i)}return s},Bf=(e,s)=>{const n=(e||"").trim();return n&&qa(s).find(a=>a.id===n)?.url||null},_f=Nf,Qa=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Pf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),oo=e=>e.name.trim().length>0&&e.command.trim().length>0,zf=e=>e.name.trim().length===0&&e.command.trim().length===0,Uf=e=>!oo(e)&&!zf(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!oo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(oo)},Gf=450,Kf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Hf=()=>({id:Kf(),name:"",command:"",icon:"play"}),Wf=({projectRef:e})=>{const s=o.useMemo(()=>ys(),[]),n=Zn(p=>p.instances),r=Zn(p=>p.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[b,h]=o.useState(new Set),x=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let p=!1;return c(!0),(async()=>{try{const N=await zr(e);if(p)return;a(N.actions),u(JSON.stringify({actions:N.actions})),h(new Set(N.actions.map(T=>T.id)))}catch{if(p)return;a([]),u(JSON.stringify({actions:[]})),h(new Set)}finally{p||c(!1)}})(),()=>{p=!0}},[e]);const y=o.useMemo(()=>s?qa(n):[],[n,s]),f=o.useMemo(()=>$f(i,b),[i,b]),g=o.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),w=d!==null&&f.canPersist&&g!==d,v=o.useCallback(async p=>await Ec(e,{actions:p,primaryActionId:null})?(u(JSON.stringify({actions:p})),h(new Set(p.map(T=>T.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ro,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!w||l||x.current)return;const p=window.setTimeout(()=>{x.current||(x.current=!0,(async()=>{try{await v(f.actions)}finally{x.current=!1}})())},Gf);return()=>{window.clearTimeout(p)}},[w,l,v,f.actions]);const D=o.useCallback(()=>{const p=Hf();a(N=>[...N,p])},[]),S=o.useCallback(p=>{a(N=>N.filter(T=>T.id!==p))},[]),m=o.useCallback((p,N)=>{a(T=>T.map(A=>A.id===p?N(A):A))},[]);return t.jsx(Qa,{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:D,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:F("space-y-6",_f),children:i.map((p,N)=>{const T=p.icon||"play",A=pn[T]||"play",P=p.name.trim()||`Action ${N+1}`,E=Uf(p);return t.jsxs("div",{className:Ha,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Wa,children:P}),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:()=>S(p.id),"aria-label":`Delete ${P}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(qs,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Wt,{children:[t.jsx(Yt,{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:A,className:"h-4 w-4"})})}),t.jsx(Vt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ya.map(R=>{const L=R.Icon,Y=(p.icon||"play")===R.key;return t.jsx("button",{type:"button",onClick:()=>m(p.id,X=>({...X,icon:R.key})),className:F("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",Y&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${R.label}`,children:t.jsx(k,{name:L,className:"h-4 w-4"})},R.key)})})})]}),t.jsx(en,{value:p.name,onChange:R=>m(p.id,L=>({...L,name:R.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(qs,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(Co,{value:p.command,onChange:R=>m(p.id,L=>({...L,command:R.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),E?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:R=>m(p.id,L=>({...L,...R?{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 ${P}`}),p.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(qs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(en,{value:p.openUrl||"",onChange:R=>m(p.id,L=>({...L,openUrl:R.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(qs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:y.length>0?t.jsxs(Rc,{value:p.desktopOpenSshForward&&y.some(R=>R.id===p.desktopOpenSshForward)?p.desktopOpenSshForward:"__none__",onValueChange:R=>{m(p.id,L=>({...L,...R==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:R}}))},children:[t.jsx(Mc,{size:Cf,className:"w-full",children:t.jsx(Fc,{placeholder:"Use output/manual URL"})}),t.jsxs(Lc,{children:[t.jsx(qo,{value:"__none__",children:"Use output/manual URL"}),y.map(R=>t.jsx(qo,{value:R.id,children:R.label},R.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},p.id)})})})},Yf={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)"},Vf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=Lt(E=>E.providers),d=Lt(E=>E.modelsMetadata),u=re(E=>E.hiddenModels),b=re(E=>E.providerOrder),h=re(E=>E.setProviderOrder),x=re(E=>E.isFavoriteModel),y=re(E=>E.toggleFavoriteModel),f=re(E=>E.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:w}=Oc(),[v,D]=o.useState(!1),[S,m]=o.useState("");o.useEffect(()=>{v||m("")},[v]);const p=e?c.find(E=>E.id===e.providerId):void 0,N=e&&p?(Array.isArray(p.models)?p.models:[]).find(E=>E.id===e.modelId):void 0,T=e?Bc(N,e.modelId):s,A=o.useMemo(()=>e?u.filter(E=>!(E.providerID===e.providerId&&E.modelID===e.modelId)):u,[u,e]),P=o.useCallback(E=>{l({providerId:E.providerID,modelId:E.modelID}),D(!1)},[l]);return t.jsxs(Wt,{modal:!1,open:v,onOpenChange:E=>{r||D(E)},children:[t.jsx(Yt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:F(zc({size:"default"}),kf,"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:F("truncate",e?"text-foreground":"text-muted-foreground"),children:T})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Vt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Uc,{providers:c,favoriteModels:g,recentModels:w,modelsMetadata:d,searchQuery:S,onSearchQueryChange:m,onSelect:P,labels:{...Yf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:A,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),D(!1)},disabled:r,autoFocus:!0,onEscape:()=>D(!1),isFavorite:E=>x(E.providerID,E.modelID),onToggleFavorite:E=>y(E.providerID,E.modelID),onReorderFavorite:(E,R)=>f(E.providerID,E.modelID,R.providerID,R.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:b,onReorderProvider:h,reorderProviderTitle:"Drag to reorder provider"})})]})},jr="w-full max-w-none",qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=Lt(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Qa,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ha,children:[t.jsx(qs,{label:"Name",settingsItem:"projects.name",controlClassName:jr,children:t.jsx(en,{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(qs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:jr,children:t.jsx(Vf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:jr,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(()=>$c(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,b)=>{i(u&&b?`${u}/${b}`: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}},Jf=450,Xf=(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{le.error("Failed to save project settings")}}finally{l.current=!1}})())},Jf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Zf=({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 Xf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(qf,{form:n}),t.jsx(Wf,{projectRef:r})]})};function eh({...e}){return t.jsx(Ea,{...e})}function th({...e}){return t.jsx(Ra,{...e})}function sh({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(Jr,{children:t.jsx(Xr,{className:F("app-region-no-drag z-50",s),children:t.jsx(Zr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:F(Ur,e),...i,children:n})})})}function yi({className:e,...s}){return t.jsx(Ma,{className:F(ca,e),...s})}function nh({className:e,...s}){return t.jsx(Fa,{className:F(da,e),...s})}const Ms=ws()(La(vo((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=xo()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await Xt("/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 go({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 gs("saving"),await Hc(r),gs("saved"),await s().loadProfiles(),!0}catch(r){return gs("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 gs("saving"),await Kc(n,a),gs("saved"),await s().loadProfiles(),!0}catch(i){return gs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return gs("saving"),await Gc(n),gs("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return gs("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:hu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Ms);const rh=[{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:"content",kind:"split",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"content",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"content",kind:"split",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:"Magic Prompts",group:"content",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request"]},{slug:"snippets",title:"Snippets",group:"content",kind:"split",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"]},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],oh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ih(e){const s=e.trim().toLowerCase();return rh.find(n=>n.slug===s)??null}function ah(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=oh[s];if(n)return n;const r=ih(s);return r?r.slug:"home"}function wx(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 Mn=100;function Sx(){const e=re(A=>A.isArchivePageOpen),s=re(A=>A.setArchivePageOpen),n=re(A=>A.setActiveMainTab),r=_e(A=>A.setCurrentSession),i=_e(A=>A.unarchiveSession),a=zs(A=>A.homeDirectory),l=$r({archived:!0}),[c,d]=o.useState(""),[u,b]=o.useState(null),[h,x]=o.useState(Mn),y=c.trim().toLowerCase(),f=o.useMemo(()=>e?[...l].sort((A,P)=>(P.time?.archived??0)-(A.time?.archived??0)):[],[l,e]),g=o.useMemo(()=>{const A=new Map;for(const P of f){const E=yt(Js(P))??"",R=A.get(E);if(R){R.sessions.push(P);continue}A.set(E,{directory:E,label:E?Bs(E,a)||E:"other projects",sessions:[P]})}return[...A.values()].sort((P,E)=>E.sessions.length-P.sessions.length)},[a,f]),w=o.useMemo(()=>y?f.filter(A=>(A.title??"").toLowerCase().includes(y)):u===null?f:g.find(A=>A.directory===u)?.sessions??[],[g,y,u,f]),v=w.slice(0,h),D=w.length-v.length,S=l.length,m=o.useCallback(A=>{b(A),x(Mn)},[]),p=o.useCallback(A=>{const P=yt(Js(A));r(A.id,P??void 0),n("chat"),s(!1)},[n,r,s]),N=o.useCallback(A=>{i(A.id).then(P=>{P?le.success("Session restored"):le.error("Failed to restore session")})},[i]);if(!e)return null;const T=(A,P,E,R,L,Y,X)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:L,title:Y,className:F("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",X?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",R?"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:P}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),X?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>_s.requestDelete({sessions:X,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 ${P}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},A);return t.jsx(Mu,{open:e,onOpenChange:s,children:t.jsxs(Fu,{children:[t.jsx(Lu,{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(Ou,{className:"pointer-events-auto 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.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-border/70 bg-sidebar px-4",children:[t.jsxs(Bu,{className:"flex items-center gap-2 typography-ui-label font-medium text-foreground",children:[t.jsx(k,{name:"archive",className:"size-4 text-muted-foreground"}),"Archived sessions"]}),t.jsx("button",{type:"button",onClick:()=>s(!1),className:"inline-flex size-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Close archived sessions",children:t.jsx(k,{name:"close",className:"size-4"})})]}),t.jsx(_u,{className:"sr-only",children:"Browse and restore archived sessions."}),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:[T("__all__","All directories",S,u===null,()=>m(null)),g.map(A=>T(A.directory||"__none__",A.label,A.sessions.length,u===A.directory,()=>m(A.directory),A.directory||void 0,A.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 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:A=>{d(A.target.value),x(Mn)},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:w.length===1?`${w.length} archived session`:`${w.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:[v.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):v.map(A=>{const P=yt(Js(A))??"",E=P?Bs(P,a)||P: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(A),role:"button",tabIndex:0,onKeyDown:R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),p(A))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:A.title||"Untitled Session"}),y&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:P,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:qc(A.time?.archived??A.time?.updated??A.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),N(A)},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 ${A.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:R=>{R.stopPropagation(),_s.requestDelete({sessions:[A],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 ${A.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},A.id)}),D>0?t.jsx("button",{type:"button",onClick:()=>x(A=>A+Mn),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 lh=()=>{const[e,s]=Ke.useState(!1),[n,r]=Ke.useState(!1);Ke.useEffect(()=>{s(ys()),r(bo())},[]);const i=Ke.useCallback(async c=>e?await yo(c):{success:!0,path:c},[e]),a=Ke.useCallback(async c=>e?await pu():{success:!0},[e]),l=Ke.useCallback(async c=>e?await mu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},ch=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),dh=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[b,h]=o.useState(""),[x,y]=o.useState(!1),[f,g]=o.useState(!1),[w,v]=o.useState(""),[D,S]=o.useState(!1),m=o.useRef(null),p=o.useCallback($=>{$.stopPropagation()},[]),N=l.length>1,T=o.useMemo(()=>ch(w),[w]),A=o.useMemo(()=>{const $=b.toLowerCase();return $?s.filter(H=>H.toLowerCase().includes($)):s},[b,s]),P=o.useMemo(()=>{const $=b.toLowerCase();return $?n.filter(H=>H.toLowerCase().includes($)):n},[b,n]),E=$=>{if($===e){u(!1);return}i($),u(!1),h("")},R=()=>{y(!0),setTimeout(()=>m.current?.focus(),50)},L=async()=>{if(!(!T||D)){if(N){g(!0);return}S(!0);try{await a(T,l[0]),v(""),y(!1),u(!1)}finally{S(!1)}}},Y=async $=>{if(!(!T||D)){S(!0);try{await a(T,$),v(""),y(!1),g(!1),u(!1)}finally{S(!1)}}},X=()=>{g(!1)},oe=()=>{v(""),y(!1),g(!1)};return o.useEffect(()=>{d||(h(""),y(!1),g(!1),v(""))},[d]),t.jsxs(Wt,{open:d,onOpenChange:u,children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Yt,{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(rt,{sideOffset:8,children:"Current branch"})]}),t.jsx(Vt,{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:b,onValueChange:h,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(vr,{children:f?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:X,disabled:D,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:T})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map($=>t.jsxs("button",{type:"button",onClick:()=>Y($),disabled:D,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:[D?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))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:m,placeholder:"New branch name",value:w,onChange:$=>v($.target.value),onClick:$=>$.stopPropagation(),onKeyDown:$=>{p($),$.key==="Enter"?($.preventDefault(),L()):$.key==="Escape"&&($.preventDefault(),oe())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:L,disabled:!T||D,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:D?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:oe,disabled:D,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(an,{onSelect:R,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Qo,{}),t.jsxs(vr,{heading:"Local branches",children:[A.map($=>t.jsxs(an,{onSelect:()=>E($),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-${$}`)),A.length===0&&t.jsx(an,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Qo,{}),t.jsxs(vr,{heading:"Remote branches",children:[P.map($=>t.jsx(an,{onSelect:()=>E($),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:$})},`remote-${$}`)),P.length===0&&t.jsx(an,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},uh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),fh=({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),b=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const f=uh(a);if(f===e){i(!1);return}d(!0);try{await s(e,f),i(!1),l("")}finally{d(!1)}},x=()=>{i(!1),l("")},y=f=>{f.key==="Enter"?(f.preventDefault(),h()):f.key==="Escape"&&(f.preventDefault(),x())};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:f=>{f.preventDefault(),h()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:f=>l(f.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:y,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:x,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:b,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},hh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:b=!1})=>{const h=o.useRef(!1),x=!!l,y=s.find(p=>p.name===u)??s[0],f=d>0&&b,g=a||e!==null||x||!y||f,w=a||e!==null||x||s.length===0,v=c>0||d>0,D=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),S=f?"Commit or stash your changes before syncing":y?v?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",m=()=>{y&&r(y)};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(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:f?0:void 0,children:t.jsxs("button",{type:"button",onClick:m,disabled:g,className:F("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:D})]})})}),t.jsx(rt,{sideOffset:8,children:S})]}),t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",className:F("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:w,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Vt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(p=>t.jsx(Ct,{onSelect:N=>{if(h.current){N.preventDefault(),h.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||x,onPointerDown:N=>{h.current=!0,N.preventDefault(),N.stopPropagation()},onClick:N=>{h.current=!0,N.preventDefault(),N.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))})]})]})},ph={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},mh={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 Ja(e){return e&&mh[e]||"var(--primary)"}const vi=({icon:e,className:s,colorToken:n})=>{const r=ph[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:Ja(n)}})},Xa=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Wt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Yt,{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:Ja(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(vi,{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(rt,{sideOffset:8,children:"Git identity"})]}),t.jsx(Vt,{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(Ct,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(vi,{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)})})]})},gh=({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(st,{delayDuration:n,children:[t.jsx(nt,{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(rt,{sideOffset:8,children:a})]})},jx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:b,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:y,availableIdentities:f,onSelectIdentity:g,isApplyingIdentity:w,isWorktreeMode:v,onOpenHistory:D,onOpenGraph:S,onOpenStashes:m,onOpenUpdateBranch:p,onOpenReintegrateCommits:N,pullRequest:T,prChecks:A,onOpenPullRequest:P})=>{if(!e)return null;const E=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:D||S||m||p?t.jsxs(Wt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Yt,{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(rt,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Vt,{align:"end",children:[D?t.jsxs(Ct,{onSelect:D,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,S?t.jsxs(Ct,{onSelect:S,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,m?t.jsxs(Ct,{onSelect:m,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,p?t.jsxs(Ct,{onSelect:p,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,N?t.jsxs(Ct,{onSelect:N,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),R=A?A.state==="success"?"var(--status-success)":A.state==="failure"?"var(--status-error)":"var(--status-warning)":null,L=T?T.state==="merged"?"merged":T.state==="closed"?"closed":T.draft?"draft":A?.state==="failure"||T.mergeable===!1||T.mergeableState==="blocked"||T.mergeableState==="dirty"?"blocked":"open":null,Y=T&&P?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",onClick:P,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-${L})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${T.number}`}),R?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:R}}):null]})}),t.jsx(rt,{sideOffset:8,children:"Open pull request"})]}):null,X=t.jsx(hh,{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}),oe=e.upstreamComparison?t.jsx(gh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,$=t.jsx(Xa,{activeProfile:y,identities:f,onSelect:g,isApplying:w,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:v?t.jsx(fh,{currentBranch:e.current,onRename:x}):t.jsx(dh,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:b,onCreate:h,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:[Y?t.jsx("div",{className:"shrink-0",children:Y}):null,t.jsx("div",{className:"min-w-0 flex-1"}),oe?t.jsx("div",{className:"min-w-0 shrink",children:oe}):null,E,t.jsx("div",{className:"shrink-0",children:X})]})]})},xh=e=>e==="/",Xs=e=>e.replace(/\\/g,"/"),sn=e=>{if(!e||xh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Zs=e=>e.endsWith("/"),er=e=>{const s=e.trim();return!s||Zs(s)?s:`${s}/`},ko=e=>e.lastIndexOf("/"),Za=e=>{if(Zs(e))return e;const s=ko(e);return s<0?e:e.slice(0,s+1)},el=e=>{const s=ko(e);return e.slice(s+1)},tl=e=>{const s=sn(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=ko(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},sl=e=>Zs(e)&&tl(e)!==null,bh=e=>{if(!sl(e))return null;const s=sn(e.trim());return el(s)||s},yh=(e,s)=>`${Za(e)}${s}/`,Ts=e=>{if(!e)return null;const s=sn(Xs(e.trim()));return s?s.toLowerCase():null},wi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},vh=(e,s)=>{const n=sn(Xs(e.trim())),r=sn(Xs(s.trim()));if(!n)return"";if(!r)return er(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:er(n)},wh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Cr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Sh=async()=>yu(),jh=({open:e,onOpenChange:s})=>{const n=zs(M=>M.homeDirectory),r=Ut(M=>M.projects),i=Ut(M=>M.addProject),a=re(M=>M.setActiveMainTab),l=re(M=>M.setSessionSwitcherOpen),c=_e(M=>M.openNewSessionDraft),d=Ms(M=>M.profiles),u=Ms(M=>M.globalIdentity),b=Ms(M=>M.defaultGitIdentityId),h=Ms(M=>M.loadProfiles),x=Ms(M=>M.loadGlobalIdentity),y=Ms(M=>M.loadDefaultGitIdentityId),{canRequestAccess:f,startAccessing:g}=lh(),{isMobile:w}=Us(),v=o.useRef(null),D=o.useRef(new Map),[S,m]=o.useState(""),[p,N]=o.useState("~/"),[T,A]=o.useState([]),[P,E]=o.useState(!1),[R,L]=o.useState(!1),[Y,X]=o.useState(null),[oe,$]=o.useState(0),[H,B]=o.useState(0),[O,J]=o.useState(!1),[de,G]=o.useState(!1),[Ce,Me]=o.useState(!1),[He,ze]=o.useState(""),[Be,Pe]=o.useState(null),[te,xe]=o.useState(!1),[Ge,Ne]=o.useState("right"),ye=o.useRef("~/"),Ae=S||n,ot=o.useMemo(()=>new Set(r.map(M=>Ts(M.path)).filter(M=>!!M)),[r]);o.useEffect(()=>{if(!e)return;N("~/"),A([]),B(0),J(!1),G(!1),Me(!1),ze(""),Pe(null),xe(!1),ye.current="~/",Ne("right"),requestAnimationFrame(()=>Cr(v.current));let M=!1;return(async()=>{const Fe=await Sh();M||(m(Fe||n||""),requestAnimationFrame(()=>Cr(v.current)))})(),()=>{M=!0}},[n,e]),o.useEffect(()=>{e&&(h(),x(),y())},[y,h,x,e]);const We=o.useMemo(()=>{const M=new Map;u&&M.set(u.id,u);for(const De of d)M.set(De.id,De);return Array.from(M.values())},[d,u]);o.useEffect(()=>{if(!e||!Ce||Be!==null)return;const M=typeof b=="string"?b.trim():"";if(M&&We.some(Fe=>Fe.id===M)){Pe(M);return}const De=We.find(Fe=>Fe.authType==="ssh"||Fe.sshKey);De&&Pe(De.id)},[We,b,Ce,e,Be]);const Q=o.useMemo(()=>We.find(M=>M.id===Be)??null,[We,Be]),V=o.useMemo(()=>Za(p),[p]),pe=o.useMemo(()=>Zs(p)?"":el(p),[p]),q=o.useMemo(()=>Ae?wi(V,Ae):"",[V,Ae]);o.useEffect(()=>{const M=ye.current;M!==V&&(Ne(V.length>=M.length?"right":"left"),ye.current=V)},[V]),o.useEffect(()=>{if(!e||!q){A([]),X(null);return}let M=!1;return E(!0),L(!1),X(null),gu(q).then(De=>{if(M)return;L(!1),X(null);const Fe=De.filter(Je=>Je.isDirectory).map(Je=>({name:Je.name,path:Xs(Je.path)})).sort((Je,dt)=>Je.name.localeCompare(dt.name));A(Fe)}).catch(De=>{if(!M){A([]);const Fe=xu(De)?De.reason:"unknown";X(Fe),L(Fe==="not-found")}}).finally(()=>{M||E(!1)}),()=>{M=!0}},[q,oe,e]);const ve=o.useMemo(()=>{const M=pe.toLowerCase(),De=te||pe.startsWith(".");return T.filter(Fe=>Fe.name.toLowerCase().startsWith(M)&&(De||!Fe.name.startsWith(".")))},[pe,T,te]),we=o.useMemo(()=>bh(p),[p]),Re=o.useMemo(()=>tl(p),[p]),qe=o.useMemo(()=>{const M=[],De=Ts(q);sl(p)&&we&&Re&&M.push({type:"parent",value:"browse:up",name:we,path:Re,alreadyAdded:!!(De&&ot.has(De))});for(const Fe of ve){const Je=Ts(Fe.path);M.push({type:"directory",value:`browse:${Fe.path}`,name:Fe.name,path:Fe.path,alreadyAdded:!!(Je&&ot.has(Je))})}return M},[ot,q,we,ve,Re,p]);o.useEffect(()=>{B(0)},[p,qe.length]);const at=o.useMemo(()=>Ae?sn(wi(p,Ae)):"",[Ae,p]),mt=Ts(at),Le=!!(mt&&ot.has(mt)),ke=o.useMemo(()=>pe?ve.find(M=>M.name===pe)??null:null,[pe,ve]),Ye=!!(at&&!Le&&(Y===null||Y==="not-found")&&(Zs(p)&&R||!Zs(p)&&pe.trim().length>0&&ke===null)),pt=!O&&!de&&!Le&&Y!=="os-permission"&&Y!=="invalid-response"&&Y!=="unknown"&&!!at,kt=pt&&He.trim().length>0,bt=qe[H]??null,_=!!bt,be=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Ie=Le?"Already added":Ce?O?"Cloning...":"Clone & add":O?"Adding...":Ye?"Create & add":"Add folder",C=Ce?kt:pt;o.useLayoutEffect(()=>{const M=v.current;M&&(M.scrollLeft=M.scrollWidth)},[p]),o.useLayoutEffect(()=>{e&&Cr(v.current)},[e]),o.useLayoutEffect(()=>{const M=qe[H];M&&D.current.get(M.value)?.scrollIntoView({block:"nearest"})},[H,qe]);const K=o.useCallback(()=>{s(!1)},[s]),ee=o.useCallback((M,De)=>{a("chat"),w&&l(!1),c({selectedProjectId:M,directoryOverride:De}),K()},[K,w,c,a,l]),ue=o.useCallback(async M=>{if(!M||O)return;const De=Ts(M);if(De&&ot.has(De))return;let Fe=M;J(!0);try{const Je=!Ce&&Ye&&Ts(M)===Ts(at);if(Ce){const Rt=He.trim();if(!Rt){le.error("Enter a repository URL before cloning.");return}const z=await Xt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:Rt,destinationPath:M,gitIdentityId:Q?.id??null})});if(!z.ok)throw new Error("Failed to clone git repository");Fe=(await z.json()).path||M}else if(Je&&!(await Xt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:q?{directory:q}:void 0,body:JSON.stringify({path:M})})).ok)throw new Error("Failed to select directory");const dt=i(Fe);if(!dt){le.error("Failed to add folder",{description:"Please select a valid directory path."});return}ee(dt.id,dt.path)}catch(Je){le.error("Failed to select directory",{description:Je instanceof Error?Je.message:"Unknown error occurred."})}finally{J(!1)}},[i,ot,q,He,Ce,O,ee,Q?.id,Ye,at]),me=o.useCallback(M=>{N(er(M))},[]),Se=o.useCallback(M=>{N(yh(p,M.name))},[p]),Ve=o.useCallback(M=>{if(M){if(M.type==="parent"){me(M.path);return}Se(M)}},[me,Se]),ft=o.useCallback(async M=>{const De=await g(M);if(!De.success)return le.error("Failed to open directory",{description:De.error||"Desktop could not grant file access."}),!1;const Fe=Ae?vh(M,Ae):er(Xs(M));return me(Fe),!0},[me,Ae,g]),lt=o.useCallback(async()=>{if(!de){G(!0);try{if(bo()){const De=await yo(at);if(!De.success||!De.path){De.error&&De.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:De.error});return}await ft(De.path);return}const M=await bu(at);if(M.status==="cancelled")return;if(M.status!=="picked"){le.error("Couldn't open a folder picker",{description:M.error});return}await ft(M.path)}catch(M){le.error("Failed to select directory",{description:M instanceof Error?M.message:"Unknown error occurred."})}finally{G(!1)}}},[ft,de,at]),it=o.useCallback(M=>{if(M.key==="ArrowDown"){M.preventDefault(),B(De=>Math.min(qe.length-1,De+1));return}if(M.key==="ArrowUp"){M.preventDefault(),B(De=>Math.max(0,De-1));return}if(M.key==="Enter"){if(M.preventDefault(),wh(M)){ue(at);return}_&&Ve(bt);return}M.key==="Backspace"&&p===""&&(M.preventDefault(),K())},[Ve,ue,K,_,bt,p,qe.length,at]),gt=t.jsxs("button",{type:"button",onClick:()=>xe(M=>!M),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:[te?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"]}),Xe=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(en,{ref:v,value:p,onChange:M=>N(Xs(M.target.value)),onKeyDown:it,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:O||de,onMouseDown:M=>M.preventDefault(),onClick:()=>{lt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),de?"Opening...":"Browse"]})]})}),Oe=qe.some(M=>M.type==="parent"),Ze=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":Ce,disabled:O||de,onClick:()=>Me(M=>!M),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ce?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(en,{value:He,onChange:M=>ze(M.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(Xa,{activeProfile:Q,identities:We,onSelect:M=>Pe(M.id),isApplying:O,iconOnly:!0})]})]}):null,Le?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:F("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",Ge==="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..."}):Y&&Y!=="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:Y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[Y==="os-permission"&&f?t.jsx(Qe,{size:"xs",onClick:()=>{lt()},disabled:de,children:"Grant access"}):null,t.jsx(Qe,{variant:"outline",size:"xs",onClick:()=>$(M=>M+1),children:"Try again"})]})]}):qe.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:qe.map((M,De)=>{const Fe=De===H,Je=M.type==="directory"&&Oe;return t.jsxs("button",{ref:dt=>{dt?D.current.set(M.value,dt):D.current.delete(M.value)},type:"button","aria-label":M.type==="parent"?M.alreadyAdded?`Go back from ${M.name}, already added`:`Go back from ${M.name}`:M.alreadyAdded?`Open ${M.name}, already added`:`Open ${M.name}`,onMouseEnter:()=>B(De),onMouseDown:dt=>dt.preventDefault(),onClick:()=>Ve(M),className:F("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",Fe&&"bg-interactive-selection text-interactive-selection-foreground",!Fe&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:F("flex min-w-0 flex-1 items-center gap-2",Je&&"pl-4"),children:[M.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:M.name})]}),M.alreadyAdded?t.jsx("span",{className:F("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Fe?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,M.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"})]},M.value)})})},V)]})}),vt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Xe,Ze]}),Ot=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:be}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Et=t.jsx(Qe,{size:w?"xs":"default",onClick:()=>{ue(at)},disabled:!C,className:F(w&&"w-full flex-1"),children:Ie}),jt=()=>t.jsxs(t.Fragment,{children:[w?null:Ot,t.jsx("div",{className:F("flex w-full flex-row justify-end gap-2 sm:w-auto",w&&"justify-stretch"),children:Et})]});return w?t.jsx(ua,{open:e,onClose:K,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:jt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:gt}),vt]})}):t.jsx(fs,{open:e,onOpenChange:s,children:t.jsxs(hs,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(Is,{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(vs,{children:"Add folder"}),t.jsx($s,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),gt]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:vt}),t.jsx(Gs,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:jt()})]})})},Fn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Cx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=ed,c=_e(N=>N.deleteSessions),d=re(N=>N.showDeletionDialog),u=re(N=>N.setShowDeletionDialog),{isMobile:b,isTablet:h,hasTouchInput:x}=Us(),y=b||h||x;o.useEffect(()=>vu(()=>{s(!1)}),[]);const f=o.useCallback(N=>{r({sessions:N.sessions,dateLabel:N.dateLabel})},[]),g=o.useCallback(()=>{r(null),a(!1)},[]),w=o.useCallback(async N=>{if(N.sessions.length===0)return;if(N.sessions.length===1){const E=N.sessions[0];await l(E.id)?le.success("Session deleted"):le.error("Failed to delete session");return}const T=N.sessions.map(E=>E.id),{deletedIds:A,failedIds:P}=await c(T);if(A.length>0){const E=P.length>0?P.length===1?`${P.length} session could not be deleted.`:`${P.length} sessions could not be deleted.`:N.dateLabel?`Removed all sessions from ${N.dateLabel}.`:void 0;le.success(A.length===1?"Deleted {count} session":`Deleted ${A.length} sessions`,{description:Fn(E)})}P.length>0&&le.error(P.length===1?`Failed to delete ${P.length} session`:`Failed to delete ${P.length} sessions`,{description:Fn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>_s.onDeleteRequest(N=>{if(!d){w(N);return}f(N)}),[f,d,w]),o.useEffect(()=>_s.onDirectoryRequest(()=>{s(!0)}),[]);const v=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const N=n.sessions[0];if(!await l(N.id)){le.error("Failed to delete session"),a(!1);return}le.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const N=n.sessions.map(E=>E.id),T=await c(N),A=T.deletedIds,P=T.failedIds;if(A.length>0){const E=P.length>0?P.length===1?`${P.length} session could not be deleted.`:`${P.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;le.success(A.length===1?"Deleted {count} session":`Deleted ${A.length} sessions`,{description:Fn(E),action:{label:"OK",onClick:()=>{}}})}if(P.length>0&&(le.error(P.length===1?`Failed to delete ${P.length} session`:`Failed to delete ${P.length} sessions`,{description:Fn("Please try again in a moment.")}),A.length===0)){a(!1);return}}g()}finally{a(!1)}}},[n,l,c,g]),D=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.`:"",S=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(N=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:N.title||"Untitled Session"})},N.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,m=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:g,disabled:i,children:"Cancel"}),t.jsx(Qe,{variant:"destructive",onClick:v,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:[y?t.jsx(ua,{open:!!n,onClose:()=>{i||g()},title:p,footer:t.jsx("div",{className:"flex justify-end gap-2",children:m}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[D&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:D}),S]})}):t.jsx(fs,{open:!!n,onOpenChange:N=>{if(!N){if(i)return;g()}},children:t.jsxs(hs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:p}),D&&t.jsx($s,{children:D})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:S}),t.jsx(Gs,{className:"mt-2 gap-2 pt-1 pb-1",children:m})]})}),t.jsx(jh,{open:e,onOpenChange:s})]})};function kx(){const e=o.useMemo(()=>ia(),[]),s=o.useRef(!1),n=o.useRef(!1),r=_e(h=>h.setCurrentSession),i=re(h=>h.setActiveMainTab),a=re(h=>h.setSettingsDialogOpen),l=re(h=>h.setSettingsPage),c=re(h=>h.navigateToDiff),d=o.useCallback(async h=>{if(!n.current){n.current=!0;try{if(h.sessionId){const x=_e.getState().currentSessionId,y=Hs().getState().selectedSessionId;if(h.sessionId!==x||h.sessionId!==y){const g=(e&&typeof window<"u"?new URLSearchParams(window.location.search).get("directory"):null)||_e.getState().getDirectoryForSession(h.sessionId);r(h.sessionId,g)}}if(h.settingsPath){l(ah(h.settingsPath)),a(!0);return}re.getState().isSettingsDialogOpen&&a(!1),h.tab&&i(h.tab),h.diffFile&&(h.tab==="diff"||!h.tab)&&c(h.diffFile)}finally{n.current=!1}}},[e,r,i,a,l,c]),u=o.useCallback(()=>{const h=_e.getState(),x=Hs().getState(),y=re.getState();return{sessionId:h.currentSessionId??x.selectedSessionId,tab:y.activeMainTab,isSettingsOpen:y.isSettingsDialogOpen,settingsPath:y.settingsPage,diffFile:y.pendingDiffFile}},[]),b=o.useCallback((h={})=>{if(e||n.current)return;const x=u();to(x,h)},[e,u]);o.useEffect(()=>{if(s.current||(s.current=!0,!Jo()))return;const h=Xo();(async()=>(await d(h),e||to({...u(),sessionId:h.sessionId??_e.getState().currentSessionId??Hs().getState().selectedSessionId,tab:h.tab??re.getState().activeMainTab,settingsPath:h.settingsPath??re.getState().settingsPage,diffFile:h.diffFile??re.getState().pendingDiffFile},{replace:!0,force:!0})))()},[d,u,e]),o.useEffect(()=>{if(e)return;let h=_e.getState().currentSessionId??Hs().getState().selectedSessionId;const x=g=>{!g||g===h||n.current||(h=g,b({replace:!0}))},y=_e.subscribe(g=>{x(g.currentSessionId)}),f=Hs().subscribe(()=>{x(Hs().getState().selectedSessionId)});return()=>{y(),f()}},[e,b]),o.useEffect(()=>{if(e)return;let h=re.getState().activeMainTab,x=re.getState().isSettingsDialogOpen,y=re.getState().settingsPage,f=re.getState().pendingDiffFile;return re.subscribe(w=>{if(n.current)return;const v=w.activeMainTab!==h,D=w.isSettingsDialogOpen!==x,S=w.settingsPage!==y,m=w.pendingDiffFile!==f&&w.activeMainTab==="diff";h=w.activeMainTab,x=w.isSettingsDialogOpen,y=w.settingsPage,f=w.pendingDiffFile,(v||D||S||m)&&b()})},[e,b]),o.useEffect(()=>{if(typeof window>"u"||e)return;const h=()=>{const x=Xo();if(Jo())d(x);else{const y=re.getState();y.isSettingsDialogOpen&&a(!1),y.activeMainTab!=="chat"&&i("chat")}};return window.addEventListener("popstate",h),()=>{window.removeEventListener("popstate",h)}},[d,e,i,a])}function Ch(e=!0){const s=Wn(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=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},b=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):i;b(y)},h))};return b(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Nx(){const e=un(s=>s.connection==="ready",void 0,"chrome");return Ch(e),null}const Si=12,kh=[{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"}],Nh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=kh,onComplete:a})=>{const l=Ke.useRef(!1);Ke.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ke.useMemo(()=>Array.from({length:Si},(d,u)=>{const b=Math.PI*2*u/Si;return{x:Math.cos(b),y:Math.sin(b),delay:u*18}}),[]);return e?t.jsx("div",{className:F("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((b,h)=>{const x=b.x*d.radius,y=b.y*d.radius,f={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${b.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:f},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},Ah=({durationMs:e=3400}={})=>{const[s,n]=Ke.useState({isActive:!1,cycle:0}),r=Ke.useRef(null),i=Ke.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ke.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Ke.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 Ke.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},nl=o.createContext(void 0),Ax=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Ah(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(nl.Provider,{value:a,children:[e,t.jsx(Nh,{isActive:s,burstKey:n})]})},Ih={triggerFireworks:()=>{},dismissFireworks:()=>{}},Ix=()=>o.useContext(nl)??Ih,ji=380,Dh=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),Ph=e=>e>=90?"critical":e>=75?"warn":"safe",Ci=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},ki=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),rl=({percentage:e})=>{const s=Dh(e),n=Ph(e),r=n==="critical"?"var(--status-error)":n==="warn"?"var(--status-warning)":"var(--status-success)",i=18,a=3,l=(i-a)/2,c=2*Math.PI*l;return t.jsxs("svg",{viewBox:`0 0 ${i} ${i}`,className:"size-[18px] -rotate-90",role:"progressbar","aria-valuenow":Math.round(s),"aria-valuemin":0,"aria-valuemax":100,children:[t.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:"var(--interactive-border)",strokeWidth:a}),t.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:r,strokeWidth:a,strokeLinecap:"round",strokeDasharray:c,strokeDashoffset:c*(1-s/100),className:"transition-[stroke-dashoffset,stroke] duration-300"})]})},Th=({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})]}),Eh=({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}=ha(),b=o.useRef(null),[h,x]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const f=()=>{const v=n.current?.getBoundingClientRect(),D=b.current?.getBoundingClientRect();if(!v||!D){x(null);return}const S=v.left-D.left,m=Math.min(Math.max(S,8),Math.max(8,D.width-ji-8));x(m)};f();const g=b.current;if(typeof ResizeObserver>"u"||!g)return;const w=new ResizeObserver(f);return w.observe(g),()=>w.disconnect()},[n,u,e,a]);const y=u&&h!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const f=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(f)},[e,a]),o.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,e]),o.useEffect(()=>{if(!e)return;const f=g=>{const w=g.target;if(!(w instanceof Node)){s();return}i.current?.contains(w)||n.current?.contains(w)||s()};return document.addEventListener("pointerdown",f,!0),document.addEventListener("wheel",f,!0),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("wheel",f,!0)}},[n,s,e]),a?t.jsxs("div",{ref:b,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:F("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",y?"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))",...y?{top:8,left:h??8,width:`min(${ji}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsx(Th,{iconNode:t.jsx(rl,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:F("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}):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
- @keyframes session-metadata-in {
4
- from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
- to { opacity: 1; transform: translateY(0) scale(1); }
6
- }
7
- @keyframes session-metadata-out {
8
- from { opacity: 1; transform: translateY(0) scale(1); }
9
- to { opacity: 0; transform: translateY(-6px) scale(0.985); }
10
- }
11
- `})]}):null},Rh=o.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:i,isNewSessionDraftOpen:a}){const l=o.useRef(null),c=td(r??""),d=Lt(L=>L.providers),u=Lt(L=>L.currentProviderId),b=Lt(L=>L.currentModelId),h=Lt(L=>L.getCurrentModel()),x=Lt(L=>L.getModelMetadata);Lt(L=>L.modelsMetadata.size);const y=fa(o.useCallback(L=>r?L.sessionModelSelections.get(r)??null:null,[r])),f=o.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const Y=c[L]?.info;if(Y.role!=="user")continue;const X=Y.model,oe=X?.providerID??X?.providerId,$=X?.modelID??X?.modelId,H=typeof oe=="string"&&oe.trim().length>0?oe:void 0,B=typeof $=="string"&&$.trim().length>0?$:void 0;if(H&&B)return{providerID:H,modelID:B}}return null},[c]),g=o.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const Y=c[L];if(Y?.info.role==="assistant"&&Zo(Y).total>0)return Y}return null},[c]),w=f??(()=>{const L=g?.info.model,Y=L?.providerID??L?.providerId,X=L?.modelID??L?.modelId;return Y&&X?{providerID:Y,modelID:X}:null})()??(y?{providerID:y.providerId,modelID:y.modelId}:null)??(u&&b?{providerID:u,modelID:b}:null),D=(w?d.find(L=>L.id===w.providerID):void 0)?.models.find(L=>L.id===w?.modelID),S=w?x(w.providerID,w.modelID):void 0,m=Ci(D?.limit,"context")??S?.limit?.context??Ci(h?.limit,"context")??0,p=g?Zo(g):null,N=g?.info?.usage,T=N?sd(N):p?.total??0,A=!a&&T>0&&m>0?Math.min(T/m*100,999):null,P=A!==null?`${ki(T)}/${ki(m)}`:null,E=A===null?"":A>=90?"text-[var(--status-error)]":A>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",R=A!==null&&P?{percentage:A,tokens:P,colorClass:E}:null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":s,onClick:()=>n(L=>!L),style:{touchAction:"manipulation"},children:t.jsx(rl,{percentage:R?.percentage??0})}),t.jsx(Eh,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:R})]})}),Ni=600,Mh=1,Fh=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Lh=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:i})=>{const a=o.useRef(new Map),l=o.useRef([]),c=o.useRef(new Set),d=o.useRef(0),u=!1,b=o.useCallback(f=>`${f.directory}
12
- ${f.sessionId}`,[]),h=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(f=>window.clearTimeout(f)),a.current.clear()},[]),x=o.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<Mh&&l.current.length>0;){const f=l.current.shift();if(!f)break;f.generation!==d.current||_e.getState().currentSessionId===f.sessionId||nd(f.sessionId,f.directory).renderable}},[e,u,i,b]),y=o.useCallback(f=>{const g=f?.id,w=Fh(f);if(!e||u||!g||!w||g===s||typeof window>"u")return;const v={sessionId:g,directory:w,generation:d.current};b(v)},[s,e,u,x,b]);o.useEffect(()=>{h()},[h,s,e,u]),o.useEffect(()=>{if(!e||u||!s||n.length===0)return;const f=window.setTimeout(()=>{const g=n.findIndex(w=>w.id===s);g<0||(y(n[g-1]),y(n[g+1]))},Ni);return()=>window.clearTimeout(f)},[s,e,u,y,n]),o.useEffect(()=>{if(!e||u||!s||r.length===0)return;const f=window.setTimeout(()=>{const g=r.findIndex(w=>w.id===s);g<0||(y(r[g-1]),y(r[g+1]))},Ni);return()=>window.clearTimeout(f)},[s,e,u,r,y]),o.useEffect(()=>h,[h])},Oh=e=>{const s=_e(n=>n.currentSessionId);return Lh({...e,currentSessionId:s}),null},Bh=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:i,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:b}=e;o.useEffect(()=>{!n||i||!a||l||s.forEach(h=>{if(c.has(h.normalizedPath))return;const x=pa(h.normalizedPath),y=r.archivedSessionsByProject.get(h.id)??[],f=d[x]??[],g=new Map(f.map(w=>[w.name.toLowerCase(),w]));y.forEach(w=>{const v=rd(w,h.normalizedPath),D=v.toLowerCase();let S=g.get(D);S||(S=u(x,v),g.set(D,S)),S.sessionIds.includes(w.id)||b(x,S.id,w.id)})})},[s,n,r,i,a,l,c,d,u,b])},_h=e=>({getOrderedGroups:o.useCallback((n,r)=>{const i=e.get(n);if(!i||i.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];i.forEach(u=>{const b=a.get(u);b&&(l.push(b),a.delete(u))});const c=[],d=[];return r.forEach(u=>{a.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),zh=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:l,buildGroupedSessions:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:b,buildGroupSearchText:h,foldersMap:x}=e,y=o.useRef(new Map),f=o.useMemo(()=>{const N=y.current,T=new Map;let A=0,P=0;const E=(L,Y)=>L.length===Y.length&&L.every((X,oe)=>X===Y[oe]),R=s.map(L=>{const Y=n(L.id),X=r(L.id),oe=i.has(L.id)?!!i.get(L.id):l,$=a.get(L.id)??null,H=N.get(L.id);if(H&&H.project===L&&E(H.activeSessions,Y)&&E(H.archivedSessions,X)&&H.rootBranch===$&&H.isRepo===oe&&H.buildGroupedSessions===c)return A+=1,T.set(L.id,H),H.section;P+=1;const B=ma([...Y,...X]),O=c(B,L.normalizedPath,[],$,oe),J={project:L,groups:O};return T.set(L.id,{project:L,activeSessions:Y,archivedSessions:X,rootBranch:$,isRepo:oe,buildGroupedSessions:c,section:J}),J});return y.current=T,A>0&&as("ui.sidebar.project_section.reused",A),P>0&&as("ui.sidebar.project_section.rebuilt",P),R},[s,n,r,i,l,c,a]),g=o.useMemo(()=>f,[f]),w=o.useMemo(()=>{const N=new WeakMap;if(!d)return N;const T=A=>A.reduce((P,E)=>P+1+T(E.children),0);return g.forEach(A=>{A.groups.forEach(P=>{const E=b(P.sessions,u),R=T(E),L=h(P).includes(u),Y=yt(P.directory??null),oe=(Y?x[Y]??[]:[]).filter($=>$.name.toLowerCase().includes(u)).length;N.set(P,{filteredNodes:E,matchedSessionCount:R,folderNameMatchCount:oe,groupMatches:L,hasMatch:L||R>0||oe>0})})}),N},[d,g,b,u,h,x]),v=o.useMemo(()=>d?g.map(N=>({...N,groups:N.groups.filter(T=>w.get(T)?.hasMatch===!0)})).filter(N=>N.groups.length>0):g,[d,g,w]),D=d?v:g,S=o.useRef(new WeakMap),m=o.useMemo(()=>{const N=S.current;return D.map(T=>{const A=N.get(T);if(A&&A.query===u)return A.section;const P=T.groups.filter($=>!$.isArchivedBucket),E=T.groups.filter($=>$.isArchivedBucket),R=P.flatMap($=>d?w.get($)?.filteredNodes??[]:$.sessions),L=P.map($=>({scopeKey:$.folderScopeKey??yt($.directory??null),directory:$.directory??null})).filter($=>!!$.scopeKey),Y=P.find($=>$.isMain)??null,X={id:"flat",label:Y?.label??"",branch:Y?.branch??null,description:Y?.description??null,isMain:!0,isArchivedBucket:!1,directory:Y?.directory??T.project.normalizedPath,folderScopeKey:Y?.folderScopeKey??T.project.normalizedPath,folderScopes:L,sessions:R};if(d){const $=P.map(H=>w.get(H)).filter(H=>!!H);w.set(X,{filteredNodes:R,matchedSessionCount:$.reduce((H,B)=>H+B.matchedSessionCount,0),folderNameMatchCount:$.reduce((H,B)=>H+B.folderNameMatchCount,0),groupMatches:$.some(H=>H.groupMatches),hasMatch:$.some(H=>H.hasMatch)})}const oe={project:T.project,groups:[X,...E]};return N.set(T,{query:u,section:oe}),oe})},[w,d,u,D]),p=o.useMemo(()=>d?D.reduce((N,T)=>N+T.groups.reduce((A,P)=>{const E=w.get(P);if(!E)return A;const R=E.folderNameMatchCount+(E.groupMatches?1:0);return A+E.matchedSessionCount+R},0),0):0,[d,D,w]);return{projectSections:f,visibleProjectSections:g,groupSearchDataByGroup:w,searchableProjectSections:v,sectionsForRender:D,flatSectionsForRender:m,searchMatchCount:p}},Uh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:b,setSessionSwitcherOpen:h}=e,x=o.useMemo(()=>{const f=new Map,g=new Map,w=(v,D,S,m)=>{f.has(v)||f.set(v,new Map);const p=f.get(v);m.forEach(N=>{const T=yt(N.session.directory??S??D);p.set(N.session.id,{directory:T}),g.has(v)||g.set(v,{id:N.session.id,directory:T}),N.children.length>0&&w(v,D,T,N.children)})};return s.forEach(v=>{v.groups.forEach(D=>{w(v.project.id,v.project.normalizedPath,D.directory,D.sessions)})}),{metaByProject:f,firstSessionByProject:g}},[s]),y=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){y.current=n;return}if(y.current===n)return;const f=s.find(N=>N.project.id===n);if(!f)return;y.current=n;const g=x.metaByProject.get(n);if(a&&g&&g.has(a)){i(N=>{if(N.get(n)===a)return N;const T=new Map(N);return T.set(n,a),T});return}const w=a?Array.from(x.metaByProject.entries()).some(([N,T])=>N!==n&&T.has(a)):!1;if(a&&g&&!w)return;if(!g||g.size===0){b("chat"),d&&h(!1),u({selectedProjectId:f.project.id,directoryOverride:f.project.normalizedPath});return}const v=r.get(n),D=v&&g.has(v)?v:null,S=x.firstSessionByProject.get(n)?.id??null,m=D??S;if(!m||m===a)return;const p=g.get(m)?.directory??null;l(m,p,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,x,b,h,i]),o.useEffect(()=>{if(!n||!a)return;const f=x.metaByProject.get(n);!f||!f.has(a)||i(g=>{if(g.get(n)===a)return g;const w=new Map(g);return w.set(n,a),w})},[n,a,x,i])},$h=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=_e(c=>c.currentSessionId),i=_e(c=>!!c.newSessionDraft?.open),[a,l]=o.useState(()=>new Map(e));return Uh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},Ln=e=>!!e.time?.archived,Gh=e=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=yt(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=o.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):a,[n]),i=o.useCallback((a,l,c,d,u)=>{const b=yt(l??null),h=ma(a).sort((S,m)=>Jn(S,m,e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(h.map(S=>[S.id,S])),y=new Map;h.forEach(S=>{const m=S.parentID;if(!m)return;const p=x.get(m);if(!p||Ln(p)!==Ln(S))return;const N=y.get(m)??[];N.push(S),y.set(m,N)}),y.forEach(S=>S.sort((m,p)=>Jn(m,p,e.pinnedSessionIds,e.sessionOrderRanks)));const f=S=>{const m=y.get(S.id)??[];return{session:S,children:m.map(p=>f(p)),worktree:null}},g=h.filter(S=>{const m=S.parentID;if(!m)return!0;const p=x.get(m);return p?Ln(p)!==Ln(S):!0}),w=[],v=[];g.forEach(S=>{const m=f(S);S.time?.archived?v.push(m):w.push(m)});const D=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:b?od(b,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:b,folderScopeKey:b,sessions:w}];return v.length>0&&D.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:b?pa(b):null,sessions:v}),D},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},Kh=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:i})=>{o.useEffect(()=>{if(!e||!s||typeof window>"u")return;const a=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(a)},[e,s,r]),o.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{i.current&&(i.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,i])},Hh=e=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((S,m,p)=>{Hr("navigation.session_select"),re.getState().closeMainSurfaces();const N=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},T=p?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),S===_e.getState().currentSessionId){e.allowReselect&&T&&e.onSessionSelected?.(S),N();return}Hr("navigation.session_state_set"),e.setCurrentSession(S,m??null),T&&e.onSessionSelected?.(S),N()},[e]),a=o.useCallback((S,m)=>{e.setEditingId(S),e.setEditTitle(m)},[e]),l=o.useCallback(async S=>{if(!e.editingId)return;const m=(S??e.editTitle).trim();m&&await e.updateSessionTitle(e.editingId,m),e.setEditingId(null),e.setEditTitle("")},[e]),c=o.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=o.useCallback(async(S,m)=>{try{return(await gn(S)).ok?(n(m),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=o.useCallback(async S=>{const m=await e.shareSession(S.id);if(!m?.share?.url){le.error("Unable to share session");return}const p=await d(m.share.url,S.id);le[p?"success":"warning"]("Session shared",{description:p?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),b=o.useCallback((S,m)=>{d(S,m).then(p=>{p||le.error("Failed to copy URL")})},[d]),h=o.useCallback(S=>{gn(S).then(m=>{if(m.ok){le.success("Session ID copied");return}le.error("Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[]),x=o.useCallback(async S=>{await e.unshareSession(S)?le.success("Session unshared"):le.error("Unable to unshare session")},[e]),y=o.useCallback(S=>{const m=[],p=N=>{(e.childrenMap.get(N)??[]).forEach(A=>{m.push(A),p(A.id)})};return p(S),m},[e.childrenMap]),f=o.useCallback((S,m)=>m?S:S.filter(p=>!p.time?.archived),[]),g=o.useCallback(async(S,m,p)=>{const N=m?.archivedBucket===!0||m?.hardDelete===!0,T=p?.descendantIds??f(y(S.id),N).map(R=>R.id);if(T.length===0){(N?await e.deleteSession(S.id):await e.archiveSession(S.id))?le.success(N?"Session deleted":"Session archived"):le.error(N?"Failed to delete session":"Failed to archive session");return}const A=[S.id,...T];if(N){const{deletedIds:R,failedIds:L}=await e.deleteSessions(A);if(L.length===0){const Y=R.length;le.success(Y===1?`Deleted ${Y} session`:`Deleted ${Y} sessions`)}else le.error("Failed to delete session");return}const{archivedIds:P,failedIds:E}=await e.archiveSessions(A);P.length>0&&le.success(P.length===1?`Archived ${P.length} session`:`Archived ${P.length} sessions`),E.length>0&&le.error(E.length===1?`Failed to archive ${E.length} session`:`Failed to archive ${E.length} sessions`)},[e,y,f]),w=o.useCallback((S,m)=>{const p=m?.archivedBucket===!0||m?.hardDelete===!0,N=f(y(S.id),p).map(T=>T.id);if(!e.showDeletionDialog||m?.skipConfirm===!0){g(S,m,{descendantIds:N});return}e.setDeleteSessionConfirm({session:S,descendantCount:N.length,descendantIds:N,archivedBucket:p})},[e,y,g,f]),v=o.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:S,archivedBucket:m,descendantIds:p}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await g(S,{archivedBucket:m},{descendantIds:p})},[e,g]),D=o.useCallback(async S=>{await e.unarchiveSession(S.id)?le.success("Session restored"):le.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:i,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:b,handleCopySessionId:h,handleUnshareSession:x,handleDeleteSession:w,handleRestoreSession:D,confirmDeleteSession:v}},Wh=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:i,setExpandedParents:a,setCollapsedProjects:l}=e,c=o.useRef(null),d=o.useRef(null),u=o.useCallback(()=>{const h=d.current;if(d.current=null,c.current=null,!h)return;const{projects:x}=Ut.getState(),y=x.map(f=>({...f,sidebarCollapsed:h.has(f.id)}));go({projects:y}).catch(()=>{})},[]),b=o.useCallback(h=>{typeof window>"u"||(d.current=h,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return o.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),o.useEffect(()=>{try{const h=s.getItem(n.sessionExpanded);if(h){const y=JSON.parse(h);Array.isArray(y)&&a(new Set(y.filter(f=>typeof f=="string")))}const x=s.getItem(n.projectCollapse);if(x){const y=JSON.parse(x);Array.isArray(y)&&l(new Set(y.filter(f=>typeof f=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const h=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(h))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:b}},Yh=5*6e4,Vh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=e,{git:l}=nr(),c=ga(h=>h.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(h=>{ef(()=>c(h.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const h=new Map;s.forEach(x=>{h.set(x.id,r.get(x.normalizedPath)?.isGitRepo??null)}),i(h)},[n,s,r,i]);const d=o.useMemo(()=>s.map(h=>{const x=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${x}`}).join("|"),[s,r]),u=o.useRef(new Map),b=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let h=!1;const x=setTimeout(()=>{(async()=>{const f=new Set(s.map(S=>S.id));for(const S of u.current.keys())f.has(S)||(u.current.delete(S),b.current.delete(S));const g=Date.now();if(s.filter(S=>{const m=r.get(S.normalizedPath);if(m?.isGitRepo===!1)return u.current.delete(S.id),b.current.delete(S.id),!1;if(m?.isGitRepo!==!0||m.branch===null)return!1;const p=m.branch.trim(),N=`${S.normalizedPath}\0${p}`,T=u.current.get(S.id);if(T===N){const A=b.current.get(S.id);return A&&(A.at=g),!1}return!(T!==void 0&&g-(b.current.get(S.id)?.at??0)<Yh)}).length===0)return;const v=[];if(s.forEach(S=>{const m=r.get(S.normalizedPath)?.branch?.trim()??"",p=`${S.normalizedPath}\0${m}`;m&&v.push({id:S.id,inputKey:p,branch:m})}),h||v.length===0)return;const D=Date.now();a(S=>{const m=new Map(S);return v.forEach(({id:p,branch:N})=>{N&&m.set(p,N)}),m}),v.forEach(({id:S,inputKey:m,branch:p})=>{u.current.set(S,m),p&&b.current.set(S,{branch:p,at:D})})})()},150);return()=>{h=!0,clearTimeout(x)}},[n,s,d,r,a])},qh=e=>{const{ownership:s}=e,n=o.useCallback(i=>s.sessionsByProject.get(i)??[],[s]),r=o.useCallback(i=>s.archivedSessionsByProject.get(i)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Qh=e=>{if(e.runtimeKey!==ir()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=wu(e.sessionId,e.directory,e.runtimeKey);s&&Su.getState().clearQueue(s),id.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),$t.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),xa.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),Gr.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=ad(e.runtimeKey,e.directory,e.sessionId);n&&ld(n,!0)},Jh=e=>{const s=new Map;for(const n of e){const r=Js(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Xh=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,i)=>{s.has(i)||n.push(r)}),n},Zh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=ir(),l=Jh(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of Xh(c,l))Qh({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},ep=(e,s)=>e?s.kind!==e.kind?s.kind==="project":s.projectRoot.length!==e.projectRoot.length?s.projectRoot.length>e.projectRoot.length:s.projectId.localeCompare(e.projectId)<0:!0,Ai=(e,s,n)=>{ep(e.get(s),n)&&e.set(s,n)},tp=e=>{const s=e;return yt(s.directory)??yt(s.project?.worktree)},sp=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const s=e.lastIndexOf("/");return s<0?null:s===0?"/":s===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,s)},np=(e,s,n,r=[])=>{const i=new Map,a=new Map;for(const y of s){const f=yt(y.normalizedPath);if(!f)continue;const g=a.get(f);(!g||y.id.localeCompare(g.id)<0)&&a.set(f,y),Ai(i,f,{projectId:y.id,projectRoot:f,scopeDirectory:f,kind:"project"})}if(n)for(const[y,f]of n){const g=yt(y),w=g?a.get(g):void 0;if(!(!w||!g))for(const v of f||[]){const D=yt(v?.path);D&&Ai(i,D,{projectId:w.id,projectRoot:g,scopeDirectory:D,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,b=new Map,h=y=>{if(!y)return null;if(l.has(y))return l.get(y)??null;const f=[];let g=y,w=null;for(;g;){if(l.has(g)){w=l.get(g)??null;break}if(f.push(g),w=i.get(g)??null,w)break;g=sp(g)}for(const v of f)l.set(v,w);return w},x=(y,f,g)=>{for(const w of y){const v=h(tp(w));if(!v)continue;c.set(w.id,v);const D=f.get(v.projectId);if(D?D.push(w):f.set(v.projectId,[w]),!g)continue;const S=g.get(v.scopeDirectory);S?S.add(w.id):g.set(v.scopeDirectory,new Set([w.id]))}};return x(e,d,b),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:b,directoryResolutions:l.size}},rp=e=>{const{enabled:s=!0,isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:i}=e,[a,l]=o.useState(new Set);return o.useEffect(()=>{if(!s||!n){l(b=>b.size===0?b:new Set);return}const d=Array.from(i.current.values()).find(b=>b!==null)?.closest(".oc-sidebar-scroller")??null;if(!d)return;const u=new IntersectionObserver(b=>{l(h=>{const x=new Set(h);let y=!1;for(const f of b){const g=f.target.dataset.projectId;if(!g)continue;const w=f.rootBounds?.top??d.getBoundingClientRect().top,v=!f.isIntersecting&&f.boundingClientRect.top<w;x.has(g)!==v&&(y=!0,v?x.add(g):x.delete(g))}return y?x:h})},{root:d,threshold:0});return i.current.forEach(b=>{b&&u.observe(b)}),()=>u.disconnect()},[s,n,i,r]),a},op=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(fs,{open:e,onOpenChange:s,children:t.jsx(hs,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(Fs,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:t.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?t.jsx(Zf,{project:n,onIdentitySave:r}):null})})})});function ol({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(rr,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const ip=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:b,groupDirectory:h,projectId:x,mobileVariant:y=!1,alwaysShowActions:f=y,isRenaming:g=!1,renameDraft:w="",onRenameDraftChange:v,onRenameSave:D,onRenameCancel:S,droppableRef:m,isDropTarget:p=!1,onNewSession:N,depth:T=0,hideActions:A=!1,archivedBucket:P=!1})=>{const[E,R]=o.useState(!1),[L,Y]=o.useState(""),X=o.useRef(null),oe=g||E,$=g?w:L,H=o.useCallback(()=>{Y(e.name),R(!0)},[e.name]),B=o.useCallback(()=>{const G=$.trim();G&&G!==e.name&&c(G),g&&D&&D(),R(!1),Y("")},[$,e.name,g,c,D]),O=o.useCallback(()=>{g&&S&&S(),R(!1),Y("")},[g,S]),J=o.useCallback(G=>{g&&v?v(G):Y(G)},[g,v]);o.useEffect(()=>{if(!g)return;const G=()=>{const He=X.current;He&&(He.focus(),He.select())},Ce=requestAnimationFrame(G),Me=window.setTimeout(G,0);return()=>{cancelAnimationFrame(Ce),window.clearTimeout(Me)}},[g]);const de=i?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:m,className:F("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",p&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:oe?void 0:G=>{G.currentTarget.blur(),l()},role:oe?void 0:"button",tabIndex:oe?void 0:0,onKeyDown:oe?void 0:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),l())},"aria-label":i?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:F("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",P?f?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":f?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(k,{name:de,className:F(Kn,p?"text-primary":"text-muted-foreground")}),oe?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onSubmit:G=>{G.preventDefault(),B()},children:[t.jsx("input",{ref:X,value:$,onChange:G=>J(G.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onKeyDown:G=>{if(G.key==="Escape"){G.stopPropagation(),O();return}(G.key===" "||G.key==="Enter")&&G.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),children:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),O()},onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:F(ba,p?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(rt,{side:"right",sideOffset:8,className:"max-w-xs",children:s??e.name})]}),t.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?t.jsx(ol,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?t.jsx(k,{name:"arrow-right-s",className:F(Kn,"text-muted-foreground")}):t.jsx(k,{name:"arrow-down-s",className:F(Kn,"text-muted-foreground")})]})]}),!oe&&(!A||P)?t.jsx("div",{className:F("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",f?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!P&&N?t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),N()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:t.jsx(k,{name:"add",className:"size-4"})}):null,P?null:t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),H()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:t.jsx(k,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":P?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(k,{name:"delete-bin",className:"size-4"})})]})}):null]}),i?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(G=>t.jsx(o.Fragment,{children:u(G,0,h??null,x??null,P,void 0,"project",b?.(G))},G.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},ap=o.memo(ip),lp=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Ku({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),d=o.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return t.jsx("div",{ref:l,...i,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},cp=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Hu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},dp=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=ar(vn(wo,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,b]=o.useState(null),[h,x]=o.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const y=f=>{l(null),b(null),x(null);const{active:g,over:w}=f;if(!w)return;const v=g.data.current,D=w.data.current;v?.type==="session"&&v.sessionId&&D?.type==="folder"&&D.folderId&&n(v.sessionId,D.folderId)};return t.jsxs(lr,{sensors:i,collisionDetection:cr,onDragStart:f=>{const g=f.active.data.current;if(g?.type==="session"&&g.sessionId){l(g.sessionId),d(g.sessionTitle??"Session");const w=f.active.rect.current.initial?.width,v=f.active.rect.current.initial?.height;b(typeof w=="number"?w:null),x(typeof v=="number"?v:null)}},onDragCancel:()=>{l(null),b(null),x(null)},onDragEnd:y,children:[r,t.jsx(Oa,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:h?`${h}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[t.jsx(k,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),t.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Yn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),i=r.length;if(i===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const d=e.slice(c,c+i);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+i,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e},Os=({icon:e,children:s,onClick:n,className:r,mobileVariant:i=!1})=>t.jsxs("button",{type:"button",onClick:n,className:F(i?cd:dd,r),children:[t.jsx(k,{name:e,className:F(xn(i),"text-muted-foreground")}),t.jsx("span",{className:F(bn(i),"flex-1 text-muted-foreground"),children:s})]}),Ii=(e,s,n)=>{if(!s)return;const r=i=>{let a=i.session.id===s;for(const l of i.children)a=r(l)||a;return a&&n.add(i.session.id),a};for(const i of e)r(i)},bs=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(bs(n,s))return!0;return!1},up=(e,s,n)=>{const r=new Map,i=a=>{const l=Js(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===e&&s))for(const c of a.children)i(c)};return i(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},fp=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const i=new Set;let a=r.session.parentID??null;for(;a&&!i.has(a);){if(n.has(a)&&s.has(a))return!1;i.add(a),a=s.get(a)?.session?.parentID??null}return!0})},Di=new WeakMap;let Pi=1;const hp=e=>{const s=Di.get(e);if(s!==void 0)return s;const n=Pi;return Pi+=1,Di.set(e,n),n},io=e=>e.children.length===0?"":e.children.map(n=>{const r=hp(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${io(n)}`}).join("|"),il=(e,s,n,r,i,a)=>{const l=ir(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const b=d.session.directory??i,h=u.session.directory??a,x=ei(l,b??"",d.session.id),y=ei(l,h??"",u.session.id);return(x?n.has(x):!1)!==(y?r.has(y):!1)?!0:d.children.some((f,g)=>c(f,u.children[g]))};return c(e,s)},tr=(e,s,n,r)=>{if(!s)return null;const i=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${i}:${c.session.id}`===s)return a=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),a},al=(e,s)=>"",pp=ws(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),mp=e=>null,No=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,ll=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let i=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(i="unread");for(const l of e.children)if(i=No(i,ll(l,s,n,r)),i==="active")return i;return i},Ti=(e,s,n,r)=>{let i=null;for(const a of e)if(i=No(i,ll(a,s,n,r)),i==="active")return i;return i},gp=50,xp=28,On=(e,s)=>s?e.sessions.some(n=>bs(n,s)):!1,bp=(e,s,n)=>e.sessions.some(r=>il(r,r,s,n,e.directory,e.directory)),yp=(e,s,n)=>{const r=i=>{const a=i.session.id;return s.get(a)!==n.get(a)?!0:i.children.some(r)};return e.sessions.some(r)},Ei=(e,s,n)=>{const r=i=>s.has(i.session.id)!==n.has(i.session.id)?!0:i.children.some(r);return e.sessions.some(r)},vp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},wp=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",i=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(i)};return e.sessions.some(i)},Sp=(e,s)=>{if(e.group!==s.group||e.groupKey!==s.groupKey||e.projectId!==s.projectId||e.hideGroupLabel!==s.hideGroupLabel||e.compactBodyPadding!==s.compactBodyPadding||e.groupSearchDataByGroup!==s.groupSearchDataByGroup||e.visibleSessionCount!==s.visibleSessionCount||e.collapsedGroups!==s.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==s.collapsedGroups.has(s.groupKey)||e.pinnedSessionIds!==s.pinnedSessionIds&&bp(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&wp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&yp(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(On(e.group,e.editingId)||On(s.group,s.editingId))||e.editTitle!==s.editTitle&&(On(e.group,e.editingId)||On(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=tr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=tr(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Ei(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Ei(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&vp(s.group,s.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===s.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===s.normalizedSessionSearchQuery&&e.hideDirectoryControls===s.hideDirectoryControls&&e.collapsedFolderIds===s.collapsedFolderIds&&e.toggleFolderCollapse===s.toggleFolderCollapse&&e.renameFolder===s.renameFolder&&e.deleteFolder===s.deleteFolder&&e.showDeletionDialog===s.showDeletionDialog&&e.setDeleteFolderConfirm===s.setDeleteFolderConfirm&&e.renderSessionNode===s.renderSessionNode&&e.showMoreGroupSessions===s.showMoreGroupSessions&&e.resetGroupSessionLimit===s.resetGroupSessionLimit&&e.mobileVariant===s.mobileVariant&&e.alwaysShowActions===s.alwaysShowActions&&e.activeProjectId===s.activeProjectId&&e.setActiveProjectIdOnly===s.setActiveProjectIdOnly&&e.setActiveMainTab===s.setActiveMainTab&&e.setSessionSwitcherOpen===s.setSessionSwitcherOpen&&e.openNewSessionDraft===s.openNewSessionDraft&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.renamingFolderId===s.renamingFolderId&&e.renameFolderDraft===s.renameFolderDraft&&e.setRenameFolderDraft===s.setRenameFolderDraft&&e.setRenamingFolderId===s.setRenamingFolderId&&e.onToggleCollapsedGroup===s.onToggleCollapsedGroup&&e.dragHandleProps===s.dragHandleProps&&e.scrollContainerRef===s.scrollContainerRef};function jp(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:b,collapsedFolderIds:h,toggleFolderCollapse:x,renameFolder:y,deleteFolder:f,showDeletionDialog:g,setDeleteFolderConfirm:w,renderSessionNode:v,showMoreGroupSessions:D,resetGroupSessionLimit:S,mobileVariant:m,alwaysShowActions:p,activeProjectId:N,setActiveProjectIdOnly:T,setActiveMainTab:A,setSessionSwitcherOpen:P,openNewSessionDraft:E,addSessionToFolder:R,createFolderAndStartRename:L,renamingFolderId:Y,renameFolderDraft:X,setRenameFolderDraft:oe,setRenamingFolderId:$,pinnedSessionIds:H,expandedParents:B,sessionOrderIndex:O,editingId:J,openSidebarMenuKey:de,activeActivitySessionIds:G,unreadActivitySessionIds:Ce,notifyOnSubtasks:Me,onToggleCollapsedGroup:He,dragHandleProps:ze,compactBodyPadding:Be=!1,scrollContainerRef:Pe}=e,te=o.useCallback((U,Z)=>{const ne=O.get(U.session.id),ce=O.get(Z.session.id);if(ne!==void 0||ce!==void 0){if(ne===void 0)return 1;if(ce===void 0)return-1;if(ne!==ce)return ne-ce}return Jn(U.session,Z.session,H,ya)},[H,O]),xe=a?c.get(s):null,Ge=$t(U=>U.foldersMap),Ne=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const U=yt(s.directory??null),Z=s.branch?.trim();return U&&Z?al():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const ye=va(),Ae=o.useMemo(()=>{const U=s.folderScopes?.map(Z=>yt(Z.directory))??[yt(s.directory??null)];return[...new Set(U.filter(Z=>!!Z))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(U=>Ae.length>0?ye.subscribeBootstrap(U):()=>{},[Ae.length,ye]),o.useCallback(()=>Ae.map(U=>`${U}\0${ye.getBootstrapState(U)??""}\0${ye.getBootstrapFailure(U)??""}`).join(""),[Ae,ye]),o.useCallback(()=>"",[]));const ot=Ae.some(U=>{const Z=ye.getBootstrapState(U);return Z==="queued"||Z==="running"}),We=Ae.find(U=>ye.getBootstrapState(U)==="failed")??null,Q=We?ye.getBootstrapFailure(We):void 0,V=Q==="os-permission"&&bo(),[pe,q]=o.useState(!1),ve=o.useCallback(()=>{We&&ye.requestBootstrap({directory:We,priority:Ne?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[ye,We,s.isMain,Ne]),we=o.useCallback(async()=>{if(!(!We||!V||pe)){q(!0);try{(await yo(We)).success&&ve()}finally{q(!1)}}},[V,We,pe,ve]),Re=b?10:5,qe=Math.max(Re,d??Re),at=a?xe?.groupMatches===!0:!1,mt=a,Le=o.useMemo(()=>[...mt?xe?.filteredNodes??[]:s.sessions].sort(te),[te,s.sessions,xe?.filteredNodes,mt]),ke=s.folderScopeKey??yt(s.directory??null),Ye=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:ke?[{scopeKey:ke,directory:s.directory??null}]:[],[ke,s.directory,s.folderScopes]),pt=o.useMemo(()=>Ye.flatMap(({scopeKey:U,directory:Z})=>(Ge[U]??[]).map(ne=>({folder:ne,scopeKey:U,scopeDirectory:Z}))),[Ye,Ge]),kt=o.useMemo(()=>{const U=new Map,Z=ne=>{ne.forEach(ce=>{U.set(ce.session.id,ce),ce.children.length>0&&Z(ce.children)})};return Z(Le),U},[Le]),bt=o.useMemo(()=>pt.map(({folder:U,scopeKey:Z,scopeDirectory:ne})=>{const ce=fp(U.sessionIds,kt).sort(te);return{folder:U,scopeKey:Z,scopeDirectory:ne,nodes:ce}}),[pt,kt,te]),_=o.useMemo(()=>{const U=new Map(bt.map(he=>[he.folder.id,he])),Z=new Map;for(const{folder:he}of bt){if(!he.parentId)continue;const ht=Z.get(he.parentId);ht?ht.push(he.id):Z.set(he.parentId,[he.id])}const ne=new Map,ce=he=>{const ht=ne.get(he);if(ht!==void 0)return ht;const wt=U.get(he);if(!wt)return ne.set(he,!1),!1;const Dt=Z.get(he)??[];if(s.isArchivedBucket&&wt.nodes.length===0){const Pt=Dt.some(ls=>ce(ls));return ne.set(he,Pt),Pt}if(!a||wt.folder.name.toLowerCase().includes(l)||wt.nodes.length>0)return ne.set(he,!0),!0;const rs=Dt.some(Pt=>ce(Pt));return ne.set(he,rs),rs};return bt.filter(({folder:he})=>ce(he.id))},[bt,s.isArchivedBucket,a,l]),be=o.useMemo(()=>new Set(_.flatMap(U=>U.folder.sessionIds)),[_]),Ie=o.useMemo(()=>Le.filter(U=>!be.has(U.session.id)),[Le,be]),C=o.useMemo(()=>_.filter(({folder:U})=>!U.parentId),[_]),K=o.useMemo(()=>{const U=new Map;return _.forEach(Z=>{if(!Z.folder.parentId)return;const ne=U.get(Z.folder.parentId)??[];ne.push(Z),U.set(Z.folder.parentId,ne)}),U},[_]),ee=o.useMemo(()=>{const U=new Map(_.map(ce=>[ce.folder.id,ce])),Z=new Map,ne=(ce,he)=>{const ht=Z.get(ce);if(ht!==void 0)return ht;if(he.has(ce))return null;he.add(ce);const wt=U.get(ce);let Dt=wt?Ti(wt.nodes,G,Ce,Me):null;for(const Kt of K.get(ce)??[])if(Dt=No(Dt,ne(Kt.folder.id,he)),Dt==="active")break;return Z.set(ce,Dt),Dt};return _.forEach(({folder:ce})=>ne(ce.id,new Set)),Z},[G,_,K,Me,Ce]),ue="project",me=o.useMemo(()=>{const U=new Set;return Ii(Le,J,U),_.forEach(({nodes:Z})=>{Ii(Z,J,U)}),U},[Le,_,J]),Se=o.useMemo(()=>{if(!de)return null;const U=tr(Le,de,ue,!!s.isArchivedBucket);if(U)return U;for(const{nodes:Z}of _){const ne=tr(Z,de,ue,!!s.isArchivedBucket);if(ne)return ne}return null},[de,Le,_,s.isArchivedBucket]),Ve=o.useCallback(U=>{const Z=new WeakMap,ne=ce=>{Z.set(ce,io(ce));for(const he of ce.children)ne(he)};return U.forEach(ne),Z},[]),ft=o.useMemo(()=>Ve(Le),[Ve,Le]),lt=o.useMemo(()=>{const U=new WeakMap;return _.forEach(({nodes:Z})=>{Z.forEach(ne=>U.set(ne,io(ne)))}),U},[_]),it=o.useCallback(U=>ft.get(U)??lt.get(U)??"",[ft,lt]),gt=o.useCallback(U=>({subtreeContainsEditing:me,menuOpenSessionId:Se,nodeStructureKey:it(U)}),[me,Se,it]),Xe=Ie.length,Oe=s.isArchivedBucket||a?Ie:Ie.slice(0,qe),Ze=Xe-Oe.length,vt=!s.isArchivedBucket&&!a&&Xe>Re&&Ze===0,Ot=s.isArchivedBucket===!0&&!a&&Oe.length>=gp,Et=s.isArchivedBucket?"archived":"active",jt=Ot&&Oe.some(U=>{if(U.children.length===0)return!1;const Z=`project:${Et}:${U.session.id}`;return B.has(Z)}),M=o.useRef(null),[De,Fe]=o.useState(null),[Je,dt]=o.useState(0),[,Rt]=o.useState(0);o.useEffect(()=>{if(!Ot)return;const U=M.current;if(!U||typeof ResizeObserver>"u")return;const Z=new ResizeObserver(()=>Rt(ne=>ne+1));return Z.observe(U),()=>Z.disconnect()},[Ot]),o.useLayoutEffect(()=>{if(!Ot){De!==null&&Fe(null),Je!==0&&dt(0);return}const U=M.current;if(!U)return;let Z=De;const ne=Pe?.current??null;if(ne&&ne.contains(U)){if(Z=ne,Z!==De){Fe(Z);return}}else if(!Z||!Z.contains(U)){let he=U.parentElement;for(;he;){const ht=window.getComputedStyle(he);if(ht.overflowY==="auto"||ht.overflowY==="scroll"){Z=he;break}he=he.parentElement}if(Z!==De){Fe(Z);return}}if(!Z)return;const ce=U.getBoundingClientRect().top-Z.getBoundingClientRect().top+Z.scrollTop;dt(he=>Math.abs(he-ce)<1?he:ce)});const z=Ot&&De!==null,ie=Gu({count:Oe.length,enabled:z,getScrollElement:()=>De,initialOffset:()=>De?.scrollTop??0,estimateSize:()=>xp,overscan:jt?20:8,scrollMargin:Je,getItemKey:U=>Oe[U]?.session.id??U}),ge=o.useCallback(U=>{const Z=[],ne=ce=>{ce.forEach(he=>{Z.push(he.session),he.children.length>0&&ne(he.children)})};return ne(U),Z},[]),et=o.useMemo(()=>ge(Le),[ge,Le]),je=o.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const U=new Map,Z=new Map;for(const{folder:ce}of _){if(!ce.parentId)continue;const he=Z.get(ce.parentId)??[];he.push(ce.id),Z.set(ce.parentId,he)}const ne=(ce,he)=>{if(he.has(ce))return[];he.add(ce);const ht=_.find(({folder:Kt})=>Kt.id===ce),wt=ht?ge(ht.nodes):[],Dt=Z.get(ce)??[];for(const Kt of Dt)wt.push(...ne(Kt,he));return wt};for(const{folder:ce}of _)U.set(ce.id,ne(ce.id,new Set));return U},[_,ge,s.isArchivedBucket]);if(a&&!at&&C.length===0&&Ie.length===0)return null;const $e=!s.isMain&&!!s.branch,ct=s.branch&&ud(s.branch,s.label)?{label:s.branch}:null,At=Ne?Ti(Le,G,Ce,Me):null,_t=At?t.jsx(ol,{state:At,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Mt=(U,Z)=>{const{folder:ne,scopeKey:ce,scopeDirectory:he,nodes:ht}=U,wt=je.get(ne.id)??[],Dt=a?!1:h.has(ne.id);return t.jsx(cp,{folderId:ne.id,children:(Kt,rs)=>t.jsx(ap,{folder:ne,displayName:Z,sessions:ht,isCollapsed:Dt,collapsedActivityState:Dt?ee.get(ne.id)??null:null,onToggle:()=>x(ne.id),onRename:Pt=>{y(ce,ne.id,Pt)},onDelete:()=>{if(s.isArchivedBucket){_s.requestDelete({sessions:wt,mode:"session"});return}if(!g){f(ce,ne.id);return}const Pt=_.filter(({folder:cs})=>cs.parentId===ne.id).length,ls=ht.length;w({scopeKey:ce,folderId:ne.id,folderName:ne.name,subFolderCount:Pt,sessionCount:ls})},renderSessionNode:v,getRenderExtras:it?Pt=>({subtreeContainsEditing:me,menuOpenSessionId:Se,nodeStructureKey:it(Pt),childRenderExtrasFor:gt}):void 0,groupDirectory:he??s.directory,projectId:r,mobileVariant:m,alwaysShowActions:p,isRenaming:Y===ne.id,renameDraft:Y===ne.id?X:void 0,onRenameDraftChange:Pt=>oe(Pt),onRenameSave:()=>{const Pt=X.trim();Pt&&y(ce,ne.id,Pt),$(null),oe("")},onRenameCancel:()=>{$(null),oe("")},droppableRef:Kt,isDropTarget:rs,depth:0,onNewSession:()=>{r&&r!==N&&T(r),A("chat"),m&&P(!1),E({selectedProjectId:r,directoryOverride:he??s.directory,targetFolderId:ne.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},ne.id)},Zt=()=>{const U=new Map;for(const ce of _){const he=ce.folder.parentId;if(!he)continue;const ht=U.get(he);ht?ht.push(ce):U.set(he,[ce])}const Z=[],ne=(ce,he)=>{const ht=he?`${he} / ${ce.folder.name}`:ce.folder.name;Z.push(Mt(ce,ht)),!(!a&&h.has(ce.folder.id))&&(U.get(ce.folder.id)??[]).forEach(Dt=>ne(Dt,ht))};return C.forEach(ce=>ne(ce,"")),Z},qt=p?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",Nt=We?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[Q==="os-permission"?"Folder access is required.":"Could not refresh sessions.",V?t.jsx(Qe,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:pe,onClick:()=>{we()},children:"Grant access"}):null,t.jsx(Qe,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:ve,children:"Try again"})]}):null,Bt=t.jsxs(dp,{scopeKey:Ye[0]?.scopeKey??ke,hasFolders:_.length>0,onSessionDroppedOnFolder:(U,Z)=>{const ne=_.find(({folder:he})=>he.id===Z);if(!ne)return;const ce=$t.getState();for(const{scopeKey:he}of Ye)he!==ne.scopeKey&&ce.getSessionFolderId(he,U)&&ce.removeSessionFromFolder(he,U);R(ne.scopeKey,Z,U)},children:[Zt(),Ot?t.jsx("div",{ref:M,children:z?t.jsx("div",{style:{height:ie.getTotalSize(),position:"relative"},children:ie.getVirtualItems().map(U=>{const Z=Oe[U.index];return Z?t.jsx("div",{"data-index":U.index,ref:ie.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${U.start-Je}px)`},children:v(Z,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:me,menuOpenSessionId:Se,nodeStructureKey:it(Z),childRenderExtrasFor:gt})},Z.session.id):null})}):Oe.map(U=>t.jsx(o.Fragment,{children:v(U,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:me,menuOpenSessionId:Se,nodeStructureKey:it(U),childRenderExtrasFor:gt})},U.session.id))}):Oe.map(U=>t.jsx(o.Fragment,{children:v(U,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:me,menuOpenSessionId:Se,nodeStructureKey:it(U),childRenderExtrasFor:gt})},U.session.id)),Xe===0&&_.length===0?s.isArchivedBucket?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):ot?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):Nt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:Nt}):t.jsx(Os,{icon:"chat-new",onClick:()=>{E({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,Xe>0&&Nt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:Nt}):null,Ze>0?t.jsx(Os,{icon:"arrow-down-s",onClick:()=>D(n,Oe.length),children:Ze===1?"Show 1 more session":`Show ${Ze} more sessions`}):null,vt?t.jsx(Os,{icon:"arrow-up-s",onClick:()=>S(n),children:"Show fewer sessions"}):null]});return i?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Bt})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:F("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>He(n),role:"button",tabIndex:0,onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),He(n))},"aria-label":Ne?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!Ne,children:[t.jsx("div",{ref:ze?.setActivatorNodeRef,className:F("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",qt),...ze?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:s.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"archive",className:F("size-4 shrink-0 text-muted-foreground",p?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",p?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ne?t.jsx(k,{name:"arrow-right-s",className:"size-4"}):t.jsx(k,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:Yn(s.label,l)}),_t]}):!s.isMain||s.worktree?t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"git-branch",className:F("size-4 shrink-0","text-muted-foreground",p?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",p?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ne?t.jsx(k,{name:"arrow-right-s",className:"size-4"}):t.jsx(k,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Yn(s.label,l)}),_t,null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:Yn(s.label,l)}),_t]})}),$e&&ct?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.isArchivedBucket?t.jsx(k,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(k,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),t.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:ct.label})]}):null]})}),s.isArchivedBucket&&et.length>0?t.jsx("div",{className:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",p?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),_s.requestDelete({sessions:et,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${s.label}`,children:t.jsx(k,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?t.jsx("div",{className:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",p?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),r&&r!==N&&T(r),A("chat"),m&&P(!1),E({selectedProjectId:r,directoryOverride:s.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${s.label}`,children:t.jsx(k,{name:"add",className:"h-4 w-4"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]}),Ne?null:t.jsx("div",{className:"oc-group-body",children:Bt})]})}const Cp=o.memo(jp,Sp);function kp(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:b,setIsSessionSearchOpen:h,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:f,hasSessionSearchQuery:g,searchMatchCount:w,selectionModeEnabled:v,onToggleSelectionMode:D,mobileVariant:S=!1}=e;if(s)return null;const m=F(u,"text-muted-foreground hover:text-foreground",!S&&"hover:bg-transparent");return t.jsx("div",{className:F("select-none flex-shrink-0",S?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:F("flex flex-col",S?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:F("flex items-center justify-between",S?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:F("flex min-w-0 items-center",S?"gap-0.5 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":S?"true":void 0,children:[i?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:m,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,a?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:m,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(k,{name:"server",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:m,"aria-label":"Update",children:t.jsx(k,{name:"download",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:m,"aria-label":"Add project",children:t.jsx(k,{name:"folder-add",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:m,"aria-label":"Archive",children:t.jsx(k,{name:"archive",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:F("flex shrink-0 items-center",S?"gap-0.5":"gap-1.5"),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>h(p=>!p),className:m,"aria-label":"Search sessions","aria-expanded":b,children:t.jsx(k,{name:"search",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:D,className:F(m,v&&"bg-interactive-hover text-primary"),"aria-label":v?"Exit selection":"Select sessions","aria-pressed":v,children:t.jsx(k,{name:"checkbox-multiple",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:v?"Exit selection":"Select sessions"})})]})]})]}),b?t.jsxs("div",{className:F(S?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:g?t.jsx("span",{children:w===1?`${w} match`:`${w} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",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",{ref:x,value:y,onChange:p=>f(p.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:p=>{p.key==="Escape"&&(p.stopPropagation(),g?f(""):h(!1))}}),y.length>0?t.jsx("button",{type:"button",onClick:()=>f(""),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 hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Np(e){const s=re(i=>i.toggleSidebar),n=re(i=>i.shortcutOverrides),r=po(fn("toggle_sidebar",n));return t.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${ti})`}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${ti})))`}}),t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:F("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),children:[t.jsx(k,{name:"chat-new",className:F(Kn,"text-current")}),t.jsx("span",{className:ba,children:"New session"})]}),e.showSidebarToggle?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:t.jsx(k,{name:"layout-left",className:"size-4"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Ap=500,ao=(e,s)=>F("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),Ip=({project:e,label:s,isSelected:n,hasActive:r,canDrag:i,onSelect:a,onOpenProjectEditDialog:l,onRemoveProject:c,mobileVariant:d=!1})=>{const{listeners:u,setNodeRef:b,transform:h,transition:x,isDragging:y}=dr({id:e.id,disabled:!i}),[f,g]=o.useState(!1),w=o.useRef(null),v=o.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);o.useEffect(()=>()=>v(),[v]);const D=o.useCallback(()=>{v(),w.current=window.setTimeout(()=>{w.current=null,g(!0)},Ap)},[v]);return t.jsx("div",{ref:b,style:{transform:ur.Translate.toString(h),transition:x},className:F(y&&"opacity-60"),children:t.jsxs(eh,{open:f,onOpenChange:g,children:[t.jsxs(th,{render:t.jsx("button",{type:"button",onClick:()=>{f||a()},onTouchStart:D,onTouchMove:v,onTouchEnd:v,onTouchCancel:v,style:{touchAction:"manipulation"},className:ao(d,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:F("inline-flex size-4 shrink-0 items-center justify-center",i&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":i?`Reorder ${s}`:void 0,...i?u:{},children:t.jsx(k,{name:"folder",className:F(xn(d),"text-muted-foreground")})}),t.jsx("span",{className:bn(d),children:s})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(rr,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsxs(sh,{className:"min-w-[160px]",children:[t.jsxs(yi,{onClick:()=>l(e.id),children:[t.jsx(k,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(nh,{}),t.jsxs(yi,{onClick:()=>c(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},Dp=({projects:e,selectedProjectId:s,onSelectProject:n,onOpenDirectoryDialog:r,onOpenProjectEditDialog:i,onRemoveProject:a,hasActiveSessionByProject:l,homeDirectory:c,className:d,mobileVariant:u=!1})=>{const b=s===null,h=Ut(g=>g.reorderProjects),x=e.length>1,y=ar(vn(Yu,{activationConstraint:{distance:8}}),vn(Wu,{activationConstraint:{delay:200,tolerance:6}})),f=o.useCallback(g=>{const{active:w,over:v}=g;if(!v||w.id===v.id)return;const D=Ut.getState().projects,S=D.findIndex(p=>p.id===w.id),m=D.findIndex(p=>p.id===v.id);S<0||m<0||h(S,m)},[h]);return t.jsxs("div",{className:F("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",d),children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:ao(u,b),"aria-pressed":b,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(k,{name:"folder",className:xn(u)}),t.jsx("span",{className:bn(u),children:"All Folders"})]})}),t.jsx(lr,{sensors:y,collisionDetection:cr,onDragEnd:f,children:t.jsx(So,{items:e.map(g=>g.id),strategy:Ba,children:e.map(g=>{const w=s===g.id,v=or(g.label?.trim()||Bs(g.normalizedPath,c)||g.normalizedPath);return t.jsx(Ip,{project:g,label:v,isSelected:w,hasActive:l?.(g.id),canDrag:x,onSelect:()=>n(w?null:g.id),onOpenProjectEditDialog:i,onRemoveProject:a,mobileVariant:u},g.id)})})}),t.jsxs("button",{type:"button",onClick:r,className:ao(u,!1),children:[t.jsx(k,{name:"add",className:xn(u)}),t.jsx("span",{className:bn(u),children:"Add folder"})]})]})},kr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function Pp({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:i=!0,showUpdateButton:a=!0}){return!i&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[i?t.jsxs(t.Fragment,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:kr,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:kr,"aria-label":"Shortcuts",children:t.jsx(k,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:kr,"aria-label":"About PiChamber",children:t.jsx(k,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Qe,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const Tp=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Ri=ws()(vo(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(s=>({stickyZoneHeaders:!s.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:s=>e({showRecentSection:s}),setShowArchivedSessions:s=>e({showArchivedSessions:s}),toggleRecentSection:()=>e(s=>({showRecentSection:!s.showRecentSection})),toggleArchivedSessions:()=>e(s=>({showArchivedSessions:!s.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:Tp})),Ep=({projectLabel:e,isCollapsed:s,alwaysShowActions:n=!1,mobileVariant:r=!1})=>{const i=s!==void 0,a=i?n?"hidden":"group-hover/project:hidden group-focus-within/project:hidden":void 0,l=xn(r),c=bn(r);return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:F("inline-flex shrink-0 items-center justify-center",l),children:[i?t.jsx("span",{className:F("items-center justify-center text-muted-foreground",l,n?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:t.jsx(k,{name:s?"arrow-right-s":"arrow-down-s",className:l})}):null,t.jsx(k,{name:"folder",className:F(l,"text-muted-foreground/80",a)})]}),t.jsx("span",{className:F(c,"text-foreground"),children:e})]})},Rp=({id:e,disabled:s=!1,children:n})=>{const{listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=dr({id:e,disabled:s}),u=o.useMemo(()=>({listeners:r,setActivatorNodeRef:a}),[r,a]);return t.jsx("div",{ref:i,style:{transform:ur.Transform.toString(l),transition:c},className:F("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};o.memo(Rp);const Mp=48,Fp=32,Lp=24,Mi=(e,s)=>or(e.label?.trim()||Bs(e.normalizedPath,s)||e.normalizedPath);function Op(e){as("ui.sidebar_projects_list.render");const s=e.isDesktopShellRuntime&&e.stickyZoneHeaders,n=o.useRef(new Map),r=o.useRef(e.getOrderedGroups);r.current!==e.getOrderedGroups&&(r.current=e.getOrderedGroups,n.current.clear());const i=(D,S)=>{const m=n.current,p=m.get(D);if(p&&p.groups===S)return p.ordered;const N=e.getOrderedGroups(D,S);if(m.set(D,{groups:S,ordered:N}),m.size>256){const T=m.keys().next().value;T!==void 0&&m.delete(T)}return N},a=o.useRef(null),l=o.useRef(0),c=o.useCallback(D=>{const m=D.scrollTop>1?Math.min(Fp+D.scrollTop,Mp):0;l.current=m,D.style.setProperty("--scroll-shadow-top-size",`${m}px`),D.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(m-8,0),Lp)}px`)},[]),d=o.useCallback(D=>{D.target.closest("[data-overlay-scrollbar-thumb], [data-sidebar-sticky-header]")||D.clientY-D.currentTarget.getBoundingClientRect().top>=l.current||(D.preventDefault(),D.stopPropagation())},[]),u=e.projectSections.length>0&&e.sectionsForRender.length>0;o.useLayoutEffect(()=>{s&&u&&a.current&&c(a.current)},[s,u,c]);let b=null;for(const D of e.projectSections)e.stuckProjectHeaders.has(D.project.id)&&(b=D.project);const h=b??(e.hasSharedSessions?null:e.sectionsForRender[0]?.project??null),x=h?Mi(h,e.homeDirectory):null,y=o.useMemo(()=>{if(!e.isAllFoldersView)return[];const D=[];for(const S of e.sectionsForRender){const m=Mi(S.project,e.homeDirectory);for(const p of S.groups)if(!p.isArchivedBucket)for(const N of p.sessions){const T=!!e.pinnedSessionIds?.has(N.session.id),A=N.session.time?.updated||N.session.time?.created||0;D.push({node:N,project:S.project,projectLabel:m,isPinned:T,timestamp:A})}}return D.sort((S,m)=>S.isPinned!==m.isPinned?S.isPinned?-1:1:m.timestamp-S.timestamp),D},[e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[f,g]=o.useState(30);o.useEffect(()=>{g(30)},[e.hasSessionSearchQuery]);const w=y.slice(0,f),v=y.length-w.length;return e.sharedSessionsOnly?t.jsx(Fs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})}):e.projectSections.length===0?t.jsx(Fs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0?t.jsx(Fs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsxs("div",{className:"oc-sticky-fade-root relative flex min-h-0 flex-1",onPointerDownCapture:s?d:void 0,onClickCapture:s?d:void 0,onContextMenuCapture:s?d:void 0,children:[t.jsx(Fs,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!s,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("oc-sidebar-scroller oc-sticky-fade-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-20"),style:s?{"--scroll-shadow-top-size":"0px"}:void 0,onScroll:s?D=>c(D.currentTarget):void 0,children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.showOnlyMainWorkspace?t.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const D=e.sectionsForRender.find(N=>N.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!D)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const S=D.groups.find(N=>N.isMain&&N.sessions.length>0)??D.groups.find(N=>N.sessions.length>0)??D.groups.find(N=>N.isMain)??D.groups[0];if(!S)return t.jsx(Os,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:D.project.id,directoryOverride:D.project.normalizedPath}),children:"New session"});const m=D.groups.find(N=>N.isArchivedBucket);return[S,...m&&m.id!==S.id?[m]:[]].map(N=>{const T=`${D.project.id}:${N.id}`,A=N.id===S.id;return t.jsx(o.Fragment,{children:e.renderGroupSessions(N,T,D.project.id,A,null,!0,a)},T)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:y.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[w.map(({node:D,project:S,projectLabel:m})=>{const p=D.session.directory??S.normalizedPath;return t.jsx(o.Fragment,{children:e.renderSessionNode(D,0,p,S.id,!1,{projectLabel:m,showFolderLabel:!0},"project")},D.session.id)}),v>0?t.jsx(Os,{icon:"arrow-down-s",onClick:()=>g(D=>D+30),children:v===1?"Show 1 more session":`Show ${v} more sessions`}):null,f>30&&y.length>30?t.jsx(Os,{icon:"arrow-up-s",onClick:()=>g(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(D=>{const S=D.project.id,m=i(S,D.groups),p=m.find(T=>T.isMain)??null,N=p?m.filter(T=>T.id!==p.id):m;return t.jsxs("div",{children:[p?e.renderGroupSessions(p,`${S}:${p.id}`,S,!0,null,void 0,a):null,N.map(T=>{const A=`${S}:${T.id}`;return t.jsx(o.Fragment,{children:e.renderGroupSessions(T,A,S,!1,null,void 0,a)},T.id)})]},S)})})]})}),s&&h&&x?t.jsx("div",{className:"oc-sticky-fade-overlay pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center gap-1.5 py-1 px-3","aria-hidden":"true",children:t.jsx(Ep,{id:h.id,projectLabel:x,mobileVariant:e.mobileVariant})}):null]})}const Bp=o.memo(Op);function _p(e){if(typeof e!="number"||!Number.isFinite(e))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),i=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${i}, ${a}:${l}`}function zp(e){if(e.info.role==="user")return"";const s=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return s&&n?`${s}/${n}`:n||s}function Up(e){const s=e.info.role==="user"?"User":"Assistant",n=_p(e.info.time?.created),r=zp(e),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
13
-
14
- *${i}*`:`**${s}**`}function $p(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function cl(e){const s=Up(e),n=$p(e.parts).trim();return n?`${s}
15
-
16
- ${n}`:""}function dl(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",i=`${n} Sub-agent: ${e.title}${r}
17
-
18
- ---
19
-
20
- `,a=e.records.map(cl).filter(Boolean).join(`
21
-
22
- ---
23
-
24
- `),l=[i+a];for(const c of e.children)l.push(dl(c,s+1));return l.join(`
25
-
26
- ---
27
-
28
- `)}function ul(e,s,n){const r=s?.trim()||"Session",i=new Date().toISOString().split("T")[0],a=`# ${r}
29
-
30
- *Exported on ${i}*
31
-
32
- ---
33
-
34
- `,l=e.map(cl).filter(Boolean).join(`
35
-
36
- ---
37
-
38
- `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>dl(u,1)).join(`
39
-
40
- ---
41
-
42
- `);c+=`
43
-
44
- ---
45
-
46
- `+d}return c}function fl(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=s,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}async function hl(e,s){const n=await ju(s,e);return n||null}async function Gp(e){const s=xo()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await Cu(e)?!0:Ia(e)}function Kp(){return fd()}function pl(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",i=new Date().toISOString().split("T")[0];return`${r}-${i}.md`}const Hp=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const i of e){r.has(i)||(r.add(i),n.push(i));const a=s.get(i);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},Gt=ws()((e,s)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{s().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{s().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,i)=>{const a=s(),l=new Set(a.selectedIds);let c=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const b=i&&i.length>0?[n,...i]:[n];if(l.has(n)){for(const x of b)l.delete(x);d===n&&(d=null)}else{for(const x of b)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,i,a,l)=>{const c=s();if(i.length===0)return;const d=n&&i.includes(n)?n:i[0],u=i.indexOf(d),b=i.indexOf(r);if(u<0||b<0)return;const[h,x]=u<=b?[u,b]:[b,u],y=i.slice(h,x+1),f=Hp(y,l),w=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const v of f)w.add(v);e({selectedIds:w,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const i=new Set(r.selectedIds);for(const a of n)i.delete(a);i.size!==r.selectedIds.size&&(i.size===0?e({selectedIds:i,scopeKey:null,anchorId:null}):e({selectedIds:i}))}}));let lo=!1;const co=new Set;let Fi=!1;function Wp(){for(const e of co)e()}function Ao(e){lo!==e&&(lo=e,Wp())}function Yp(e){e.key==="Shift"&&Ao(!0)}function Vp(e){e.key==="Shift"&&Ao(!1)}function qp(){Ao(!1)}function Qp(){Fi||typeof window>"u"||(Fi=!0,window.addEventListener("keydown",Yp),window.addEventListener("keyup",Vp),window.addEventListener("blur",qp))}function Jp(e){return Qp(),co.add(e),()=>{co.delete(e)}}function Xp(){return lo}function Zp(){return!1}function em(){return Ke.useSyncExternalStore(Jp,Xp,Zp)}const Nr=new WeakMap,tm=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;Nr.get(n)?.();const r=s.getBoundingClientRect().top;let i=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,Nr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const u=s.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,as("ui.sidebar.selection_scroll_anchor_adjustment")),i-=1,i<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Nr.set(n,c),l=window.requestAnimationFrame(d)},sm=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=em(),b=u?n:s,h=x=>{if(u||x.shiftKey){d(x);return}c(x)};return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":b,onPointerDown:a,onMouseDown:l,onClick:h,onKeyDown:x=>x.stopPropagation(),children:t.jsx(k,{name:u?"delete-bin":"archive",className:i})})}),t.jsx(rt,{side:"left",sideOffset:8,children:b})]})});function nm(e){as("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:i,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:b,editingId:h,setEditingId:x,editTitle:y,setEditTitle:f,handleSaveEdit:g,handleCancelEdit:w,toggleParent:v,handleSessionSelect:D,handleSessionDoubleClick:S,togglePinnedSession:m,handleShareSession:p,copiedSessionId:N,handleCopyShareUrl:T,handleCopySessionId:A,handleUnshareSession:P,openSidebarMenuKey:E,setOpenSidebarMenuKey:R,renamingFolderId:L,getFoldersForScope:Y,getSessionFolderId:X,removeSessionFromFolder:oe,addSessionToFolder:$,createFolderAndStartRename:H,openContextPanelTab:B,handleDeleteSession:O,handleRestoreSession:J,mobileVariant:de,alwaysShowActions:G,renderSessionNode:Ce,secondaryMeta:Me,renderContext:He="project",subtreeContainsEditing:ze,menuOpenSessionId:Be,childRenderExtrasFor:Pe}=e,te=o.useMemo(()=>Da(),[]),xe=!a&&!de,Ge=o.useRef(!1),Ne=o.useRef(h);Ne.current=h;const ye=o.useRef(null),Ae=o.useRef(g);Ae.current=g;const[ot,We]=o.useState(y),Q=o.useRef(ot);Q.current=ot;const V=o.useRef(null),pe=o.useRef(null),q=s.session,ve=q,we=yt(q.directory??null)??yt(r??null),Re=_e(W=>W.currentSessionId===q.id),qe=wa(we),at=hd(we),mt=Ut(o.useCallback(W=>{if(Me?.projectLabel||!i)return null;const Ue=W.projects.find(ut=>ut.id===i);return Ue?Ue.label?.trim()||Bs(yt(Ue.path)??Ue.path,null)||Ue.path:null},[i,Me?.projectLabel])),Le=Me?.projectLabel??(mt?or(mt):null),ke=Me?.branchLabel??s.worktree?.branch??(qe&&qe!=="HEAD"?qe:null),Ye=ke,pt=at===!0||!!(ke||s.worktree),kt=s.children.length,bt=ve.agent;o.useMemo(()=>{const W=s.worktree?.branch?.trim()||ke?.trim(),Ue=yt(s.worktree?.path??we);return W&&Ue?al():null},[s.worktree,ke,we]);const _=mp();o.useMemo(()=>null,[_]);const be=i??we??null,Ie=ja(),C=mo(),K=Gt(W=>W.enabled),ee=Gt(o.useCallback(W=>W.selectedIds.has(q.id),[q.id])),ue=Gt(W=>W.toggleSelected),me=Gt(W=>W.setRange),Se=o.useCallback(W=>{const Ue=[],ut=St=>{St.children.forEach(Tt=>{Ue.push(Tt.session.id),ut(Tt)})};return ut(W),Ue},[]);o.useCallback(W=>{const Ue=[],ut=St=>{St.children.forEach(Tt=>{Ue.push(Tt.session),ut(Tt)})};return ut(W),Ue},[]);const[Ve,ft]=o.useState(!1),[lt,it]=o.useState(!0),gt=`${He}:${a?"archived":"active"}:${q.id}`,Xe=pd(o.useCallback(W=>!!W.sessionMemoryState.get(md(q.id))?.isZombie,[q.id])),Ze=Sa(q.id)?.type??"idle",vt=Ze==="busy"||Ze==="retry",Ot=gd(q.id,vt),Et=xd(q.id),jt=ve.title||"Untitled Session",M=s.children.length>0,De=bd(l,we,q.id),Fe=gt,Je=d?!0:c.has(Fe);o.useMemo(()=>up(s,Je,we),[Je,s,we]);const dt=jd(),Rt=!!ve.parentID,ie=yd(q.id)>0&&(!Rt||b),ge=ve.time?.updated||ve.time?.created||Date.now(),et=Cd(ge),[je,$e]=o.useState(!1),ct=o.useMemo(()=>Se(s).length,[Se,s]),At=o.useCallback(async W=>{const Ue=[];let ut=0;for(const St of W)try{if(!we)throw new Error("Session directory is required for export");await C.loadCompleteHistory?.(St.session.id,we);const Tt=Kr(Ie.getState(),St.session.id).list,Qt=St.session.title||"Untitled Sub-agent",es=St.session.agent,ts=await At(St.children);ut+=ts.skipped,Ue.push({title:Qt,agent:es,records:Tt,children:ts.children})}catch{ut+=Se(St).length+1}return{children:Ue,skipped:ut}},[Se,Ie,we,C]),_t=o.useCallback(W=>{W<=0||le.warning(W===1?`Exported session, but skipped ${W} sub-agent task that could not be loaded.`:`Exported session, but skipped ${W} sub-agent tasks that could not be loaded.`)},[]),Mt=o.useCallback(async W=>{if(!we){le.error("Nothing to export");return}try{await C.loadCompleteHistory?.(q.id,we)}catch{le.error("Failed to load the complete session history");return}const Ue=Kr(Ie.getState(),q.id).list;if(Ue.length===0){le.error("Nothing to export");return}let ut,St=0;if(W&&s.children.length>0){const ts=await At(s.children);ut=ts.children,St=ts.skipped}const Tt=ul(Ue,ve.title??null,ut),Qt=pl(ve.title??null),es=await hl(Tt,Qt);if(es){le.success("Session exported",{action:{label:Kp(),onClick:()=>{Gp(es).then(ts=>{ts||le.error("Failed to reveal path")})}}}),_t(St);return}fl(Tt,Qt),le.success("Session exported"),_t(St)},[At,Ie,s.children,ve.title,q.id,we,_t,C]),Zt=o.useCallback(async()=>{if(s.children.length>0){it(!0),ft(!0);return}await Mt(!1)},[Mt,s.children.length]),qt=o.useCallback(()=>{we&&hn("desktop_open_session_mini_chat_window",{sessionId:q.id,directory:we,apiBaseUrl:Yr(),clientToken:Wr()}).catch(W=>{console.warn("[session-sidebar] failed to open mini chat window",W)})},[q.id,we]);o.useEffect(()=>{if(h!==q.id)return;const W=Ue=>{const St=Ue.target?.closest?.(`[data-session-rename-form="${CSS.escape(q.id)}"]`);pe.current&&!St&&Ae.current(Q.current)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[h,q.id]),o.useLayoutEffect(()=>{if(h!==q.id){V.current===q.id&&(V.current=null);return}V.current!==q.id&&(V.current=q.id,We(y))},[h,y,q.id]);const Nt=Et.length,Bt=!vt&&ie&&!Re,U=vt&&Ot,Z=De,ne=t.jsx(k,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),ce=Z?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:ne}):null,he=M?t.jsx("button",{type:"button",onClick:W=>{W.stopPropagation(),v(Fe)},onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),W.stopPropagation(),v(Fe))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":Je?"Collapse subsessions":"Expand subsessions",children:Je?t.jsx(k,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(k,{name:"arrow-right-s",className:"h-3 w-3"})}):null,ht=Xe?t.jsx(k,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,wt=W=>{if(!W&&ye.current){const{id:Ue,title:ut}=ye.current;ye.current=null,x(Ue),f(ut)}},Dt=W=>{$e(W)},Kt=W=>{W.preventDefault(),W.stopPropagation()},rs=W=>{W.preventDefault(),W.stopPropagation()},Pt=W=>{W.preventDefault(),W.stopPropagation(),R(null),O(q,{archivedBucket:a})},ls=W=>{W.preventDefault(),W.stopPropagation(),R(null),O(q,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},cs=W=>{if(Ge.current){Ge.current=!1;return}if(K){if(W?.preventDefault(),W?.stopPropagation(),W?.shiftKey){const ut=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Qt=>Qt.getAttribute("data-session-row")).filter(Qt=>typeof Qt=="string"&&Qt.length>0),St=Gt.getState().anchorId,Tt=new Map;Tt.set(q.id,Se(s)),me(St,q.id,ut,be,Tt);return}ue(q.id,be,Se(s));return}W?.currentTarget&&tm(W.currentTarget),D(q.id,we)},os=W=>{W.defaultPrevented||W.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||cs(W)},Ds=W=>{(W.button===2||W.button===0&&W.ctrlKey&&!K)&&(Ge.current=!0)},Ss=({Item:W,Separator:Ue,Sub:ut,SubTrigger:St,SubContent:Tt})=>t.jsxs(t.Fragment,{children:[t.jsxs(W,{onClick:()=>{ye.current={id:q.id,title:jt}},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(W,{onClick:()=>A(q.id),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(W,{onClick:()=>we&&m({directory:we,sessionId:q.id}),className:"[&>svg]:mr-1",children:[De?t.jsx(k,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(k,{name:"pushpin",className:"mr-1 h-4 w-4"}),De?"Unpin session":"Pin session"]}),t.jsxs(W,{onClick:()=>{Zt()},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),t.jsxs(W,{disabled:!we,onClick:()=>{we&&B(we,{mode:"chat",dedupeKey:`session:${q.id}`,label:jt,sessionTitleFallback:jt})},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"chat-4",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Side Panel"}),t.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]}),te?t.jsxs(W,{disabled:!we,onClick:qt,className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(Ue,{}),a?null:t.jsxs(W,{className:"[&>svg]:mr-1",onClick:()=>O(q,{archivedBucket:a}),children:[t.jsx(k,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(W,{className:"[&>svg]:mr-1",onClick:()=>J(q),children:[t.jsx(k,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(W,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>O(q,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(k,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]}),nn=t.jsx(Jr,{children:t.jsx(Xr,{className:"app-region-no-drag z-50",children:t.jsx(Zr,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(L||Ne.current),style:{color:"var(--surface-elevated-foreground)"},className:F(Ur,"min-w-[180px]"),children:Ss({Item:({className:W,...Ue})=>t.jsx(Ma,{className:F(ca,W),...Ue}),Separator:({className:W,...Ue})=>t.jsx(Fa,{className:F(da,W),...Ue}),Sub:zu,SubTrigger:({className:W,children:Ue,...ut})=>t.jsxs(Uu,{className:F(Sd,W),...ut,children:[Ue,t.jsx(k,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:W,children:Ue,...ut})=>t.jsx(Jr,{children:t.jsx(Xr,{className:"app-region-no-drag z-50",children:t.jsx(Zr,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:F(Ur,W),...ut,children:Ue})})})})})})});return t.jsxs(o.Fragment,{children:[t.jsx(lp,{sessionId:q.id,sessionDirectory:we??null,sessionTitle:jt,children:t.jsxs(Ea,{open:je,onOpenChange:Dt,onOpenChangeComplete:wt,children:[t.jsxs(Ra,{render:t.jsx("div",{"data-session-row":q.id,"data-session-scope":be??"","data-session-archived":a?"1":"0",onClick:os,style:n>0?{marginLeft:`${n*14}px`}:void 0,className:F("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",n>0?"bg-secondary/30 hover:bg-interactive-hover":"hover:bg-interactive-hover",Re&&!ee&&"bg-interactive-selection",ee&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[he,ce,h===q.id?t.jsxs("form",{ref:pe,"data-session-rename-form":q.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:W=>W.stopPropagation(),onMouseDown:W=>W.stopPropagation(),onSubmit:W=>{W.preventDefault(),g(ot)},children:[t.jsx("input",{value:ot,onChange:W=>We(W.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:W=>{W.stopPropagation(),W.key==="Escape"&&w()}}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:w,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground 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("button",{type:"button",onMouseDown:Ds,onClick:W=>cs(W),onDoubleClick:W=>{W.stopPropagation(),S(q.id,jt)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:F("block min-w-0 flex-1 truncate font-normal typography-ui-label",ie?"text-foreground":"text-foreground/90"),children:Yn(jt,u)})}),Me?.showFolderLabel&&Le||Ye||pt||_||kt>0||bt&&bt!=="default"||U||Nt>0||dt>0?t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[Me?.showFolderLabel&&Le?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Le}):null,Ye?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(k,{name:"git-branch",className:F("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Ye})]}):pt?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(k,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,kt>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(k,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:kt})]}):null,bt&&bt!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:bt}):null,U?t.jsx(vd,{sessionId:q.id,running:vt,className:"text-muted-foreground/70"}):null,Nt>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(k,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:Nt})]}):null,null]}):null]})]}),De?t.jsx(k,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,t.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[t.jsx("div",{className:F("flex items-center justify-end",xe&&(G||je)?"opacity-0":xe?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:vt?t.jsx(rr,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):Bt?t.jsx(wd,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:et})}),xe?t.jsx("div",{className:F("absolute inset-0 flex items-center justify-end",G||je?"opacity-100":"pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:t.jsx(sm,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Kt,onMouseDown:rs,onArchive:Pt,onDelete:ls})}):null]}),ht&&!de?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:ht}):null]}),nn]})}),M&&Je?s.children.map(W=>{const Ue=Pe?Pe(W):{subtreeContainsEditing:ze,menuOpenSessionId:Be,nodeStructureKey:""};return t.jsx(o.Fragment,{children:Ce(W,n+1,we??r,i,a,void 0,He,Ue)},W.session.id)}):null,t.jsx(fs,{open:Ve,onOpenChange:ft,children:t.jsxs(hs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:"Export Markdown"}),t.jsx($s,{children:ct===1?`This session has ${ct} sub-agent task. Include it in the export?`:`This session has ${ct} sub-agent tasks. Include them in the export?`})]}),t.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:lt,onChange:W=>it(W.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Gs,{children:[t.jsx(Qe,{type:"button",onClick:()=>ft(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Qe,{type:"button",onClick:()=>{ft(!1),Mt(lt)},size:"sm",children:"Export"})]})]})})]},q.id)}const Li=e=>yt(e.session.directory??null),rm=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),om=e=>{if(!e.openSidebarMenuKey)return null;const s=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${s}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},Bn=e=>e.menuOpenSessionId??om(e),_n=(e,s,n)=>s?n.has(e.node.session.id)?!0:bs(e.node,s):!1,uo=(e,s,n,r,i)=>{if(e.session.id!==s.session.id)return!0;const a=i(e);if(n.has(a)!==r.has(a)||e.children.length!==s.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(uo(e.children[l],s.children[l],n,r,i))return!0;return!1},im=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return uo(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${e.renderContext??"project"}:${n}:${i.session.id}`)||uo(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},am=(e,s)=>{if(e.node.session.id!==s.node.session.id||e.node.session!==s.node.session||e.depth!==s.depth||e.groupDirectory!==s.groupDirectory||e.projectId!==s.projectId||e.archivedBucket!==s.archivedBucket||(e.renderContext??"project")!==(s.renderContext??"project")||e.mobileVariant!==s.mobileVariant||e.alwaysShowActions!==s.alwaysShowActions||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||Li(e.node)!==Li(s.node)||!rm(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&il(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&im(e,s)||e.editingId!==s.editingId&&(_n(e,e.editingId,e.subtreeContainsEditing)||_n(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(_n(e,e.editingId,e.subtreeContainsEditing)||_n(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(bs(e.node,e.copiedSessionId)||bs(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Bn(e),r=Bn(s);if(bs(e.node,n)||bs(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=Bn(e),r=Bn(s);if(bs(e.node,n)||bs(s.node,r))return!1}return e.setEditingId===s.setEditingId&&e.setEditTitle===s.setEditTitle&&e.handleSaveEdit===s.handleSaveEdit&&e.handleCancelEdit===s.handleCancelEdit&&e.toggleParent===s.toggleParent&&e.handleSessionSelect===s.handleSessionSelect&&e.handleSessionDoubleClick===s.handleSessionDoubleClick&&e.togglePinnedSession===s.togglePinnedSession&&e.handleShareSession===s.handleShareSession&&e.handleCopyShareUrl===s.handleCopyShareUrl&&e.handleCopySessionId===s.handleCopySessionId&&e.handleUnshareSession===s.handleUnshareSession&&e.setOpenSidebarMenuKey===s.setOpenSidebarMenuKey&&e.getFoldersForScope===s.getFoldersForScope&&e.getSessionFolderId===s.getSessionFolderId&&e.removeSessionFromFolder===s.removeSessionFromFolder&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.openContextPanelTab===s.openContextPanelTab&&e.handleDeleteSession===s.handleDeleteSession&&e.handleRestoreSession===s.handleRestoreSession&&e.renderSessionNode===s.renderSessionNode},lm=o.memo(nm,am),Oi={selected:0,"active-project":1,expanded:2,visible:3,background:4};function cm(e){const s=new Map,n=(r,i,a)=>{const l=yt(r??null);if(!l)return;const c=s.get(l);c&&Oi[c.priority]<=Oi[i]||s.set(l,{directory:l,priority:i,reason:a})};for(const r of e.projectSections){const i=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":i&&(a="expanded"),n(r.project.normalizedPath,a,i?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=i&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":i&&(d="visible"),n(l.directory,d,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}function dm(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l="Untitled Session";return t.jsx(fs,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(hs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx($s,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be permanently deleted.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be archived.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`\\"${s?.session.title||l}\\" will be permanently deleted.`:`\\"${s?.session.title||l}\\" will be archived.`})]}),t.jsxs(Gs,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>{a()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:s?.archivedBucket?"Delete":"Archive"})]})]})]})})}function um(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l=s?.archivedBucket===!0,c=s?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return t.jsx(fs,{open:!!s,onOpenChange:b=>{b||n(null)},children:t.jsxs(hs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:d}),t.jsx($s,{children:u})]}),t.jsxs(Gs,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>{a()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:l?"Delete":"Archive"})]})]})]})})}function fm(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(fs,{open:!!s,onOpenChange:i=>{i||n(null)},children:t.jsxs(hs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:"Delete folder?"}),t.jsx($s,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted. Sessions inside will not be deleted.`:`\\"${s?.folderName??""}\\" will be permanently deleted.`})]}),t.jsxs(Gs,{children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const hm=({selectedCount:e,archivedBucket:s,onRestore:n,onDelete:r,onDone:i})=>{const a=s?"Delete":"Archive",l="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return t.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[t.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),t.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[s?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(k,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:F("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":a,children:t.jsx(k,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:l,"aria-label":"Exit selection",children:t.jsx(k,{name:"close",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},pm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:b,setBulkDeleteConfirm:h}=e,x=Gt(H=>H.enabled),y=Gt(H=>H.selectedIds.size),f=y>0,g=Gt(H=>H.selectedIds),w=Gt(H=>H.scopeKey),v=o.useCallback(()=>{Gt.getState().toggleMode()},[]),D=o.useCallback(()=>{Gt.getState().disable()},[]),S=o.useMemo(()=>{if(!f||typeof document>"u")return!1;let H=!1,B=!1;for(const O of g){const J=document.querySelectorAll(`[data-session-row="${CSS.escape(O)}"]`);for(const de of J)de.getAttribute("data-session-archived")==="1"?B=!0:H=!0}return B&&!H},[f,g]),m=o.useMemo(()=>{if(w)return w;if(!f||typeof document>"u")return null;for(const H of g){const O=document.querySelector(`[data-session-row="${CSS.escape(H)}"]`)?.getAttribute("data-session-scope");if(O&&O.length>0)return O}return null},[f,g,w]),p=o.useMemo(()=>{if(!m)return[];const H=i.get(m);return H&&H.length>0?H.map(B=>B.scopeKey):[m]},[m,i]),N=o.useMemo(()=>p.flatMap(H=>r[H]??[]),[r,p]),T=o.useCallback(H=>{for(const B of p)if((r[B]??[]).some(O=>O.id===H))return B;return null},[r,p]),A=o.useMemo(()=>{if(!f)return!1;for(const H of p)for(const B of r[H]??[])for(const O of B.sessionIds)if(g.has(O))return!0;return!1},[r,p,f,g]),P=o.useCallback((H,B)=>{const O=Array.from(g);for(const J of p)J!==H&&l(J,O);a(H,B,O)},[a,l,g,p]),E=o.useCallback(H=>{if(!f)return;const B=T(H);B&&P(B,H)},[f,P,T]),R=o.useCallback(()=>{const H=p[0];if(!H||!f)return;const B=c(H);B&&P(H,B.id)},[c,f,P,p]),L=o.useCallback(()=>{if(!f)return;const H=Array.from(g);for(const B of p)l(B,H)},[l,g,p,f]),Y=o.useCallback(async()=>{const H=Array.from(g);if(H.length!==0){if(S){const{deletedIds:B,failedIds:O}=await b(H);B.length>0&&le.success(B.length===1?`Deleted ${B.length} session`:`Deleted ${B.length} sessions`),O.length>0&&le.error(O.length===1?`Failed to delete ${O.length} session`:`Failed to delete ${O.length} sessions`)}else{const{archivedIds:B,failedIds:O}=await d(H);B.length>0&&le.success(B.length===1?`Archived ${B.length} session`:`Archived ${B.length} sessions`),O.length>0&&le.error(O.length===1?`Failed to archive ${O.length} session`:`Failed to archive ${O.length} sessions`)}Gt.getState().clear()}},[d,S,b,g]),X=o.useCallback(()=>{if(!f)return;const H=g.size;if(!n){Y();return}h({sessionCount:H,archivedBucket:S})},[S,Y,g,n,h,f]),oe=o.useCallback(async()=>{if(!f||!S)return;const H=Array.from(g),{restoredIds:B,failedIds:O}=await u(H);B.length>0&&le.success(B.length===1?`Restored ${B.length} session`:`Restored ${B.length} sessions`),O.length>0&&le.error(O.length===1?`Failed to restore ${O.length} session`:`Failed to restore ${O.length} sessions`),Gt.getState().clear()},[S,f,g,u]),$=o.useCallback(async()=>{h(null),await Y()},[Y]);return o.useEffect(()=>{if(!x)return;const H=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),B=O=>{if(s)return;const J=O.target;if(J&&(J.tagName==="INPUT"||J.tagName==="TEXTAREA"||J.isContentEditable))return;const de=H?O.metaKey:O.ctrlKey;if(O.key==="Escape"){O.preventDefault(),Gt.getState().disable();return}if(de&&O.key==="Backspace"){O.preventDefault(),X();return}if(de&&(O.key==="a"||O.key==="A")){const G=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(G.length===0)return;O.preventDefault();const Me=Gt.getState().scopeKey??G[0]?.getAttribute("data-session-scope")??null,He=Be=>Me?Be.getAttribute("data-session-scope")===Me:!0,ze=G.filter(He).map(Be=>Be.getAttribute("data-session-row")).filter(Be=>typeof Be=="string"&&Be.length>0);if(ze.length===0)return;Gt.getState().replaceAll(ze,Me||null)}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[X,s,x]),{selectionModeEnabled:x,hasSelection:f,selectedIdsSize:y,bulkScopeIsArchived:S,derivedSelectionScope:m,bulkScopeFolders:N,bulkCanRemoveFromFolder:A,handleToggleSelectionMode:v,handleExitSelectionMode:D,handleBulkMoveToFolder:E,handleBulkCreateFolderAndMove:R,handleBulkRemoveFromFolder:L,handleBulkDelete:X,handleBulkRestore:oe,confirmBulkDelete:$}},Bi="oc.sessions.projectCollapse",_i="oc.sessions.groupOrder",zi="oc.sessions.groupCollapse",Ui="oc.sessions.activeSessionByProject",$i="oc.sessions.expandedParents.v3",mm=(e,s,n)=>{if(e.time?.archived)return!0;const r=si(Js(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const i of s)if(si(i)===r)return!0;return!1},gm=new Set,Ar=[],ss=e=>{const s=o.useRef(e);return s.current=e,o.useCallback((...n)=>s.current(...n),[])},xm=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l})=>{const c=_e(d=>d.currentSessionDirectory);return o.useEffect(()=>{s.setBootstrapDemand(e,cm({projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,i,l,c,e,n]),o.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},bm=({directories:e})=>{const s=o.useMemo(()=>{const r=new Set;return e.forEach(i=>{const a=yt(i)?.toLowerCase();a&&r.add(a)}),r},[e]);return un(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=yt(i.directory)?.toLowerCase();if(a&&s.has(a))return!0}return!1},void 0,"catalog")?t.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:t.jsx(rr,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},ym=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Hr("react.session_sidebar_render"),as("ui.session_sidebar.render"),as(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),as(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,b]=o.useState(""),h=o.useRef(null),x=o.useRef(null),[y,f]=o.useState(null),[g,w]=o.useState(""),[v,D]=o.useState(null),[S,m]=o.useState(new Set),p=o.useMemo(()=>Rn(),[]),[N,T]=o.useState(new Set),[A,P]=o.useState(null),[E,R]=o.useState(new Map),[L,Y]=o.useState(new Map),[X,oe]=o.useState(!1),[$,H]=o.useState(null),[B,O]=o.useState(null),[J,de]=o.useState(""),[G,Ce]=o.useState(null),[Me,He]=o.useState(null),[ze,Be]=o.useState(null),Pe=Gr(j=>j.ids),te=kd(o.useCallback(j=>e?j.rankById:ya,[e])),xe=un(j=>e?Nd(j.catalog):"",void 0,"catalog"),Ge=o.useMemo(()=>xe?xe.split("|"):Ar,[xe]),Ne=o.useMemo(()=>new Set(Ge),[Ge]),ye=Ad(eo(j=>e?Object.entries(j.index.session.unseenCount).filter(([,ae])=>ae>0).map(([ae])=>ae).sort():Ar)),Ae=o.useMemo(()=>new Set(ye),[ye]),ot=Gr(j=>j.toggle),[We,Q]=o.useState(()=>{try{const j=Rn().getItem(zi);if(!j)return new Set;const ae=JSON.parse(j);return new Set(Array.isArray(ae)?ae.filter(se=>typeof se=="string"):[])}catch{return new Set}}),[V,pe]=o.useState(()=>{try{const j=Rn().getItem(_i);if(!j)return new Map;const ae=JSON.parse(j),se=new Map;return Object.entries(ae).forEach(([tt,It])=>{Array.isArray(It)&&se.set(tt,It.filter(us=>typeof us=="string"))}),se}catch{return new Map}}),q=o.useMemo(()=>{try{const j=Rn().getItem(Ui);if(!j)return new Map;const ae=JSON.parse(j),se=new Map;return Object.entries(ae).forEach(([tt,It])=>{typeof It=="string"&&It.length>0&&se.set(tt,It)}),se}catch{return new Map}},[]),ve=o.useCallback(j=>{try{p.setItem(Ui,JSON.stringify(Object.fromEntries(j.entries())))}catch{}},[p]),[we,Re]=o.useState(new Map),qe=o.useRef(new Map),at=o.useRef(0),mt=zs(j=>j.homeDirectory),Le=zs(j=>j.currentDirectory),ke=Ut(j=>j.projects),Ye=Ut(j=>j.activeProjectId),pt=Ut(j=>j.removeProject),kt=Ut(j=>j.setActiveProjectIdOnly),bt=Ut(j=>j.updateProjectMeta),_=Ut(j=>j.reorderProjects),be=re(j=>j.setActiveMainTab),Ie=re(j=>j.openContextPanelTab),C=re(j=>j.setSettingsDialogOpen),K=re(j=>j.setSettingsPage),ee=re(j=>j.toggleHelpDialog),ue=re(j=>j.setSessionSwitcherOpen),me=re(j=>j.setArchivePageOpen),Se=re(j=>j.notifyOnSubtasks),Ve=re(j=>j.showDeletionDialog),ft=re(j=>j.setShowDeletionDialog),lt=Id(u,120),it=o.useMemo(()=>lt.trim().toLowerCase(),[lt]),gt=it.length>0,Xe=$t(j=>j.collapsedFolderIds),Oe=$t(j=>j.foldersMap),Ze=$t(j=>j.getFoldersForScope),vt=$t(j=>j.createFolder),Ot=$t(j=>j.renameFolder),Et=$t(j=>j.deleteFolder),jt=$t(j=>j.addSessionToFolder),M=$t(j=>j.addSessionsToFolder),De=$t(j=>j.removeSessionFromFolder),Fe=$t(j=>j.removeSessionsFromFolders),Je=$t(j=>j.toggleFolderCollapse),dt=$t(j=>j.getSessionFolderId);Kh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:h});const Rt=Dd(e),z=mo(),ie=va(),ge=un(j=>j.connection,void 0,"chrome"),et=un(j=>{for(const ae of j.catalog.listStatusByDirectory.values())if(ae==="ready")return!0;return!1},void 0,"catalog"),je=$r({archived:!1}),$e=$r({archived:!0}),ct=`session-sidebar:${o.useId()}`,At=_e(j=>j.setCurrentSession),_t=_e(j=>j.updateSessionTitle),Mt=_e(j=>j.shareSession),Zt=_e(j=>j.unshareSession),qt=_e(j=>j.availableWorktreesByProject)??new Map,Nt=_e(j=>j.openNewSessionDraft),Bt=o.useCallback(j=>{re.getState().closeMainSurfaces(),Nt(j),r?.()},[r,Nt]),U=Wn(eo(j=>({checkForUpdates:j.checkForUpdates,available:j.available,runtimeType:j.runtimeType,info:j.info,downloading:j.downloading,downloaded:j.downloaded,progress:j.progress,error:j.error,downloadUpdate:j.downloadUpdate,restartToUpdate:j.restartToUpdate}))),Z=o.useMemo(()=>Pd(ke,qt,{includeWorktrees:!0}),[qt,ke]),ne=o.useMemo(()=>je.filter(j=>mm(j,Z,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[je,Z]),ce=o.useMemo(()=>[...ne,...$e],[$e,ne]),he=ir(),ht=o.useMemo(()=>`${he}|${ke.map(j=>`${j.id}:${yt(j.path)??""}`).join("|")}`,[ke,he]),[wt,Dt]=o.useState(null),Kt=wt!==ht,[rs,Pt]=o.useState(new Set),ls=o.useMemo(()=>ys(),[]),{isTablet:cs}=Us(),os=s||cs,{buildGroupSearchText:Ds,filterSessionNodesForSearch:Ss,buildGroupedSessions:nn}=Gh({homeDirectory:mt,pinnedSessionIds:Pe,sessionOrderRanks:te}),{scheduleCollapsedProjectsPersist:W}=Wh({safeStorage:p,keys:{sessionExpanded:$i,projectCollapse:Bi,groupOrder:_i,groupCollapse:zi},groupOrderByProject:V,collapsedGroups:We,setExpandedParents:m,setCollapsedProjects:T}),Ue=o.useMemo(()=>Td(ne,Pe,te),[Pe,te,ne]),ut=o.useMemo(()=>Ue.map(j=>j.id).join("|"),[Ue]),St=o.useRef(null),Tt=o.useMemo(()=>{const j=St.current;if(j&&j.signature===ut)return j.map;const ae=new Map(Ue.map((se,tt)=>[se.id,tt]));return St.current={signature:ut,map:ae},ae},[Ue,ut]),Qt=o.useMemo(()=>{const j=new Map;return Ue.forEach(ae=>{const se=ae.parentID;if(!se)return;const tt=j.get(se)??[];tt.push(ae),j.set(se,tt)}),j.forEach(ae=>ae.sort((se,tt)=>Jn(se,tt,Pe,te))),j},[Ue,Pe,te]),es=o.useMemo(()=>t.jsx(Os,{icon:"chat-new",mobileVariant:s,onClick:()=>Bt(),children:"New session"}),[s,Bt]),ts=o.useMemo(()=>ke.find(j=>j.id===v)??null,[ke,v]),js=o.useCallback(j=>{v&&bt(v,{label:j.label,defaultModel:j.defaultModel??null})},[v,bt]),hr=o.useCallback(()=>{const j=Wn.getState();if(j.available&&j.info){oe(!0);return}U.checkForUpdates().then(()=>{const{available:ae,error:se}=Wn.getState();if(se){le.error("Failed to check for updates",{description:se});return}if(!ae){le.success("You are on the latest version");return}oe(!0)})},[U]),ps=Ed(),Cn=o.useCallback(()=>{if(s&&ue(!1),r?.(),ps?.openSettings){ps.openSettings();return}C(!0)},[ps,s,r,ue,C]),pr=U.available&&(U.runtimeType==="desktop"||U.runtimeType==="web"),kn=_e(j=>j.deleteSession),Nn=_e(j=>j.deleteSessions),mr=_e(j=>j.archiveSession),An=_e(j=>j.archiveSessions),I=_e(j=>j.unarchiveSession),fe=_e(j=>j.unarchiveSessions),{copiedSessionId:Te,handleSessionSelect:xt,handleSessionDoubleClick:Cs,handleSaveEdit:ds,handleCancelEdit:rn,handleShareSession:ms,handleCopyShareUrl:bl,handleCopySessionId:yl,handleUnshareSession:vl,handleDeleteSession:wl,handleRestoreSession:Sl,confirmDeleteSession:jl}=Hh({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:b,setIsSessionSearchOpen:d,setActiveMainTab:be,setSessionSwitcherOpen:ue,setCurrentSession:At,updateSessionTitle:_t,shareSession:Mt,unshareSession:Zt,deleteSession:kn,deleteSessions:Nn,archiveSession:mr,archiveSessions:An,unarchiveSession:I,childrenMap:Qt,showDeletionDialog:Ve,setDeleteSessionConfirm:Ce,deleteSessionConfirm:G,setEditingId:f,setEditTitle:w,editingId:y,editTitle:g}),Cl=o.useCallback(()=>{if(!Me)return;const{scopeKey:j,folderId:ae}=Me;He(null),Et(j,ae)},[Me,Et]),Io=o.useCallback(()=>{_s.requestDirectoryDialog()},[]),kl=o.useCallback(j=>{m(ae=>{const se=Rd(ae,j);try{p.setItem($i,JSON.stringify(Array.from(se)))}catch{}return se})},[p]),Do=o.useCallback((j,ae)=>{if(!j)return null;ae&&Xe.has(ae)&&Je(ae);const se=vt(j,"New folder",ae);return O(se.id),de(se.name),se},[Xe,Je,vt]),Po=ss(xt),Nl=ss(Cs),Al=ss(ds),Il=ss(rn),Dl=ss(ms),Pl=ss(bl),Tl=ss(yl),El=ss(vl),Rl=ss(wl),Ml=ss(Sl),gr=ss(Do),To=o.useCallback((j,ae)=>{Y(se=>{const tt=new Map(se);return tt.set(j,ae+7),tt})},[]),In=o.useCallback(j=>{Y(ae=>{if(!ae.has(j))return ae;const se=new Map(ae);return se.delete(j),se})},[]),Eo=o.useCallback(j=>{Y(ae=>{let se=!1;const tt=new Map(ae),It=`${j}:`;for(const us of tt.keys())us.startsWith(It)&&(tt.delete(us),se=!0);return se?tt:ae})},[]),Fl=o.useCallback(j=>{at.current=Date.now()+150,Eo(j),T(ae=>{const se=new Set(ae);se.has(j)?se.delete(j):se.add(j);try{p.setItem(Bi,JSON.stringify(Array.from(se)))}catch{}return W(se),se})},[Eo,p,W]),ks=o.useMemo(()=>ke.map(j=>({...j,normalizedPath:yt(j.path)})).filter(j=>!!j.normalizedPath),[ke]),Ll=o.useMemo(()=>ks.map(j=>j.normalizedPath),[ks]),Ro=Md(e?Ll:Ar);Vh({enabled:e,normalizedProjects:ks,gitRepoStatus:Ro,setProjectRepoStatus:R,setProjectRootBranches:Re});const Ol=_e(j=>j.isLoading),Mo=o.useMemo(()=>np(ne,ks,qt,$e),[$e,qt,ks,ne]);Zh({enabled:e,hasAuthoritativeGlobalSessions:et,sessions:ce});const{getSessionsForProject:Bl,getArchivedSessionsForProject:_l}=qh({ownership:Mo});Bh({enabled:e,normalizedProjects:ks,ownership:Mo,isSessionsLoading:Ol,hasAuthoritativeGlobalSessions:et,isWorktreeTopologyLoading:Kt,unresolvedWorktreeProjectPaths:rs,foldersMap:Oe,createFolder:vt,addSessionToFolder:jt});const Fo=o.useRef(!1);Ye&&E.has(Ye)&&(Fo.current=!!E.get(Ye));const zl=Ri(j=>j.showArchivedSessions),Lo=Ri(j=>j.stickyZoneHeaders),xr=Ut(j=>j.manualProjectOrder),Oo=o.useRef(new Set),Dn=Fd(Oo.current,S,"project");Oo.current=Dn;const br={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:cs,catalogSessions:je,archivedSessions:$e,projects:ke,activeProjectId:Ye,manualProjectOrder:xr,currentDirectory:Le,availableWorktreesByProject:qt,pinnedSessionIds:Pe,sessionOrderRanks:te,foldersMap:Oe,collapsedFolderIds:Xe,gitBranches:Rt,gitRepoStatus:Ro,updateStore:U,showArchivedSessions:zl,projectRepoStatus:E,projectRootBranches:we,resolvedWorktreeTopologyKey:wt,unresolvedWorktreeProjectPaths:rs,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:y,editTitle:g,editingProjectDialogId:v,expandedParents:S,collapsedProjects:N,visibleSessionCountByGroup:L,updateDialogOpen:X,openSidebarMenuKey:$,renamingFolderId:B,renameFolderDraft:J,deleteSessionConfirm:G,deleteFolderConfirm:Me,bulkDeleteConfirm:ze,collapsedGroups:We},Bo=o.useRef(null),_o=Bo.current;if(_o){let j=!1;for(const ae of Object.keys(br))Object.is(_o[ae],br[ae])||(as(`ui.session_sidebar.source.${ae}`),j=!0);j||as("ui.session_sidebar.source.parent_or_context")}Bo.current=br;const Ul=o.useMemo(()=>{const j=new Map(xr.map((ae,se)=>[ae,se]));return[...ks].sort((ae,se)=>(j.get(ae.id)??1/0)-(j.get(se.id)??1/0))},[xr,ks]),{projectSections:Ft,groupSearchDataByGroup:zo,flatSectionsForRender:Pn,searchMatchCount:$l}=zh({normalizedProjects:Ul,getSessionsForProject:Bl,getArchivedSessionsForProject:_l,projectRepoStatus:E,projectRootBranches:we,lastRepoStatus:Fo.current,buildGroupedSessions:nn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,filterSessionNodesForSearch:Ss,buildGroupSearchText:Ds,foldersMap:Oe}),Gl=o.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Kl}=_h(V),Uo=o.useRef(!1);o.useEffect(()=>{if(Uo.current||Ft.length===0)return;const j=Ft.flatMap(ae=>ae.groups.filter(se=>se.isArchivedBucket).map(se=>`${ae.project.id}:${se.id}`));j.length>0&&Q(ae=>new Set([...ae,...j])),Uo.current=!0},[Ft]),o.useMemo(()=>{const j=new Map,ae=new Map;return Ft.forEach(se=>{const tt=or(se.project.label?.trim()||Bs(se.project.normalizedPath,mt)||se.project.normalizedPath);se.groups.forEach(It=>{const us=It.branch&&It.branch!=="HEAD"&&It.branch!==tt?It.branch:null,on={projectLabel:tt,branchLabel:us},Ps=xc=>{xc.forEach(Ks=>{const Ho=se.project.normalizedPath.length,bc=ae.get(Ks.session.id)??-1;Ho<bc||(j.set(Ks.session.id,{node:Ks,projectId:se.project.id,groupDirectory:It.directory,secondaryMeta:on}),ae.set(Ks.session.id,Ho),Ks.children.length>0&&Ps(Ks.children))})};Ps(It.sessions)})}),j},[Ft,mt]);const yr=o.useMemo(()=>Pn.map(j=>j.groups.some(ae=>ae.isArchivedBucket)?{...j,groups:j.groups.filter(ae=>!ae.isArchivedBucket)}:j),[Pn]),Hl=o.useMemo(()=>A?yr.filter(j=>j.project.id===A):yr,[yr,A]),Wl=o.useMemo(()=>{let j=0;for(const ae of Ft)for(const se of ae.groups)se.isArchivedBucket||(j+=se.sessions.length);return j},[Ft]),Yl=o.useMemo(()=>{const j=new Map;for(const ae of Ft){let se=0;for(const tt of ae.groups)tt.isArchivedBucket||(se+=tt.sessions.length);j.set(ae.project.id,se)}return j},[Ft]),Vl=o.useCallback(j=>{const ae=Ft.find(se=>se.project.id===j);return ae?ae.groups.some(se=>se.isArchivedBucket?!1:se.sessions.some(tt=>Ne.has(tt.session.id))):!1},[Ne,Ft]),ql=o.useCallback(j=>{const ae=Ft.find(se=>se.project.id===j);return ae?ae.groups.some(se=>se.isArchivedBucket?!1:se.sessions.some(tt=>Ae.has(tt.session.id))):!1},[Ft,Ae]),Ql=s?"flex size-9 shrink-0 items-center justify-center rounded-full leading-none 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":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Jl=s?"size-4":"h-4.5 w-4.5",Xl=rp({enabled:e&&Lo,isDesktopShellRuntime:ls,projectSections:Ft,projectHeaderSentinelRefs:qe}),Tn=ss((j,ae=0,se,tt,It=!1,us,on="project",Ps)=>t.jsx(lm,{node:j,depth:ae,groupDirectory:se,projectId:tt,archivedBucket:It,pinnedSessionIds:Pe,expandedParents:Dn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,notifyOnSubtasks:Se,editingId:y,setEditingId:f,editTitle:g,setEditTitle:w,handleSaveEdit:Al,handleCancelEdit:Il,toggleParent:kl,handleSessionSelect:Po,handleSessionDoubleClick:Nl,togglePinnedSession:ot,handleShareSession:Dl,copiedSessionId:Te,handleCopyShareUrl:Pl,handleCopySessionId:Tl,handleUnshareSession:El,openSidebarMenuKey:$,setOpenSidebarMenuKey:H,renamingFolderId:B,getFoldersForScope:Ze,getSessionFolderId:dt,removeSessionFromFolder:De,addSessionToFolder:jt,createFolderAndStartRename:gr,openContextPanelTab:Ie,handleDeleteSession:Rl,handleRestoreSession:Ml,mobileVariant:s,alwaysShowActions:os,renderSessionNode:Tn,secondaryMeta:us,renderContext:on,subtreeContainsEditing:Ps?.subtreeContainsEditing??gm,menuOpenSessionId:Ps?.menuOpenSessionId??null,nodeStructureKey:Ps?.nodeStructureKey??"",childRenderExtrasFor:Ps?.childRenderExtrasFor})),Zl=o.useMemo(()=>{const j=new Map;return Pn.forEach(ae=>{const se=ae.groups.find(tt=>!tt.isArchivedBucket);se?.folderScopes&&se.folderScopes.length>0&&j.set(ae.project.id,se.folderScopes)}),j},[Pn]),ec=o.useCallback((j,ae)=>{const se=[];return ae.forEach(tt=>{tt.isArchivedBucket||(se.push(tt.directory),tt.folderScopes?.forEach(It=>se.push(It.directory)))}),t.jsx(bm,{directories:se})},[]),$o=o.useCallback(j=>{In(j),Q(ae=>{const se=new Set(ae);return se.has(j)?se.delete(j):se.add(j),se})},[In]),tc=o.useCallback((j,ae,se,tt,It,us,on)=>t.jsx(Cp,{group:j,groupKey:ae,projectId:se,hideGroupLabel:tt,dragHandleProps:It,compactBodyPadding:us,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,groupSearchDataByGroup:zo,visibleSessionCount:L.get(ae),collapsedGroups:We,hideDirectoryControls:a,collapsedFolderIds:Xe,toggleFolderCollapse:Je,renameFolder:Ot,deleteFolder:Et,showDeletionDialog:Ve,setDeleteFolderConfirm:He,renderSessionNode:Tn,showMoreGroupSessions:To,resetGroupSessionLimit:In,mobileVariant:s,alwaysShowActions:os,activeProjectId:Ye,setActiveProjectIdOnly:kt,setActiveMainTab:be,setSessionSwitcherOpen:ue,openNewSessionDraft:Bt,addSessionToFolder:jt,createFolderAndStartRename:gr,renamingFolderId:B,renameFolderDraft:J,setRenameFolderDraft:de,setRenamingFolderId:O,pinnedSessionIds:Pe,expandedParents:Dn,sessionOrderIndex:Tt,editingId:y,editTitle:g,openSidebarMenuKey:$,activeActivitySessionIds:Ne,unreadActivitySessionIds:Ae,notifyOnSubtasks:Se,onToggleCollapsedGroup:$o,scrollContainerRef:on}),[gt,it,zo,L,We,a,Xe,Je,Ot,Et,Ve,Tn,To,In,s,os,Ye,kt,be,ue,Bt,jt,gr,B,J,Pe,Dn,Tt,y,g,$,Ne,Ae,Se,$o]),Go=!!(B||y||v),{selectionModeEnabled:Ko,hasSelection:sc,selectedIdsSize:nc,bulkScopeIsArchived:rc,derivedSelectionScope:oc,bulkScopeFolders:ic,bulkCanRemoveFromFolder:ac,handleToggleSelectionMode:lc,handleExitSelectionMode:cc,handleBulkMoveToFolder:dc,handleBulkCreateFolderAndMove:uc,handleBulkRemoveFromFolder:fc,handleBulkDelete:hc,handleBulkRestore:pc,confirmBulkDelete:mc}=pm({isInlineEditing:Go,showDeletionDialog:Ve,foldersMap:Oe,folderScopesByProject:Zl,addSessionsToFolder:M,removeSessionsFromFolders:Fe,createFolderAndStartRename:Do,archiveSessions:An,unarchiveSessions:fe,deleteSessions:Nn,setBulkDeleteConfirm:Be}),gc=o.useCallback(()=>{re.getState().closeMainSurfaces(),be("chat"),s&&ue(!1),Nt(),r?.()},[s,r,Nt,be,ue]);return t.jsx(Ld,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:h,className:F("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(xm,{owner:ct,childStores:ie,projectSections:Ft,activeProjectId:Ye,collapsedProjects:N,collapsedGroups:We,currentDirectory:Le}),t.jsx($h,{projectSections:Ft,activeProjectId:Ye,initialActiveSessionByProject:q,persistActiveSessionByProject:ve,handleSessionSelect:Po,mobileVariant:s,openNewSessionDraft:Nt,setActiveMainTab:be,setSessionSwitcherOpen:ue}),t.jsx(Oh,{enabled:e,sortedSessions:Ue,prefetchSession:async j=>{await z.syncSession(j)}}),!a&&!s?t.jsx(Np,{onNewSession:gc,showSidebarToggle:!0}):null,t.jsx(kp,{hideDirectoryControls:a,handleOpenDirectoryDialog:Io,onOpenArchive:()=>{s&&ue(!1),me(!0)},onOpenSettings:s?Cn:void 0,onOpenInstances:s?ps?.openInstances:void 0,instanceLabel:s?ps?.instanceLabel:void 0,onOpenUpdate:s?ps?.openUpdate:void 0,headerActionIconClass:Jl,headerActionButtonClass:Ql,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:b,hasSessionSearchQuery:gt,searchMatchCount:$l,selectionModeEnabled:Ko,onToggleSelectionMode:lc,mobileVariant:s}),ge==="error"||ge==="unavailable"?t.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded bg-[var(--status-error-background)] p-2 text-xs text-[var(--status-error-foreground)]",children:"Unable to reach server"}):null,!a&&Ft.length>0?t.jsx(Dp,{projects:Ft.map(j=>j.project),selectedProjectId:A,onSelectProject:j=>{P(j),j&&kt(j)},onOpenDirectoryDialog:Io,onOpenProjectEditDialog:D,onRemoveProject:pt,totalSessionCount:Wl,getSessionCountForProject:j=>Yl.get(j)??0,hasActiveSessionByProject:Vl,hasUnseenByProject:ql,homeDirectory:mt,mobileVariant:s}):null,t.jsx(Bp,{sectionsForRender:Hl,projectSections:Ft,activeProjectId:Ye,showOnlyMainWorkspace:l,hasSessionSearchQuery:gt,emptyState:es,searchEmptyState:Gl,isAllFoldersView:A===null,pinnedSessionIds:Pe,renderSessionNode:Tn,renderGroupSessions:tc,homeDirectory:mt,collapsedProjects:N,hideDirectoryControls:a,projectRepoStatus:E,isDesktopShellRuntime:ls,stickyZoneHeaders:Lo,stuckProjectHeaders:Xl,mobileVariant:s,alwaysShowActions:os,toggleProject:Fl,setActiveProjectIdOnly:kt,setActiveMainTab:be,setSessionSwitcherOpen:ue,openNewSessionDraft:Bt,openProjectEditDialog:D,removeProject:pt,projectHeaderSentinelRefs:qe,reorderProjects:_,getOrderedGroups:Kl,setGroupOrderByProject:pe,renderProjectStatusIndicator:ec,openSidebarMenuKey:$,setOpenSidebarMenuKey:H,isInlineEditing:Go}),Ko&&sc?t.jsx(hm,{selectedCount:nc,scopeKey:oc,scopeFolders:ic,archivedBucket:rc,onMoveToFolder:dc,onCreateFolderAndMove:uc,onRemoveFromFolder:fc,canRemoveFromFolder:ac,onRestore:pc,onDelete:hc,onDone:cc}):null,s?null:t.jsx(Pp,{onOpenSettings:Cn,onOpenShortcuts:ee,onOpenAbout:()=>{K("about"),C(!0)},onOpenUpdate:hr,showRuntimeButtons:!0,showUpdateButton:pr}),t.jsx(Ka,{open:X,onOpenChange:oe,info:U.info,downloading:U.downloading,downloaded:U.downloaded,progress:U.progress,error:U.error,onDownload:U.downloadUpdate,onRestart:U.restartToUpdate,runtimeType:U.runtimeType}),t.jsx(op,{open:!!ts,onOpenChange:j=>{j||D(null)},project:ts,onSave:js}),t.jsx(dm,{value:G,setValue:Ce,showDeletionDialog:Ve,setShowDeletionDialog:ft,onConfirm:jl}),t.jsx(fm,{value:Me,setValue:He,onConfirm:Cl}),t.jsx(um,{value:ze,setValue:Be,showDeletionDialog:Ve,setShowDeletionDialog:ft,onConfirm:mc})]})})},Dx=o.memo(ym),Gi=6,ns=.18,cn=1.2,dn=.38,Vn=48,vm=(e,s)=>e==="left"?s<0:s>0,Px=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Tx=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,Ki=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),Ex=e=>{const{side:s,dx:n,dy:r,dt:i,progress:a,isDragging:l}=e,c=n/Math.max(1,i);if(l){const d=s==="left"?c<-ns:c>ns,u=s==="left"?c>ns:c<-ns;return d||!u&&a<dn}return Math.abs(n)>=Vn&&Math.abs(r)<=Math.abs(n)*cn&&vm(s,n)},wm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:i,progress:a}=e,l=r/Math.max(1,i);return s==="left"?n?l<-ns?!1:l>ns?!0:a>dn:l>ns?!0:l<-ns?!1:a>dn:n?l>ns?!1:l<-ns?!0:a>dn:l<-ns?!0:l>ns?!1:a>dn},Sm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',jm=(e,s)=>{if(!(e instanceof Element))return!1;const n=e.closest(Sm);if(n&&s.contains(n))return!0;let r=e;for(;r&&r!==s;){if(r instanceof HTMLElement&&r.scrollWidth>r.clientWidth){const i=getComputedStyle(r).overflowX;if(i==="auto"||i==="scroll")return!0}r=r.parentElement}return!1},Cm=({value:e,options:s,disabled:n,onChange:r})=>{const i=e||"Default",a=t.jsxs("div",{className:F("flex h-6 w-fit items-center gap-1.5 rounded-lg border border-border/20 bg-interactive-selection/20 px-2",n?"cursor-not-allowed opacity-60":"cursor-pointer hover:bg-interactive-hover/30"),children:[t.jsx("span",{className:"typography-micro whitespace-nowrap font-medium capitalize",children:i}),t.jsx(k,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:a}),t.jsxs(Vt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(Ct,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:F("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(Ct,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:F("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Hi=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function km(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:i=!1,onConfirm:a}=e,l=Lt(m=>m.loadProviders),c=Lt(m=>m.loadAgents),d=Lt(m=>m.providers),u=Lt(m=>m.currentProviderId),b=Lt(m=>m.currentModelId),h=Lt(m=>m.currentVariant||""),x=Lt(m=>m.currentAgentName||""),[y,f]=o.useState(()=>Hi({providerID:u,modelID:b,variant:h,agent:x}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&f(Hi({providerID:u,modelID:b,variant:h,agent:x}))},[s,u,b,h,x]),o.useEffect(()=>{if(!s||d.length===0)return;const m=d.find(A=>A.id===y.providerID)??d[0],p=Array.isArray(m?.models)?m.models:[],N=p.some(A=>A.id===y.modelID),T=p[0]?.id??"";m?.id===y.providerID&&N||f(A=>({...A,providerID:typeof m?.id=="string"?m.id:"",modelID:typeof T=="string"?N?A.modelID:T:"",variant:""}))},[s,d,y.providerID,y.modelID]),o.useCallback(m=>Od(m.mode),[]);const g=o.useMemo(()=>{const p=d.find(N=>N.id===y.providerID)?.models?.find(N=>N.id===y.modelID);return p?.variants?Object.keys(p.variants):[]},[d,y.providerID,y.modelID]),w=g.length>0;o.useEffect(()=>{w||!y.variant||f(m=>({...m,variant:""}))},[w,y.variant]);const v=y.providerID.trim().length>0&&y.modelID.trim().length>0,D=o.useCallback(()=>{!v||i||a(y)},[v,i,a,y]);return o.useEffect(()=>{if(!s)return;const m=p=>{(p.metaKey||p.ctrlKey)&&p.key==="Enter"&&(p.preventDefault(),D())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[s,D]),t.jsx(fs,{open:s,onOpenChange:m=>{i||n(m)},children:t.jsxs(hs,{className:"max-w-md overflow-visible",children:[t.jsx(Is,{children:t.jsx(vs,{children:"Send to new session"})}),t.jsx("div",{className:"flex flex-col gap-4",children:t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Thinking level"}),t.jsx(Cm,{value:y.variant,options:g,disabled:!w,onChange:m=>f(p=>({...p,variant:m}))})]})}),t.jsx("div",{className:"flex items-center justify-end gap-3",children:t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Qe,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:i,children:"Cancel"}),t.jsx(Qe,{size:"sm",onClick:D,disabled:!v||i,children:i?"Sending":"Send"})]})})]})})}const fo=5,ml=15,zn=new Map,qn=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},Nm=(e,s)=>{const n=qn(s);return Math.max(n*fo,Math.min(n*ml,n*e))},Am=async(e,s)=>{const n=await $d(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Im=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Wi=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],Yi=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},Dm=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=dr({id:e});return t.jsx("li",{ref:i,style:{transform:ur.Transform.toString(l),transition:c},className:F(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},Pm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[b,h]=o.useState(""),[x,y]=o.useState(null),[f,g]=o.useState(()=>new Set),[w,v]=o.useState([]),[D,S]=o.useState(null),[m,p]=o.useState(!1),[N,T]=o.useState(0),A=o.useRef(!1),P=o.useRef(""),E=o.useRef(null),R=re(C=>C.todoPanelHeight),L=re(C=>C.setTodoPanelHeight),Y=re(C=>C.notesPanelHeight),X=re(C=>C.setNotesPanelHeight),[oe,$]=o.useState(!1),H=o.useRef(0),B=o.useRef(R),O=_e(C=>C.currentSessionId),J=_e(C=>C.createSession),de=_e(C=>C.initializeNewPiChamberSession),G=_e(C=>C.sendMessage),Ce=_e(C=>C.setCurrentSession),Me=Bd(C=>C.setPendingInputText),He=zs(C=>C.currentDirectory),ze=re(C=>C.openContextPanelTab),Be=re(C=>C.setActiveMainTab),Pe=re(C=>C.setSessionSwitcherOpen),te=re(C=>C.padding),xe=o.useCallback(async(C,K)=>{if(!e)return!1;const ee=e.id,me=(zn.get(ee)??Promise.resolve()).catch(()=>{}).then(()=>_d(e,{notes:C,todos:K}));zn.set(ee,me);try{const Se=await me;return Se||le.error("Failed to save project notes"),Se}finally{zn.get(ee)===me&&zn.delete(ee)}},[e]);o.useEffect(()=>{if(!e){c(""),u([]),v([]),h(""),g(new Set);return}let C=!1;return a(!0),(async()=>{try{const K=await zd(e),ee=await Promise.all(K.plans.map(ue=>Am(ue,"Plan")));if(C)return;c(K.notes),u(Wi(K.todos)),v(ee),P.current=K.notes,A.current=!0,h(""),g(new Set)}catch{C||(le.error("Failed to load project notes"),c(""),u([]),v([]),P.current="",A.current=!0)}finally{C||a(!1)}})(),()=>{C=!0}},[N,e]),o.useEffect(()=>{if(!e)return;const C=K=>{const ee=K.detail;ee?.projectId&&ee.projectId!==e.id||T(ue=>ue+1)};return window.addEventListener("pichamber:project-plan-saved",C),window.addEventListener("pichamber:project-notes-updated",C),()=>{window.removeEventListener("pichamber:project-plan-saved",C),window.removeEventListener("pichamber:project-notes-updated",C)}},[e]),o.useEffect(()=>{if(d.length<7)return;const C=Nm(d.length,te),K=qn(te)*fo;R!==C&&(R<K||R>C)&&L(C)},[d.length,te,R,L]),o.useEffect(()=>{if(!oe)return;const C=ee=>{const ue=ee.clientY-H.current,me=Math.min(qn(te)*ml,Math.max(qn(te)*fo,B.current+ue));L(me)},K=()=>{$(!1)};return window.addEventListener("pointermove",C),window.addEventListener("pointerup",K,{once:!0}),window.addEventListener("pointercancel",K,{once:!0}),()=>{window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",K),window.removeEventListener("pointercancel",K)}},[oe,te,L]);const Ge=o.useCallback(C=>{$(!0),H.current=C.clientY,B.current=R,C.preventDefault()},[R]),Ne=o.useCallback(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),ye=o.useCallback(()=>{Ne(),P.current=l,xe(l,d)},[Ne,l,xe,d]);o.useEffect(()=>{if(!(!e||!A.current)&&l!==P.current)return E.current=window.setTimeout(()=>{E.current=null,P.current=l,xe(l,d)},400),()=>{Ne()}},[Ne,l,xe,e,d]),o.useEffect(()=>()=>Ne(),[Ne]);const Ae=o.useCallback(()=>{const C=b.trim();if(!C)return;const K=Yi(d,{id:Im(),text:C.slice(0,En),completed:!1,createdAt:Date.now()});u(K),h(""),xe(l,K)},[b,l,xe,d]),ot=o.useCallback(C=>{g(K=>{const ee=new Set(K);return ee.has(C)?ee.delete(C):ee.add(C),ee})},[]),We=o.useCallback((C,K)=>{const ee=d.find(Ve=>Ve.id===C);if(!ee||ee.completed===K)return;const ue=d.filter(Ve=>Ve.id!==C),me={...ee,completed:K},Se=K?[...ue,me]:Yi(ue,me);u(Se),xe(l,Se)},[l,xe,d]),Q=o.useCallback(C=>{const K=d.filter(ee=>ee.id!==C);u(K),xe(l,K)},[l,xe,d]),V=o.useCallback(()=>{const C=d.filter(K=>!K.completed);C.length!==d.length&&(u(C),xe(l,C))},[l,xe,d]),pe=o.useCallback(C=>{const{active:K,over:ee}=C;if(!ee||K.id===ee.id)return;const ue=d.findIndex(Ve=>Ve.id===K.id),me=d.findIndex(Ve=>Ve.id===ee.id);if(ue===-1||me===-1)return;const Se=Wi(Vu(d,ue,me));u(Se),xe(l,Se)},[l,xe,d]),q=ar(vn(wo,{activationConstraint:{distance:8}})),ve=b.slice(0,En),we=d.reduce((C,K)=>C+(K.completed?1:0),0),Re=o.useCallback(()=>{Be("chat"),Pe(!1)},[Be,Pe]),qe=o.useCallback((C,K)=>{!e||x!==null||S({todoId:C,todoText:K})},[e,x]),at=o.useCallback(C=>{if(!O){le.error("No active session selected");return}Re();const K=`\`\`\`md
47
- ${C}
48
- \`\`\``;Me(K,"append"),le.success("Todo sent to current session"),n?.()},[O,n,Re,Me]),mt=o.useCallback(async C=>{if(!e||!D)return;const K=await ni("plan.todo.visible",{todo_text:D.todoText}),ue=[{synthetic:!0,text:await ni("plan.todo.instructions",{todo_text:D.todoText})}];p(!0),y(D.todoId);try{Re();const me=await J(void 0,e.path,null);if(!me?.id){le.error("Failed to create session");return}const Se=me.id,Ve=me.directory??e.path;de(me.id,Lt.getState().agents??[]);const ft=fa.getState();ft.saveSessionModelSelection(Se,C.providerID,C.modelID),C.agent.trim()&&(ft.saveSessionAgentSelection(Se,C.agent),ft.saveAgentModelForSession(Se,C.agent,C.providerID,C.modelID),ft.saveAgentModelVariantForSession(Se,C.agent,C.providerID,C.modelID,C.variant||void 0)),Ce(Se,Ve),await G(K,C.providerID,C.modelID,C.agent.trim()||void 0,void 0,void 0,ue,C.variant||void 0),le.success("Todo sent to new session"),S(null),n?.()}catch{le.error("Failed to send note")}finally{p(!1),y(null)}},[J,de,n,D,e,Re,G,Ce]),Le=o.useRef(null),[ke,Ye]=o.useState(!1),[pt,kt]=o.useState(null),bt=o.useCallback(async C=>{if(!(!e||pt)){kt(C);try{if(!await Ud(e,C)){le.error("Failed to delete plan");return}v(ee=>ee.filter(ue=>ue.id!==C)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{kt(null)}}},[pt,e]),_=o.useCallback(async()=>{if(!e||ke)return;const C=await ku({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(C.success&&C.path){Ye(!0);try{const K=new URLSearchParams({path:C.path,allowOutsideWorkspace:"true"});C.outsideFileGrant&&K.set("outsideFileGrant",C.outsideFileGrant);const ee=await Xt(`/api/fs/read?${K.toString()}`,{cache:"no-store"});if(!ee.ok){le.error("Failed to read plan file");return}const ue=await ee.text();if(!ue.trim()){le.error("Plan file is empty");return}const me=C.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await ri(e,ue,me)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(K){const ee=K instanceof Error?K.message:void 0;le.error("Failed to read plan file",ee?{description:ee}:void 0)}finally{Ye(!1)}}else C.error==="Native file picker not available"&&Le.current?.click()},[ke,e]),be=o.useCallback(async C=>{if(!(!e||!C)){Ye(!0);try{const K=await C.text();if(!K.trim()){le.error("Plan file is empty");return}const ee=C.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await ri(e,K,ee)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(K){const ee=K instanceof Error?K.message:void 0;le.error("Failed to read plan file",ee?{description:ee}:void 0)}finally{Ye(!1)}}},[e]),Ie=o.useCallback(C=>{const K=e?.path?.trim(),ee=He?.trim()||K;ee&&ze(ee,{mode:"file",targetPath:C.path,dedupeKey:C.path,label:C.title})},[He,ze,e]);return e?t.jsxs("div",{className:F("w-full min-w-0 space-y-3 p-3",r),children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:e.path,children:`Quick notes - ${s?.trim()||e.path.split("/").filter(Boolean).pop()||e.path}`}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",oi]})]}),t.jsx(Co,{value:l,onChange:C=>c(C.target.value.slice(0,oi)),onBlur:ye,placeholder:"Capture context, reminders, or links",resizedHeight:Y,onResizeHeightChange:X,useScrollShadow:!0,scrollShadowSize:56,disabled:i})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:d.length===1?`${d.length} item`:`${d.length} items`}),t.jsx("button",{type:"button",onClick:V,disabled:i||we===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:"Clear completed"})]}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ve.length,"/",En]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(en,{value:ve,onChange:C=>h(C.target.value.slice(0,En)),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),Ae())},placeholder:"Add a todo",disabled:i,className:"h-8"}),t.jsx("button",{type:"button",onClick:Ae,disabled:i||ve.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",title:"Add todo",children:t.jsx(k,{name:"add",className:"h-4 w-4"})})]}),t.jsx("div",{className:F("overflow-y-auto rounded-lg border border-border/60 bg-background/40",oe&&"transition-none"),style:d.length<7?void 0:{height:`${R}px`,maxHeight:`${R}px`},children:d.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No todos yet. Add a small checklist for this project."}):t.jsx(lr,{sensors:q,collisionDetection:cr,onDragEnd:pe,children:t.jsx(So,{items:d.map(C=>C.id),strategy:Ba,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(C=>{const K=f.has(C.id);return t.jsx(Dm,{id:C.id,children:ee=>t.jsxs("div",{className:F("flex gap-1.5 px-2.5 py-1.5",K?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:ee.setActivatorNodeRef,...ee.attributes,...ee.listeners,onClick:ue=>{ue.preventDefault(),ue.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":`Reorder \\"${C.text}\\"`,title:`Reorder \\"${C.text}\\"`,children:t.jsx(k,{name:"draggable",className:"h-3.5 w-3.5"})}),t.jsx("div",{className:"flex h-6 items-center",children:t.jsx(la,{checked:C.completed,onChange:ue=>We(C.id,ue),ariaLabel:`Mark \\"${C.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>ot(C.id),className:F("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",K?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",C.completed&&"text-muted-foreground line-through"),title:K?void 0:C.text,"aria-label":K?`Collapse todo \\"${C.text}\\"`:`Expand todo \\"${C.text}\\"`,children:C.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>Q(C.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete \\"${C.text}\\"`,title:`Delete \\"${C.text}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:x===C.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send \\"${C.text}\\"`,title:`Send \\"${C.text}\\"`,children:t.jsx(k,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(Vt,{align:"end",className:"w-56",children:[t.jsx(Ct,{onClick:()=>at(C.text),children:"Send to current session"}),t.jsx(Ct,{onClick:()=>qe(C.id,C.text),children:"Send to new session"})]})]})]})]})},C.id)})})})})}),d.length>=7&&t.jsx("div",{className:F("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",oe&&"bg-[var(--interactive-border)]"),onPointerDown:Ge,role:"separator","aria-orientation":"horizontal","aria-label":"Resize todo list"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Plans"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:w.length===1?`${w.length} file`:`${w.length} files`})]}),t.jsx("input",{ref:Le,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:C=>{const K=C.target.files?.[0]??null;be(K),C.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:_,disabled:!e||ke,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Import plan from file",title:"Import plan from file",children:t.jsx(k,{name:"add",className:"h-3.5 w-3.5"})})]}),t.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:w.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No saved plans yet."}):t.jsx("ul",{className:"divide-y divide-border/50",children:w.map(C=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>Ie(C),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[t.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:C.title}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(C.createdAt).toLocaleDateString("en-US")})]}),t.jsx("button",{type:"button",onClick:()=>{bt(C.id)},disabled:pt===C.id,className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",title:"Delete plan","aria-label":`Delete plan \\"${C.title}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id))})})]}),t.jsx(km,{open:D!==null,onOpenChange:C=>{!C&&!m&&S(null)},projectDirectory:e?.path??null,submitting:m,onConfirm:mt})]}):t.jsx("div",{className:F("w-full min-w-0 p-3",r),children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},Rx=({onActionComplete:e})=>{const s=Ut(c=>c.activeProjectId),n=Ut(c=>c.projects),r=zs(c=>c.homeDirectory),i=o.useMemo(()=>s?n.find(c=>c.id===s)??n[0]??null:n[0]??null,[s,n]),a=o.useMemo(()=>i?{id:i.id,path:i.path}:null,[i]),l=o.useMemo(()=>i?i.label?.trim()||Bs(i.path,r)||i.path:null,[i,r]);return t.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:t.jsx(Pm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Qn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),ho=512*1024,Tm=new TextEncoder,Em=new TextDecoder,Ir=e=>{const s=Tm.encode(e);if(s.byteLength<=ho)return{text:e,byteLength:s.byteLength};let n=s.byteLength-ho;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Em.decode(r),byteLength:r.byteLength}},Ws=(e,s)=>`${e}\0${s}`,Dr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},Rm="terminal-store";let Vi=!1,qi=0;const Un=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(qi+=1,`tab-${Date.now().toString(36)}-${qi.toString(36)}`),Pr=e=>typeof e=="object"&&e!==null,Mm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function zt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Fm=/^Terminal(?: (\d+))?$/,Lm=e=>{let s=0;for(const n of e){const r=Fm.exec(n.label);if(!r)continue;const i=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(i)&&(s=Math.max(s,i))}return s===0?"Terminal":`Terminal ${s+1}`},Tr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Er=e=>({tabs:[e],activeTabId:e.id}),is=(e,s)=>e.tabs.findIndex(n=>n.id===s);let Rr=null,Mr=null;const Om=e=>{if(Mr&&Rr?.sessions===e.sessions&&Rr.nextTabId===e.nextTabId)return Mr;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(i=>({id:i.id,label:i.label,iconKey:i.iconKey,createdAt:i.createdAt}))}]),nextTabId:e.nextTabId};return Rr={sessions:e.sessions,nextTabId:e.nextTabId},Mr=s,s},Bm=()=>{const e=$u(()=>Nu());if(!e)return;let s=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==s)return s=r.state,e.setItem(n,r)},removeItem:n=>(s=null,e.removeItem(n))}},Ee=ws()(La(vo((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=zt(n);r&&e(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=Un(),c=Tr(l,"Terminal");return a.set(r,Er(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=zt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=zt(n),i=s().sessions.get(r);if(!i)return;const a=i.activeTabId;return a?i.tabs.find(l=>l.id===a)??i.tabs[0]:i.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Ws(zt(n),r))??Qn,createTab:n=>{const r=zt(n);if(!r)return"tab-invalid";const i=Un();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Lm(c?.tabs??[]),b=Tr(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,b]}):l.set(r,Er(b)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||is(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=zt(n),l=i.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const b=is(u,r);if(b<0||u.tabs[b]?.label===l)return c;const h=[...u.tabs];return h[b]={...h[b],label:l},d.set(a,{...u,tabs:h}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const b=i?.trim()||null;if(d.tabs[u]?.iconKey===b)return l;const h=[...d.tabs];return h[u]={...h[u],iconKey:b},c.set(a,{...d,tabs:h}),{sessions:c}})},closeTab:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=is(c,r);if(d<0)return a;const u=c.tabs.filter(g=>g.id!==r),b=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,g])=>!(g.directory===i&&g.tabId===r))),h=Object.keys(b).length!==Object.keys(a.projectActionRuns).length,x=Ws(i,r),y=a.buffers.has(x)?Dr(a.buffers,g=>g===x):null;if(u.length===0){const g=Un(),w=Tr(g,"Terminal");return l.set(i,Er(w)),{sessions:l,nextTabId:a.nextTabId+1,...y?{buffers:y}:{},...h?{projectActionRuns:b}:{}}}let f=c.activeTabId;return c.activeTabId===r&&(f=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:f}),{sessions:l,...y?{buffers:y}:{},...h?{projectActionRuns:b}:{}}})},setTabSessionId:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const b=d.tabs[u],h=i!==null&&b.terminalSessionId!==i,x=i?"running":b.terminalSessionId?"exited":b.lifecycle,y={...b,terminalSessionId:i,lifecycle:x,isConnecting:!1},f=Ws(a,r),g=h&&l.buffers.has(f)?Dr(l.buffers,v=>v===f):null,w=[...d.tabs];return w[u]=y,c.set(a,{...d,tabs:w}),{sessions:c,...g?{buffers:g}:{}}})},setTabLifecycle:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const b=[...d.tabs];return b[u]={...b[u],lifecycle:i,isConnecting:!1},c.set(a,{...d,tabs:b}),{sessions:c}})},setConnecting:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const b=[...d.tabs];return b[u]={...b[u],isConnecting:i},c.set(a,{...d,tabs:b}),{sessions:c}})},replaceBuffer:(n,r,i,a)=>{const l=zt(n);e(c=>{const d=c.sessions.get(l);if(!d||is(d,r)<0)return c;const u=Ws(l,r),b=c.buffers.get(u)??Qn;if(b.lastSequence>a)return c;const h=Ir(i);if(b.lastSequence===a&&b.byteLength===h.byteLength&&b.chunks.map(f=>f.data).join("")===h.text)return c;const x=c.nextChunkId,y=new Map(c.buffers);return y.set(u,{chunks:h.text?[{id:x,data:h.text,byteLength:h.byteLength}]:[],byteLength:h.byteLength,lastSequence:a}),{buffers:y,nextChunkId:h.text?x+1:x}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=zt(n);e(d=>{const u=d.sessions.get(c);if(!u||is(u,r)<0)return d;const b=Ws(c,r),h=d.buffers.get(b)??Qn;if(a!==void 0&&a<=h.lastSequence)return d;const x=d.nextChunkId,y=Ir(i),f=l!==void 0&&l!==i?Ir(l).text:void 0,g={id:x,data:y.text,...f!==void 0?{replayData:f}:{},byteLength:y.byteLength},w=[...h.chunks,g];let v=h.byteLength+g.byteLength;for(;v>ho&&w.length>1;){const S=w.shift();if(!S)break;v-=S.byteLength}const D=new Map(d.buffers);return D.set(b,{chunks:w,byteLength:v,lastSequence:a??h.lastSequence}),{buffers:D,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=zt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const b=is(u,r);if(b<0)return c;const h=u.tabs[b],x=a.autoOpened??h.previewAutoOpened,y=a.locked??h.previewUrlLocked;if(h.previewUrl===i&&h.previewAutoOpened===x&&h.previewUrlLocked===y)return c;const f=[...u.tabs];return f[b]={...h,previewUrl:i,previewAutoOpened:x,previewUrlLocked:y},d.set(l,{...u,tabs:f}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=is(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const b=[...c.tabs];return b[d]={...u,previewAutoOpened:!0},l.set(i,{...c,tabs:b}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const i=r.projectActionRuns[n.key];return i&&i.directory===n.directory&&i.actionId===n.actionId&&i.tabId===n.tabId&&i.sessionId===n.sessionId&&i.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(i=>{const a=i.projectActionRuns[n];return!a||a.status===r?i:{projectActionRuns:{...i.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const i={...r.projectActionRuns};return delete i[n],{projectActionRuns:i}})},removeDirectory:n=>{const r=zt(n);e(i=>{const a=new Map(i.sessions);a.delete(r);const l=Ws(r,""),c=Dr(i.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Rm,storage:Bm(),partialize:Om,merge:(e,s)=>{if(!Pr(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let i=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!Pr(u))continue;const b=Array.isArray(u.tabs)?u.tabs:[],h=[],x=new Map;for(const w of b){if(!Pr(w))continue;const v=typeof w.id=="string"?w.id:null;if(!v)continue;const D=Mm(v);D!==null&&(i=Math.max(i,D));const S=D===null?v:Un();x.set(v,S),h.push({id:S,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(h.length===0)continue;const y=typeof u.activeTabId=="string"?u.activeTabId:null,f=y?x.get(y)??y:null,g=f?h.some(w=>w.id===f):!1;r.set(d,{tabs:h,activeTabId:g?f:h[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,i+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!Vi){Vi=!0;const e=Ee.persist,s=()=>{Ee.getState().hasHydrated||Ee.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function _m(e){const{colors:s}=e,n=s.syntax.base;return{background:s.surface.background,foreground:n.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:s.surface.elevatedForeground}}function zm(e,s,n,r,i=!1){const l=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:i}}const Fr=["\x1B[0m","\x1B[m"],Um=e=>{const s=e.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const i=r.slice(1,4).map(Number);return i.some(a=>a<0||a>255)?null:i},Qi=e=>{const s=Um(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},$m=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...Fr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);Fr.some(b=>b.length>u.length&&b.startsWith(u))&&(i=d)}const l=i>0?r.slice(-i):"";let c=i>0?r.slice(0,-i):r;for(const d of Fr)c=c.replaceAll(d,n);return{data:c,carry:l}},Gm=(e,s,n,r,i)=>{if(n.width<=0||n.height<=0||r<=0||i<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*i);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(i-1,l))}},Km=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let i=n,a=n;for(;i>0&&r(e[i-1]);)i-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:i,endColumn:a}};let Hm=null;const Wm=()=>Hm??=Qs(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,8])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Ym=2e3,Vm=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(s=>setTimeout(s,Ym))]).then(()=>{})},qm=(e,s,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${s}`;const i=r.measureText("M"),a=Math.ceil(i.width),l=Math.ceil((i.actualBoundingBoxAscent||n*.8)+(i.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},gl=o.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:i,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:b=!0},h)=>{const x=o.useRef(null),y=o.useRef(null),f=o.useRef(null),g=o.useRef(n),w=o.useRef(r),v=o.useRef(null),D=o.useRef(null),S=o.useRef(null),m=o.useRef(""),p=o.useRef(""),N=o.useRef(Qi(i.background)),T=o.useRef(!1),A=o.useRef(0),P=o.useRef(b),E=o.useRef(!1),[R,L]=o.useState(0),[Y,X]=o.useState(0);g.current=n,w.current=r,P.current=b,N.current=Qi(i.background),o.useLayoutEffect(()=>{const B=x.current;if(!B)return;const O=qm(B,a,l);D.current=O,O&&w.current(O.cols,O.rows)},[a,l]);const oe=o.useCallback(()=>{const B=x.current,O=y.current;if(!B||!O||!f.current||!P.current)return;const J=B.getBoundingClientRect();if(!(J.width<24||J.height<24))try{f.current.fit();const de={cols:O.cols,rows:O.rows};(!v.current||v.current.cols!==de.cols||v.current.rows!==de.rows)&&(v.current=de,w.current(de.cols,de.rows)),E.current||(E.current=!0,L(G=>G+1))}catch{}},[]),$=o.useCallback(()=>{if(T.current||!m.current||!y.current)return;const B=y.current,O=m.current;m.current="";const J=$m(O,p.current,N.current);if(p.current=J.carry,!J.data){m.current&&$();return}T.current=!0;const de=A.current;B.write(J.data,()=>{y.current!==B||A.current!==de||(T.current=!1,m.current&&$())})},[]),H=o.useCallback(()=>{S.current=null,m.current="",p.current="",T.current=!1,A.current+=1;const B=y.current;if(!B){X(O=>O+1);return}try{B.reset();const O=N.current;O&&B.write(`${O}\x1B[2J\x1B[H`)}catch{X(O=>O+1)}},[]);return o.useEffect(()=>{const B=x.current;if(!B)return;let O=!1,J=null,de=null,G=null,Ce=null,Me=[];const He=()=>{J&&P.current&&(J.options.cursorBlink=!0)},ze=te=>{te.relatedTarget instanceof Node&&B.contains(te.relatedTarget)||J&&(J.options.cursorBlink=!1)},Be=()=>{J&&P.current&&B.contains(document.activeElement)&&(J.options.cursorBlink=!0)},Pe=()=>{J&&(J.options.cursorBlink=!1)};return B.addEventListener("focusin",He),B.addEventListener("focusout",ze),window.addEventListener("focus",Be),window.addEventListener("blur",Pe),Promise.all([Wm(),Vm()]).then(([{module:te,ghostty:xe}])=>{if(O)return;J=new te.Terminal({...zm(a,l,i,xe,!1),...D.current??{}});const Ge=new te.FitAddon;J.loadAddon(Ge),J.open(B),y.current=J,f.current=Ge,Me=[J.onData(ye=>g.current(ye))],de=new ResizeObserver(()=>{G&&clearTimeout(G),G=setTimeout(oe,80)}),de.observe(B),oe();const Ne=N.current;Ne&&J.write(`${Ne}\x1B[2J\x1B[H`),Ce=requestAnimationFrame(oe)}),()=>{O=!0;const te=document.activeElement;te instanceof HTMLElement&&B.contains(te)&&(te.blur(),window.Capacitor?.getPlatform?.()==="android"&&Qs(async()=>{const{Keyboard:Ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:Ge}},__vite__mapDeps([113,114])).then(({Keyboard:Ge})=>Ge.hide()).catch(()=>{})),de?.disconnect(),G&&clearTimeout(G),Ce!==null&&cancelAnimationFrame(Ce),B.removeEventListener("focusin",He),B.removeEventListener("focusout",ze),window.removeEventListener("focus",Be),window.removeEventListener("blur",Pe),Me.forEach(xe=>xe.dispose()),J?.dispose(),y.current=null,f.current=null,v.current=null,S.current=null,m.current="",p.current="",T.current=!1,A.current+=1,E.current=!1}},[oe,a,l,Y,i]),o.useEffect(()=>{const B=y.current,O=x.current;!B||!O||(B.options.cursorBlink=b&&document.hasFocus()&&O.contains(document.activeElement))},[b,R]),o.useEffect(()=>{if(!y.current)return;if(s.length===0){S.current!==null&&H();return}const O=S.current;let J=-1;if(O!==null){for(let Ce=s.length-1;Ce>=0;Ce-=1){const Me=s[Ce].id;if(Me===O){J=Ce;break}if(Me<O)break}if(J<0){H();return}}const de=J<0,G=J>=0?s.slice(J+1):s;m.current+=G.map(Ce=>de?Ce.replayData??Ce.data:Ce.data).join(""),S.current=s.at(-1)?.id??null,$()},[s,$,R,H]),o.useEffect(()=>{if(!u||!b)return;const B=requestAnimationFrame(()=>y.current?.focus());return()=>cancelAnimationFrame(B)},[u,b,R,e]),o.useEffect(()=>{const B=x.current;if(!d||!B)return;const O=J=>{const de=J;if(!de.isComposing)switch(de.inputType){case"insertText":de.data&&g.current(de.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return B.addEventListener("beforeinput",O),()=>B.removeEventListener("beforeinput",O)},[d,R]),o.useEffect(()=>{const B=x.current,O=y.current;if(!d||!B||!O)return;let J=null,de=null,G="idle",Ce=0,Me=0,He=0,ze=0,Be=null;const Pe=Math.max(12,l+2),te=()=>{window.Capacitor?.getPlatform?.()==="android"&&Qs(async()=>{const{Keyboard:pe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:pe}},__vite__mapDeps([113,114])).then(({Keyboard:pe})=>pe.show()).catch(()=>{})},xe=()=>{de&&(clearTimeout(de),de=null)},Ge=(V,pe)=>{const q=B.querySelector("canvas");return q?Gm(V,pe,q.getBoundingClientRect(),O.cols,O.rows):null},Ne=(V,pe)=>{const q=B.querySelector("canvas");if(!q)return;const ve=q.getBoundingClientRect(),we=ve.left+(pe.column+.5)/O.cols*ve.width,Re=ve.top+(pe.row+.5)/O.rows*ve.height;q.dispatchEvent(new MouseEvent(V,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:we,clientY:Re}))},ye=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},Ae=V=>{V.pointerType!=="touch"||J!==null||(J=V.pointerId,G="pending",Ce=V.clientX,Me=V.clientY,He=V.clientY,ze=0,Be=null,B.setPointerCapture(V.pointerId),de=setTimeout(()=>{if(de=null,J!==V.pointerId||G!=="pending")return;const pe=Ge(Ce,Me);if(!pe)return;const q=O.buffer.active,ve=Math.max(0,q.length-O.rows-q.viewportY+pe.row),we=q.getLine(ve),Re=Array.from({length:O.cols},(mt,Le)=>we?.getCell(Le)?.getChars()??""),qe=Km(Re,pe.column),at={column:qe.startColumn,row:pe.row};Be={column:qe.endColumn,row:pe.row},G="selecting",Ne("mousedown",at),Ne("mousemove",Be)},350))},ot=V=>{if(J!==V.pointerId)return;if(G==="selecting"){const ve=Ge(V.clientX,V.clientY);ve&&(!Be||ve.column!==Be.column||ve.row!==Be.row)&&(Be=ve,Ne("mousemove",ve)),V.cancelable&&V.preventDefault();return}if(G==="pending"){if(Math.hypot(V.clientX-Ce,V.clientY-Me)<8)return;xe(),G="scrolling"}if(G!=="scrolling")return;const pe=He-V.clientY;He=V.clientY,ze+=pe;const q=Math.trunc(ze/Pe);q&&(O.scrollLines(q),ze-=q*Pe),V.cancelable&&V.preventDefault()},We=V=>{if(J!==V.pointerId)return;const pe=G==="pending",q=G==="selecting";xe(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),J=null,G="idle",q&&ye(),pe&&(O.focus(),te())},Q=V=>{if(J!==V.pointerId)return;const pe=G==="selecting";xe(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),J=null,G="idle",pe&&ye()};return B.addEventListener("pointerdown",Ae),B.addEventListener("pointermove",ot,{passive:!1}),B.addEventListener("pointerup",We),B.addEventListener("pointercancel",Q),()=>{xe(),B.removeEventListener("pointerdown",Ae),B.removeEventListener("pointermove",ot),B.removeEventListener("pointerup",We),B.removeEventListener("pointercancel",Q)}},[d,l,R]),o.useImperativeHandle(h,()=>({focus:()=>y.current?.focus(),fit:oe,getSelection:()=>{const B=y.current,O=B?.getSelectionPosition(),J=B?.getSelection()??"";return!O||!J.trim()?null:{text:J,startLine:O.start.y+1,endLine:O.end.y+1}}}),[oe]),t.jsx("div",{ref:x,"data-terminal-owner":"main",className:F("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});gl.displayName="TerminalViewport";const Qm=280,Ji=4,Jm=({transform:e})=>({...e,y:0}),Xm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=dr({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:ur.Transform.toString(l),transition:c},className:F("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},Zm=({id:e,children:s,className:n})=>t.jsx("div",{className:F("h-full",n),"data-sortable-tab-id":e,children:s}),eg=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:i,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:b,activePillLowercase:h=!0,nonCompositedIndicator:x=!1,className:y})=>{const f=re(Q=>Q.isMobile),{isTablet:g}=Us(),w=f||g,v=o.useRef(null),[D,S]=o.useState({left:!1,right:!1}),m=o.useMemo(()=>e.map(Q=>Q.id),[e]),p=a==="scrollable",N=l==="default",T=l==="active-pill",P=T||l==="animated",E=N,R=P||E,L=T&&p,Y=P,X=b??P,oe=typeof i=="function",$=oe?Xm:Zm,H=o.useRef(new Map),[B,O]=o.useState(null),[J,de]=o.useState(!1),[G,Ce]=o.useState(null),Me=o.useRef(!1),He=o.useRef(0),ze=o.useRef(s),Be=o.useRef(null),Pe=o.useMemo(()=>{if(!R||!G||!s||G===s)return 0;const Q=e.findIndex(pe=>pe.id===G),V=e.findIndex(pe=>pe.id===s);return Q<0||V<0?0:Q>V?Ji:-Ji},[s,e,G,R]),te=ar(vn(wo,{activationConstraint:{distance:8}})),xe=o.useCallback((Q,V)=>!Q||!V?Q===V:Math.abs(Q.left-V.left)<.5&&Math.abs(Q.top-V.top)<.5&&Math.abs(Q.width-V.width)<.5&&Math.abs(Q.height-V.height)<.5,[]),Ge=o.useCallback((Q,V)=>{if(V){H.current.set(Q,V);return}H.current.delete(Q)},[]),Ne=o.useCallback(()=>{if(!R||!s){O(Re=>Re===null?Re:null);return}const Q=v.current,V=H.current.get(s);if(!Q||!V){O(Re=>Re===null?Re:null);return}let pe=0,q=0,ve=V;for(;ve&&ve!==Q;)pe+=ve.offsetLeft,q+=ve.offsetTop,ve=ve.offsetParent;const we={left:pe,top:q,width:V.offsetWidth,height:V.offsetHeight};O(Re=>xe(Re,we)?Re:we)},[s,xe,R]),ye=o.useCallback(()=>{if(!p){S({left:!1,right:!1});return}const Q=v.current;if(!Q){S({left:!1,right:!1});return}S({left:Q.scrollLeft>2,right:Q.scrollLeft+Q.clientWidth<Q.scrollWidth-2})},[p]);o.useEffect(()=>{if(!p){S({left:!1,right:!1});return}const Q=v.current;if(!Q)return;ye(),Q.addEventListener("scroll",ye,{passive:!0});const V=new ResizeObserver(ye);return V.observe(Q),()=>{Q.removeEventListener("scroll",ye),V.disconnect()}},[p,e.length,ye]),o.useEffect(()=>{if(!R){O(null);return}Ne();const Q=v.current;if(!Q)return;const V=new ResizeObserver(()=>{performance.now()-He.current>Qm&&de(!1),Ne()});if(V.observe(Q),s){const pe=H.current.get(s);pe&&V.observe(pe)}return()=>{V.disconnect()}},[s,e.length,Ne,R]),o.useLayoutEffect(()=>{Ne()});const Ae=m.join("\0");o.useLayoutEffect(()=>{if(!R){Me.current=!1,de(!1);return}const Q=Be.current!==Ae;if(Be.current=Ae,!Me.current){Me.current=!0,ze.current=s;return}const V=ze.current!==s;if(ze.current=s,!V||Q){de(!1);return}He.current=performance.now(),de(!0)},[s,Ae,R]),o.useEffect(()=>{if(!p||!s)return;const Q=v.current;if(!Q)return;const V=window.requestAnimationFrame(()=>{const pe=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),q=Q.querySelector(`[data-sortable-tab-id="${pe}"]`);q&&(q.scrollIntoView({block:"nearest",inline:"nearest"}),ye())});return()=>{window.cancelAnimationFrame(V)}},[s,p,e.length,ye]);const ot=o.useCallback(Q=>{if(!i)return;const{active:V,over:pe}=Q;!pe||V.id===pe.id||i(String(V.id),String(pe.id))},[i]),We=t.jsxs("div",{className:F("relative flex h-full min-w-0 flex-1",y),children:[p&&D.left?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",P?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,p&&D.right?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",P?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:v,className:F("relative flex h-full min-w-0 flex-1",P?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",P&&"@container/pill-tabs",P&&"pill-tabs__track",P&&(c??"gap-0.5 py-0.5"),E&&"items-center overflow-y-hidden",Y&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",p?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:p?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[P&&B?t.jsx("div",{className:F("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",X&&J&&(x?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:x?{left:`${B.left+Pe}px`,top:`${B.top}px`,width:`${B.width}px`,height:`${B.height}px`}:{transform:`translate3d(${B.left+Pe}px, ${B.top}px, 0)`,width:`${B.width}px`,height:`${B.height}px`}}):null,E&&B?t.jsx("div",{className:F("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",J&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${B.left+Pe}px, 0, 0)`,width:`${B.width}px`},"aria-hidden":!0}):null,e.map(Q=>{const V=Q.id===s,pe=u&&P&&!V&&!!Q.icon,q=!pe,ve=!!Q.icon,we=u&&P&&V&&!p&&!L,Re=Q.closable!==!1&&!!r,qe=Re&&!!Q.icon,at=p||L?void 0:P?we?"flex-none basis-auto":f?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",mt=Re?ke=>{ke.button===1&&(ke.preventDefault(),ke.stopPropagation(),r?.(Q.id))}:void 0,Le=Re?ke=>{ke.button===1&&ke.preventDefault()}:void 0;return t.jsx($,{id:Q.id,className:at,children:t.jsxs("div",{ref:ke=>Ge(Q.id,ke),onAuxClick:mt,onMouseDown:Le,className:F("group flex h-full min-w-0 flex-nowrap items-center",p||L?"shrink-0":P?"w-full":"w-full min-w-0",P?"relative z-10 bg-transparent":V?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":V,"aria-label":pe?Q.title??Q.label:void 0,onClick:()=>n(Q.id),onPointerDown:R?()=>{de(!0),Ce(Q.id)}:void 0,onPointerUp:R?()=>Ce(null):void 0,onPointerLeave:R?()=>Ce(null):void 0,onPointerCancel:R?()=>Ce(null):void 0,className:F(P?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",P&&h?"lowercase":null,P&&(pe?"gap-0":"gap-1.5"),P?L?"shrink-0 whitespace-nowrap px-3 text-center":p?"max-w-56 shrink-0 px-3 text-center":pe?"px-2 !min-w-0 text-center":we?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":p?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",P?d??(T?f?"h-[38px]":"h-[31px]":"h-7"):null,P?V?"text-foreground":"text-muted-foreground hover:text-foreground":null,P?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:Q.title??Q.label,children:P?t.jsxs(t.Fragment,{children:[ve?t.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",qe&&(w?"opacity-0":"group-hover:opacity-0")),children:Q.icon}),qe?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",w?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:ke=>{ke.stopPropagation()},onClick:ke=>{ke.stopPropagation(),r?.(Q.id)},"aria-label":Q.closeLabel??`Close ${Q.label} tab`,title:Q.closeLabel??`Close ${Q.label} tab`,children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,q?t.jsx("span",{className:"animated-tabs__label truncate",children:Q.label}):null]}):t.jsxs("span",{className:F("flex min-w-0 flex-nowrap items-center gap-1.5",!p&&"justify-center"),children:[ve?t.jsxs("span",{className:F("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",V?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",qe&&(w?"opacity-0":"group-hover:opacity-0")),children:Q.icon}),qe?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",w?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:ke=>{ke.stopPropagation()},onClick:ke=>{ke.stopPropagation(),r?.(Q.id)},"aria-label":Q.closeLabel??`Close ${Q.label} tab`,title:Q.closeLabel??`Close ${Q.label} tab`,children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,t.jsx("span",{className:"truncate leading-[1.2]",children:Q.label})]})}),Re&&!qe?t.jsx("button",{type:"button",onPointerDown:ke=>{ke.stopPropagation()},onClick:ke=>{ke.stopPropagation(),r?.(Q.id)},className:F("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",P?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",P?V?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":V?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":Q.closeLabel??`Close ${Q.label} tab`,title:Q.closeLabel??`Close ${Q.label} tab`,children:t.jsx(k,{name:"close",className:"h-3 w-3"})}):null]})},Q.id)})]})]});return oe?t.jsxs(lr,{sensors:te,collisionDetection:cr,onDragEnd:ot,modifiers:[Jm],children:[t.jsx(So,{items:m,strategy:qu,children:We}),t.jsx(Oa,{dropAnimation:null})]}):We},tg="\x1B",sg=new RegExp(`${tg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),ng=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,rg=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,og=/Serving HTTP on .*? port (\d{2,5})/i,ig=new Set([".",",",";",":","!","?"]),ag=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",i=s.slice(0,-1),a=(i.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(i.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=i;continue}if(ig.has(n)){s=s.slice(0,-1);continue}break}return s},Xi=e=>{let s=ag(e);return s=s.replace("0.0.0.0","127.0.0.1"),s=s.replace("[::1]","127.0.0.1"),s=s.replace("[::]","127.0.0.1"),s},lg=e=>{if(!e)return null;const s=e.replace(sg,""),n=s.match(og);if(n?.[1]){const i=Number.parseInt(n[1],10);if(Number.isFinite(i)&&i>0&&i<=65535)return`http://127.0.0.1:${i}/`}const r=s.split(`
49
- `);for(const i of r){if(!rg.test(i))continue;const a=Array.from(i.matchAll(ng));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Xi(c[1])).port}catch{return!1}});return Xi((l??a[0])[1])}return null},cg=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const i=new AbortController,a=window.setTimeout(()=>i.abort(),s);try{const l=await Xt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:i.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},dg={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ug=(e,s)=>{if(s&&e.startsWith("arrow-")){const n=s==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return dg[e]},xl=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},fg=(e,s)=>e&&(s==="ctrl"?xl(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Zi={cols:80,rows:24},Mx=({visible:e})=>{const{terminal:s,runtime:n}=nr(),{currentTheme:r}=Ca(),i=o.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});i.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=Gd(),l=re(z=>z.terminalFontSize),c=re(z=>z.terminalShell),d=re(z=>z.terminalLoginShells.includes(z.terminalShell)),{isMobile:u,isTablet:b,hasTouchOnlyPointer:h}=Us(),x=u||b,y=(x||h)&&n.platform==="web",f=!0,g=re(z=>z.showTerminalQuickKeysOnDesktop),w=x||g,v=_e(z=>z.currentSessionId),D=_e(z=>z.newSessionDraft),S=v!==null||D?.open===!0,m=Kd()??null,p=Ee(z=>m?z.sessions.get(m):void 0),N=Ee(z=>z.hasHydrated),T=Ee(z=>z.ensureDirectory),A=Ee(z=>z.createTab),P=Ee(z=>z.setActiveTab),E=Ee(z=>z.closeTab),R=Ee(z=>z.setTabSessionId),L=Ee(z=>z.setTabLifecycle),Y=Ee(z=>z.setConnecting),X=Ee(z=>z.appendToBuffer),oe=Ee(z=>z.replaceBuffer),$=Ee(z=>z.setTabPreviewUrl),H=xa(z=>z.addDraft),B=re(z=>z.openContextPreview),O=o.useMemo(()=>p?p.activeTabId??p.tabs[0]?.id??null:null,[p,f]),J=o.useMemo(()=>{if(p)return O?p.tabs.find(z=>z.id===O)??p.tabs[0]:p.tabs[0]},[p,O]),de=o.useMemo(()=>(p?.tabs??[]).map(z=>({icon:(()=>{const ie=z.iconKey?pn[z.iconKey]??"terminal":"terminal";return t.jsx(k,{name:ie,className:"h-4 w-4"})})(),id:z.id,label:z.label,title:z.label,closeLabel:"Close tab"})),[p?.tabs]),G=J?.terminalSessionId??null,Ce=J?.lifecycle??"idle",Me=Ee(z=>m&&O?z.getBuffer(m,O).chunks:Qn.chunks),He=J?.isConnecting??!1,ze=J?.previewUrl??null,[Be,Pe]=o.useState(null),[te,xe]=o.useState(!1),[Ge,Ne]=o.useState(!1),[ye,Ae]=o.useState(null),[ot,We]=o.useState(!1),Q=o.useRef(null),V=o.useRef(null),pe=o.useRef(O),q=o.useRef(G),ve=o.useRef(m),we=o.useRef(null),Re=o.useRef(null),qe=o.useRef(new Set),at=o.useRef(""),mt=o.useRef(new Set),Le=o.useRef(0),ke=o.useCallback(()=>{at.current="",mt.current.clear(),Le.current+=1},[]),Ye=o.useCallback(()=>{y||typeof document<"u"&&!document.hasFocus()||we.current?.focus()},[y]),pt=o.useCallback(()=>{y||we.current?.focus()},[y]),bt=re(z=>z.activeMainTab)==="terminal",_=e??bt,[be,Ie]=o.useState(_);o.useEffect(()=>{_&&Ie(!0)},[_]),o.useEffect(()=>{q.current=G},[G]),o.useEffect(()=>{!G||!s.updateAppearance||s.updateAppearance(G,i.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,G]),o.useEffect(()=>{pe.current=O,ke()},[O,ke]),o.useEffect(()=>{ve.current=m},[m]),o.useEffect(()=>{!w&&ye!==null&&Ae(null)},[w,ye,Ae]),o.useEffect(()=>{!G&&ye!==null&&Ae(null)},[G,ye,Ae]);const C=o.useCallback(()=>{Q.current?.(),Q.current=null,V.current=null,Ne(!1)},[]);o.useEffect(()=>()=>{C(),q.current=null},[C]);const K=o.useCallback((z,ie,ge)=>{if(!ge)return;const et=`${at.current}${ge}`.replace(/\r\n|\r/g,`
50
- `),je=et.split(`
51
- `),$e=et.endsWith(`
52
- `)?je.join(`
53
- `):je.slice(0,-1).join(`
54
- `);if(at.current=et.endsWith(`
55
- `)?"":(je[je.length-1]??"").slice(-1024),!$e)return;const ct=lg($e);if(!ct||mt.current.has(ct))return;const At=Le.current;mt.current.add(ct),cg(ct).then(_t=>{if(mt.current.delete(ct),!_t||Le.current!==At)return;const Mt=Ee.getState().getDirectoryState(z)?.tabs.find(Zt=>Zt.id===ie);!Mt||Mt.previewUrlLocked||Mt.previewUrl===ct||$(z,ie,ct,{locked:!1,autoOpened:!1})})},[$]),ee=o.useCallback((z,ie,ge)=>{if(V.current===ge)return;C(),V.current=ge;const et=s.connect(ge,{onEvent:je=>{if(V.current===ge)switch(je.type){case"snapshot":{Y(z,ie,!1),Pe(null),xe(!1),Ne(!1),Ye(),oe(z,ie,je.data??"",je.sequence??0),K(z,ie,je.data??""),je.status==="exited"&&L(z,ie,"exited");break}case"reconnecting":{Pe(null),xe(!1),Ne(!0);break}case"data":{je.data&&(X(z,ie,je.data,je.sequence,je.replayData),K(z,ie,je.data));break}case"exit":{const $e=typeof je.exitCode=="number"?je.exitCode:null,ct=typeof je.signal=="number"?je.signal:null,_t=!!Ee.getState().getDirectoryState(z)?.tabs.find(Mt=>Mt.id===ie)?.label?.startsWith("Action:");X(z,ie,`\\r\\n[Process exited${$e!==null?` with code ${$e}`:""}${ct!==null?` (signal ${ct})`:""}]\\r\\n`),L(z,ie,"exited"),Y(z,ie,!1),Pe(_t?null:"Terminal session ended"),xe(!1),Ne(!1),C();break}}},onError:(je,$e)=>{if(V.current===ge){if(!$e){Pe(null),xe(!1);return}if(Ne(!1),je.code==="SESSION_NOT_FOUND"&&!Ee.getState().getDirectoryState(z)?.tabs.find(At=>At.id===ie)?.label?.startsWith("Action:")){Pe(null),xe(!1),Y(z,ie,!1),R(z,ie,null),L(z,ie,"idle"),C();return}Pe(`Connection failed: ${je.message}`),xe(!0),Y(z,ie,!1),L(z,ie,"exited"),R(z,ie,null),C()}}});Q.current=()=>{et.close(),V.current=null}},[X,oe,C,Ye,K,Y,L,R,s]);o.useEffect(()=>{let z=!1;if(!N||!be)return;if(!m){Pe(S?"No working directory available for terminal.":"Select a session to open the terminal."),C();return}return(async()=>{const ge=m;if(!ve.current||ve.current!==ge)return;if(!Ee.getState().getDirectoryState(ge)){T(ge);return}const je=Ee.getState().getDirectoryState(ge);if(!je||je.tabs.length===0)return;const $e=je.activeTabId??je.tabs[0]?.id??null;if(!$e)return;const ct=je.tabs.find(Nt=>Nt.id===$e)??je.tabs[0],At=ct?.terminalSessionId??null,_t=ct?.lifecycle??"idle",Mt=!!ct?.label?.startsWith("Action:"),Zt=Ee.getState().getBuffer(ge,$e),qt=Zt.byteLength>0||Zt.chunks.length>0;if(!At){if(_t==="exited"){Y(ge,$e,!1);return}if(Mt&&qt){Y(ge,$e,!1);return}const Nt=`${ge}\0${$e}`;if(qe.current.has(Nt))return;const Bt=Re.current??Zi;qe.current.add(Nt),Pe(null),xe(!1),Ne(!1),Y(ge,$e,!0);try{const U=await s.createSession({cwd:ge,sessionId:$e,cols:Bt.cols,rows:Bt.rows,shell:c,loginShell:d,...i.current}),Z=!z&&ve.current===ge&&pe.current===$e;if(!Ee.getState().getDirectoryState(ge)?.tabs.find(he=>he.id===$e)){try{await s.close(U.sessionId)}catch{}return}if(R(ge,$e,U.sessionId),!Z)return;const ce=Re.current;ce&&(ce.cols!==Bt.cols||ce.rows!==Bt.rows)&&s.resize({sessionId:U.sessionId,...ce}).catch(()=>{});return}catch(U){const Z=Ee.getState().getDirectoryState(ge)?.tabs.find(ne=>ne.id===$e);if(!Z||Z.terminalSessionId||(Y(ge,$e,!1),ve.current!==ge||pe.current!==$e))return;Pe(U instanceof Error?U.message:"Failed to start terminal session"),xe(!0),Ne(!1);return}finally{qe.current.delete(Nt)}}!At||z||(q.current=At,ee(ge,$e,At))})(),()=>{z=!0,q.current=null,C()}},[S,m,G,Ce,O,be,f,N,T,Y,L,R,ee,C,s,d,c]),o.useEffect(()=>{if(!_||y)return;if(typeof window>"u"){Ye();return}const z=window.requestAnimationFrame(()=>{Ye()});return()=>{window.cancelAnimationFrame(z)}},[O,Ye,_,y]);const ue=o.useCallback(async()=>{if(!m||ot)return;const z=Ee.getState().getDirectoryState(m),ie=O??z?.activeTabId??z?.tabs[0]?.id??null;if(!ie)return;const ge=z?.tabs.find(et=>et.id===ie)?.terminalSessionId??null;if(!(!ge||!s.restartSession)){We(!0),Pe(null),xe(!1),Ne(!1),C(),ke();try{const et=Re.current??Zi,je=await s.restartSession(ge,{cwd:m,shell:c,loginShell:d,...et,...i.current});if(Ee.getState().getDirectoryState(m)?.tabs.find(ct=>ct.id===ie)?.terminalSessionId!==ge||(R(m,ie,je.sessionId),L(m,ie,"running"),ve.current!==m||pe.current!==ie))return;q.current=je.sessionId,ee(m,ie,je.sessionId)}catch(et){if(Ee.getState().getDirectoryState(m)?.tabs.find($e=>$e.id===ie)?.terminalSessionId!==ge||ve.current!==m||pe.current!==ie)return;Pe(et instanceof Error?et.message:"Failed to restart terminal"),xe(!1),Ne(!1),q.current=ge,ee(m,ie,ge)}finally{We(!1)}}},[O,C,m,f,ot,ke,L,R,ee,s,d,c]),me=o.useCallback(async()=>{await ue()},[ue]),Se=o.useCallback(()=>{if(!m)return;const z=A(m);P(m,z),Pe(null),xe(!1),Ne(!1),C()},[A,C,m,P]),Ve=o.useCallback(()=>{const z=we.current?.getSelection(),ie=v??(D?.open?"draft":null);!z||!ie||!J||!m||H({directory:m,sessionKey:ie},{source:"terminal",fileLabel:J.label,startLine:z.startLine,endLine:z.endLine,code:z.text,language:J.terminalSessionId??J.id,text:""})},[J,H,v,m,D?.open]),ft=o.useCallback(z=>{m&&(P(m,z),Pe(null),xe(!1),Ne(!1),C())},[C,m,P]),lt=o.useCallback(z=>{if(!m)return;z===O&&C(),Pe(null),xe(!1),Ne(!1);const ie=Ee.getState().getDirectoryState(m)?.tabs.find(ge=>ge.id===z)?.terminalSessionId;(async()=>{ie&&await s.close(ie),E(m,z)})().catch(ge=>Pe(ge instanceof Error?ge.message:"Terminal session ended"))},[O,E,C,m,s]),it=o.useCallback(z=>{if(!z||Ge)return;let ie=z,ge=!1;ye&&z.length>0&&(ie=fg(z,ye),ge=!0);const et=q.current;et&&(s.sendInput(et,ie).catch(je=>{Ge||Pe(je instanceof Error?je.message:"Failed to send input")}),ge&&(Ae(null),pt()))},[ye,pt,Ge,Ae,s]),gt=o.useCallback((z,ie)=>{const ge=Re.current;if((!ge||ge.cols!==z||ge.rows!==ie)&&(Re.current={cols:z,rows:ie}),!_)return;const et=q.current;et&&s.resize({sessionId:et,cols:z,rows:ie}).catch(()=>{})},[_,s]),Xe=o.useCallback(z=>{Ae(ie=>ie===z?null:z),pt()},[pt,Ae]),Oe=o.useCallback(z=>{const ie=ug(z,ye);ie&&(it(ie),Ae(null),pt())},[ye,pt,it,Ae]),Ze=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),vt=o.useCallback(z=>{if(z.repeat)return;const ie=z.key;if(!ie||ie==="Control"||ie==="Meta"||ie==="Alt"||ie==="Shift")return;const ge=ie.length===1?ie.toLowerCase():ie;if(ge in Ze){z.preventDefault(),z.stopPropagation(),Oe(Ze[ge]);return}if(ye!=="ctrl")return;const et=z.code??"",je=ie.length===1&&/[a-zA-Z]/.test(ie)?ie.toUpperCase():et.startsWith("Key")&&et.length===4?et.slice(3).toUpperCase():null;if(je&&je.length===1&&je>="A"&&je<="Z"){const $e=xl(je);if(!$e)return;z.preventDefault(),z.stopPropagation(),it($e),Ae(null),pt()}},[ye,pt,Oe,it,Ze,Ae]);o.useEffect(()=>{if(!(!w||!ye||!G))return window.addEventListener("keydown",vt),()=>window.removeEventListener("keydown",vt)},[ye,vt,w,G]);const Ot=o.useMemo(()=>{const z=ln[wr].stack;if(typeof window>"u")return(ln[a]??ln[wr]).stack;const ge=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ge&&ge.trim().length>0?ge.trim():(ln[a]??ln[wr]).stack??z},[a]),Et=o.useMemo(()=>_m(r),[r]),jt=`${m??"no-dir"}::${O??"no-tab"}`;if(o.useEffect(()=>{if(!_||y)return;const z=we.current;if(!z)return;const ie=()=>{z.fit()};if(typeof window<"u"){const ge=window.requestAnimationFrame(()=>{ie(),Ye()}),et=[220,400].map(je=>window.setTimeout(ie,je));return()=>{window.cancelAnimationFrame(ge),et.forEach(je=>window.clearTimeout(je))}}ie()},[Ye,_,y,jt,G]),o.useEffect(()=>{if(!_||!y)return;let z=null;const ie=()=>{z!==null&&window.cancelAnimationFrame(z),z=window.requestAnimationFrame(()=>{z=null,we.current?.fit()})};return window.addEventListener("oc:keyboard-settled",ie),()=>{window.removeEventListener("oc:keyboard-settled",ie),z!==null&&window.cancelAnimationFrame(z)}},[_,jt,y]),!S)return t.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!m)return t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{children:"No working directory available for this session."}),t.jsx("button",{onClick:ue,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const M=!G||He||ot||Ge,De=be,Fe=x?"lg":"xs",Je=x?"w-10 p-0":"w-9 p-0",dt=z=>{x&&z.preventDefault()},Rt=t.jsxs(t.Fragment,{children:[t.jsx(Qe,{type:"button",size:Fe,variant:"outline",onPointerDown:dt,onClick:()=>Oe("esc"),disabled:M,children:"Esc"}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("tab"),disabled:M,children:[t.jsx(k,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"chip","aria-pressed":ye==="ctrl",className:x?"px-3":"px-2",onPointerDown:dt,onClick:()=>Xe("ctrl"),disabled:M,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"chip","aria-pressed":ye==="alt",className:x?"px-3":"px-2",onPointerDown:dt,onClick:()=>Xe("alt"),disabled:M,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("arrow-up"),disabled:M,children:[t.jsx(k,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("arrow-left"),disabled:M,children:[t.jsx(k,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("arrow-down"),disabled:M,children:[t.jsx(k,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("arrow-right"),disabled:M,children:[t.jsx(k,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Qe,{type:"button",size:Fe,variant:"outline",className:Je,onPointerDown:dt,onClick:()=>Oe("enter"),disabled:M,children:[t.jsx(k,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:F("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[p?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:F("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(eg,{items:de,activeId:O,onSelect:ft,onClose:lt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:F("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Se,title:"New tab",children:t.jsx(k,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ue()},disabled:ot,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(k,{name:"restart",className:"h-4 w-4"})}),t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:Ve,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(k,{name:"attachment-2",className:"h-4 w-4"})}),ze?t.jsxs(Qe,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{m&&B(m,ze)},title:"Open preview pane",children:[t.jsx(k,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&w&&f&&p?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Rt}):null,!x&&w&&!p?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Rt}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Et.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:De?t.jsx(gl,{ref:z=>{we.current=z},sessionKey:jt,chunks:Me,onInput:it,onResize:gt,theme:Et,fontFamily:Ot,fontSize:l,enableTouchScroll:y,autoFocus:_,isVisible:_},jt):null}),!Ge&&Be&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:Be}),te&&x&&t.jsx(Qe,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:me,disabled:ot,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&w?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Rt})}):null]})},hg=ws(()=>({statusById:new Map})),Fx=()=>{Pa(),ka()},Lx=e=>{_e.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),re.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),Pa(),Ee.getState().clearAll(),zs.getState().resetForRuntimeSwitch(),Lt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),Ut.getState().resetForRuntimeSwitch(),Hd.getState().resetForRuntimeSwitch(),hg.setState({statusById:new Map}),Wd(),Yd(),Qu.getState().reset(),Au.getState().resetForRuntimeSwitch(),ga.getState().resetForRuntimeSwitch(e.runtimeKey),pp.getState().resetForRuntimeSwitch(),$t.getState().resetForRuntimeSwitch(e.runtimeKey),Iu.getState().resetForRuntimeSwitch(e.runtimeKey),_e.getState().restoreForRuntimeSwitch(e.runtimeKey),re.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=re.getState();to({sessionId:_e.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),ka()},pg=48,mg=96,Ht=(e,...s)=>{try{e?.(...s)}catch{}},Lr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Ox=(e,s)=>{const n=o.useRef(s);n.current=s;const r=s.enabled;o.useEffect(()=>{const i=e.current;if(!i||r===!1)return;const a=i.style.touchAction;i.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?mg:pg;let d=!1,u=!1,b=!1,h=null,x=!1,y=0,f=0,g=0,w=0;const v=()=>{d=!1,u=!1,b=!1,h=null},D=()=>{const P=n.current,E=h,R=x;u&&E&&(Ht(E==="left"?P.onLeftProgress:P.onRightProgress,R?1:0),Ht(P.onDragEnd,E,R)),v()},S=()=>{D(),u||v()},m=P=>{const E=n.current;if(E.enabled===!1){u&&h?D():v();return}if(P.touches.length!==1){u&&h?D():v();return}const R=P.touches[0],L=i.getBoundingClientRect(),Y=i.clientWidth,X=!!E.leftOpen,oe=!!E.rightOpen,$=H=>jm(H,i);if(X||oe){if($(P.target)){v();return}if(X&&oe){const H=R.clientX<=L.left+c;R.clientX>=L.right-c?(h="right",x=!0):H?(h="left",x=!0):(h=X?"left":"right",x=!0)}else X?(h="left",x=!0):(h="right",x=!0);w=Lr(h==="left"?E.leftWidth:E.rightWidth,Y),w<10&&(w=Y||window.innerWidth||320),w<10&&(w=320),d=!0}else{if($(P.target)){v();return}h=null,x=!1,w=0,d=!0}y=R.clientX,f=R.clientY,g=Date.now(),u=!1,b=!1},p=P=>{if(!d)return;if(P.touches.length!==1){S();return}const E=P.touches[0],R=E.clientX-y,L=E.clientY-f;if(!b){if(Math.abs(R)<Gi&&Math.abs(L)<Gi)return;if(Math.abs(L)>Math.abs(R)*cn){v();return}if(!h){const oe=n.current;h=R>0?"left":"right",w=Lr(h==="left"?oe.leftWidth:oe.rightWidth,i.clientWidth),w<10&&(w=window.innerWidth||320)}if(h==="left"){if(!x&&R<=0){v();return}if(x&&R>=0){v();return}}else{if(!x&&R>=0){v();return}if(x&&R<=0){v();return}}b=!0,u=!0,Ht(n.current.onDragStart,h)}if(!u)return;P.cancelable&&P.preventDefault();const Y=n.current,X=Ki(h,x,R,w);Ht(h==="left"?Y.onLeftProgress:Y.onRightProgress,X)},N=(P,E)=>{if(!d){v();return}const R=P-y,L=E-f;if(!h&&!x&&Math.abs(R)>=Vn&&Math.abs(L)<=Math.abs(R)*cn){const B=n.current;h=R>0?"left":"right",w=Lr(h==="left"?B.leftWidth:B.rightWidth,i.clientWidth),w<10&&(w=window.innerWidth||320)}if(!h){v();return}const Y=Math.max(1,Date.now()-g),X=n.current;if(!u){const B=Math.abs(R),O=Math.abs(L);B>=Vn&&O<=B*cn?h==="left"&&!x&&R>0?(Ht(X.onLeftProgress,1),Ht(X.onLeftOpen)):h==="right"&&!x&&R<0?(Ht(X.onRightProgress,1),Ht(X.onRightOpen)):Ht(h==="left"?X.onLeftProgress:X.onRightProgress,x?1:0):Ht(h==="left"?X.onLeftProgress:X.onRightProgress,x?1:0);const J=h;v(),Ht(X.onDragEnd,J);return}const oe=Ki(h,x,R,w),$=wm({side:h,isOpenAtStart:x,dx:R,dt:Y,progress:oe}),H=h;Ht(H==="left"?$?X.onLeftOpen:X.onLeftClose:$?X.onRightOpen:X.onRightClose),v(),Ht(X.onDragEnd,H,$)},T=P=>{const E=P.changedTouches[0];if(!E){v();return}const R=E.clientX-y,L=E.clientY-f;d&&(u||Math.abs(R)>=Vn&&Math.abs(L)<=Math.abs(R)*cn)&&P.cancelable&&P.preventDefault(),N(E.clientX,E.clientY)},A=()=>{S()};return i.addEventListener("touchstart",m,{passive:!0}),i.addEventListener("touchmove",p,{passive:!1}),i.addEventListener("touchend",T,{passive:!1}),i.addEventListener("touchcancel",A,{passive:!0}),()=>{try{u&&h&&D()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",m),i.removeEventListener("touchmove",p),i.removeEventListener("touchend",T),i.removeEventListener("touchcancel",A)}},[e,r])};function Bx({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(k,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function ea({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const Or=()=>Ls.filter(e=>qr.has(e.id)).map(e=>({...Ta(e)})),gg=()=>{if(typeof window>"u")return Qr;const e=window.localStorage.getItem("openInAppId");return e&&Vr(e)?e:Qr};let Br=!1,Ys=!1,Ns=!1,As=0,mn=null;const ta=()=>{mn&&(clearTimeout(mn),mn=null)},Es=ws()((e,s)=>({selectedAppId:gg(),availableApps:Or(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Br||typeof window>"u")return;Br=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Or(),hasLoadedApps:u});return}const b=new Set(d.map(f=>f.name)),h=new Map(d.map(f=>[f.name,f.iconDataUrl??void 0])),y=Ls.filter(f=>b.has(f.appName)||qr.has(f.id)).map(f=>({...Ta(f),iconDataUrl:h.get(f.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!ys()||!yn()||Ys||s().hasLoadedApps&&!d)return;const b=Ls.map(h=>h.appName);ta(),Ys=!0,Ns=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:y,isCacheStale:f}=await ci(b,d),g=x&&!y&&h.length===0&&As<3;if(e({isCacheStale:y?f:!1}),n(h,x?!g:!1),x){if(g){const v=[800,1600,3200][As]??3200;As+=1,Ns=!0,mn=setTimeout(()=>{r()},v);return}As=0,Ns=!1;return}if(As<3){const v=[1e3,3e3,7e3][As]??7e3;As+=1,Ns=!0,mn=setTimeout(()=>{r()},v)}}finally{Ys=!1,Ns||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,b=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Vr(u.openInAppId)?u.openInAppId:null;b&&(window.localStorage.setItem("openInAppId",b),e({selectedAppId:b}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(As=3,Ns=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",i),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Br||s().initialize(),!ys()||!yn()||Ys||s().hasLoadedApps&&!n)return;const i=Ls.map(a=>a.appName);ta(),n&&e({hasLoadedApps:!1}),Ys=!0,Ns=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await ci(i,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=Ls.filter(x=>d.has(x.appName)||qr.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:h.length>0?h:Or(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{Ys=!1,Ns||e({isScanning:!1})}},selectApp:async n=>{Vr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await go({openInAppId:n}))}})),xg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",bg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",_r=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?xg:e.id==="terminal"?bg:void 0}),sa=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,i]=o.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>i(!0)}):t.jsx("span",{className:F("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},yg=({directory:e,className:s})=>{const n=Es(f=>f.selectedAppId),r=Es(f=>f.availableApps),i=Es(f=>f.isCacheStale),a=Es(f=>f.isScanning),l=Es(f=>f.initialize),c=Es(f=>f.loadInstalledApps),d=Es(f=>f.selectApp);o.useEffect(()=>{l()},[l]);const u=ys()&&yn(),b=o.useMemo(()=>{const f=r.find(g=>g.id===n)??r.find(g=>g.id===Qr)??r[0]??Ls[0];return _r(f||Ls[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async f=>{await Du(e,f.id,f.appName)||await Ia(e,f.appName)},x=async f=>{await d(f.id),await h(f)},y=async()=>{(await gn(e)).ok&&le.success("Path copied to clipboard")};return t.jsxs("div",{className:F("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(b)},className:F("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${b.label}`,children:t.jsx(sa,{label:b.label,iconDataUrl:b.iconDataUrl,fallbackIconDataUrl:b.fallbackIconDataUrl})}),t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(k,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Vt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{y()},children:[t.jsx(k,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(tn,{}),r.map(f=>{const g=_r(f);return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{x(f)},children:[t.jsx(sa,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:f.label}),b.id===f.id?t.jsx(k,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},f.id)}),i?t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(k,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},vg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],wg=["dev","start","preview","serve"];async function Sg(e,s,n){if(!e)return null;const r=kg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=Ng(n);if(i){const a=await Ag(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${i}`,label:`Start (${i})`}}}if(await jg(e)){const i=await Cg(),a=typeof i=="number"&&Number.isFinite(i)&&i>0?i:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function jg(e){const s=`${e}/index.html`,n=await sr(s,e);return typeof n=="string"&&n.trim().length>0}async function Cg(){try{const e=await Xt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function kg(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(wg.some(i=>n.includes(i)))return s}return null}function Ng(e){for(const{pattern:s}of vg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Ag(e){const s=await sr(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),i=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(i.startsWith("bun@"))return"bun";if(i.startsWith("pnpm@"))return"pnpm";if(i.startsWith("yarn@"))return"yarn";if(i.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,i]of n){const a=await sr(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function sr(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await Xt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=xo()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Xt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Ig(e){try{const s=await sr(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Dg=(e,s,n)=>new Promise(r=>{let i=!1,a=null,l=null;const c=d=>{i||(i=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),i?a.close():l=setTimeout(()=>c(!1),n)}),Pg="\x1B",Tg=new RegExp(`${Pg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Eg=/https?:\/\/[^\s<>'"`]+/gi,Jt="__pichamber_auto_discover_preview__",Rg=15e3,Mg=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},Fg=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Lg=e=>{const n=e.replace(Tg,"").match(Eg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const i=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&i.push({raw:a,parsed:l})}catch{}if(i.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",b=c.pathname||"/",h=b.split("/").filter(Boolean).length,x=b==="/"||b==="",y=!!(c.search||c.hash);let f=0;return u&&(f+=50),x&&(f+=30),f-=Math.min(h*5,20),y&&(f-=10),f};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},na=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=Ca(),{terminal:l}=nr(),{isMobile:c}=Us(),d=o.useMemo(()=>ys(),[]),u=Zn(_=>_.instances),b=Zn(_=>_.load),h=re(_=>_.terminalShell),x=re(_=>_.terminalLoginShells.includes(_.terminalShell)),y=re(_=>_.setSettingsPage),f=re(_=>_.setSettingsDialogOpen),g=re(_=>_.setSettingsProjectsSelectedId),w=re(_=>_.openContextPreview),v=Ee(_=>_.ensureDirectory),D=Ee(_=>_.setTabLabel),S=Ee(_=>_.setTabIconKey),m=Ee(_=>_.setActiveTab),p=Ee(_=>_.setConnecting),N=Ee(_=>_.setTabSessionId),T=Ee(_=>_.setTabPreviewUrl),A=Ee(_=>_.projectActionRuns),P=Ee(_=>_.setProjectActionRun),E=Ee(_=>_.updateProjectActionRunStatus),R=Ee(_=>_.removeProjectActionRun),[L,Y]=o.useState([]),[X,oe]=o.useState(null),[$,H]=o.useState(!1),B=o.useRef({}),O=o.useRef({}),J=o.useRef({}),de=o.useRef({}),G=o.useRef(new Set),Ce=o.useRef(0),Me=e?.id??null,He=e?.path??"",ze=o.useMemo(()=>Me?{id:Me,path:He}:null,[Me,He]);o.useEffect(()=>{d&&b().catch(()=>{})},[d,b]);const Be=o.useCallback(async _=>{await aa(_)},[]),Pe=o.useCallback(async()=>{if(!ze)return;const _=Ce.current+1;Ce.current=_,H(!0);try{const be=await zr(ze);if(Ce.current!==_)return;const Ie=be.actions;Y(Ie),oe(C=>C===Jt||C&&Ie.some(K=>K.id===C)?C:null)}catch{if(Ce.current!==_)return}finally{Ce.current===_&&H(!1)}},[ze]),te=o.useMemo(()=>Va(s||ze?.path||""),[s,ze?.path]),xe=o.useMemo(()=>X?L.find(_=>_.id===X)??null:null,[L,X]),Ge=o.useMemo(()=>({id:Jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Ne=!c,ye=o.useMemo(()=>Ne?[Ge,...L]:L,[L,Ge,Ne]);o.useEffect(()=>{Pe()},[Pe]),o.useEffect(()=>{if(typeof window>"u")return;const _=be=>{const Ie=be.detail;Me&&(Ie?.projectId&&Ie.projectId!==Me||Pe())};return window.addEventListener(ro,_),()=>{window.removeEventListener(ro,_)}},[Pe,Me]),o.useEffect(()=>{X&&(X===Jt&&Ne||L.some(_=>_.id===X)||oe(null))},[L,Ne,X]),o.useEffect(()=>{const _=()=>{const be=Ee.getState(),Ie=be.sessions,C=be.projectActionRuns;for(const[K,ee]of Object.entries(C)){const me=Ie.get(ee.directory)?.tabs.find(Ze=>Ze.id===ee.tabId);if(!me||me.terminalSessionId!==ee.sessionId){R(K);continue}const Se=O.current[K]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};O.current[K]=Se;const Ve=ye.find(Ze=>Ze.id===ee.actionId),ft=be.getBuffer(ee.directory,ee.tabId).chunks;if(!Ve||ft.length===0)continue;const lt=ft.filter(Ze=>Se.lastSeenChunkId===null||Ze.id>Se.lastSeenChunkId);if(lt.length===0)continue;const it=lt.map(Ze=>Ze.data).join(""),gt=`${Se.tail}${it}`,Xe=!Se.openedUrl&&Ve.autoOpenUrl===!0?Lg(gt):null,Oe=lt[lt.length-1]?.id??Se.lastSeenChunkId;if(Se.lastSeenChunkId=Oe,Se.tail=gt.slice(-512),Xe)if(Se.openedUrl=!0,Se.openInPreview){const Ze=C[K];Ze&&(T(Ze.directory,Ze.tabId,Xe,{locked:!1,autoOpened:!1}),Ze.status==="waiting-for-preview"&&E(K,"running"),window.clearTimeout(de.current[K]),delete de.current[K],w(Ze.directory,Xe))}else Be(Xe),le.success("Opened URL from action output");O.current[K]=Se}for(const K of Object.keys(O.current))C[K]||(delete O.current[K],window.clearTimeout(de.current[K]),delete de.current[K])};return _(),Ee.subscribe((be,Ie)=>{(be.sessions!==Ie.sessions||be.buffers!==Ie.buffers)&&_()})},[ye,w,Be,A,R,T,E]);const Ae=o.useCallback(async(_,be={})=>{if(!te)throw new Error("No active directory");const Ie=xs(te,_.id);v(te);const C=Ee.getState(),K=C.getDirectoryState(te);let ee=B.current[Ie]||null;const ue=ee?!!K?.tabs.some(Ve=>Ve.id===ee):!1;(!ee||!ue)&&(ee=C.createTab(te),B.current[Ie]=ee),D(te,ee,`Action: ${_.name}`),S(te,ee,_.icon||"play"),m(te,ee),be.revealTerminal!==!1&&re.getState().openContextPanelTab(te,{mode:"terminal"});const Se=Ee.getState().getDirectoryState(te)?.tabs.find(Ve=>Ve.id===ee);return{key:Ie,tabId:ee,sessionId:Se?.terminalSessionId??null}},[v,te,m,S,D]),ot=o.useCallback(async _=>{if(!i&&c)return;if(!te){le.error("No active directory for action");return}const be=xs(te,_.id),Ie=A[be];if(!(Ie&&Ie.status==="running")&&!G.current.has(be)){G.current.add(be);try{const C=_.id===Jt?await(async()=>{const[Oe,Ze]=await Promise.all([zr({id:ze?.id??"",path:te}),Ig(te)]),vt=await Sg(te,Oe.actions,Ze);if(!vt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Jt,name:"Auto-discover",command:vt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:vt.previewUrlHint||""}})():_,K=C.autoOpenUrl===!0&&(C.openUrl||"").trim().length>0,ee=!K&&_.id!==Jt,{key:ue,tabId:me,sessionId:Se}=await Ae(C,{revealTerminal:ee});let Ve=Se;if(!Ve){p(te,me,!0);try{Ve=(await l.createSession({cwd:te,sessionId:me,shell:h,loginShell:x,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,N(te,me,Ve)}finally{p(te,me,!1)}}if(!Ve)throw new Error("Failed to create terminal session");J.current[ue]?.(),p(te,me,!0);const ft=l.connect(Ve,{onEvent:Oe=>{Oe.type==="snapshot"&&(Ee.getState().replaceBuffer(te,me,Oe.data??"",Oe.sequence??0),Ee.getState().setConnecting(te,me,!1)),Oe.type==="data"&&typeof Oe.data=="string"&&Oe.data.length>0&&Ee.getState().appendToBuffer(te,me,Oe.data,Oe.sequence,Oe.replayData),Oe.type==="exit"&&(Ee.getState().setTabLifecycle(te,me,"exited"),Ee.getState().setConnecting(te,me,!1),Ee.getState().removeProjectActionRun(ue),delete O.current[ue],J.current[ue]?.(),delete J.current[ue],window.clearTimeout(de.current[ue]),delete de.current[ue])},onError:(Oe,Ze)=>{Ee.getState().setConnecting(te,me,!1),Ze&&(Ee.getState().setTabLifecycle(te,me,"exited"),Ee.getState().setTabSessionId(te,me,null),Ee.getState().removeProjectActionRun(ue))}});J.current[ue]=ft.close;const lt=C.autoOpenUrl===!0&&d&&(C.desktopOpenSshForward||"").trim().length>0,it=C.autoOpenUrl?Fg(C.openUrl):null,gt=C.autoOpenUrl&&d?Bf(C.desktopOpenSshForward,u):null;P({key:ue,directory:te,actionId:C.id,tabId:me,sessionId:Ve,status:C.id===Jt&&!it?"waiting-for-preview":"running"}),window.clearTimeout(de.current[ue]),delete de.current[ue],C.id===Jt&&!it&&(de.current[ue]=window.setTimeout(()=>{const Oe=Ee.getState(),Ze=Oe.projectActionRuns[ue];Oe.updateProjectActionRunStatus(ue,"running"),Ze&&(Oe.setActiveTab(Ze.directory,Ze.tabId),re.getState().openContextPanelTab(Ze.directory,{mode:"terminal"})),delete de.current[ue]},Rg)),O.current[ue]={lastSeenChunkId:null,openedUrl:!!gt||!!it||K,tail:"",openInPreview:C.id===Jt};const Xe=Mg(C.command.trim().replace(/\r\n|\r/g,`
56
- `));await l.sendInput(Ve,`${Xe}\r`),gt?(T(te,me,null,{locked:!0}),Be(gt),le.success("Opened forwarded URL")):it?(T(te,me,it,{locked:!0,autoOpened:!0}),w(te,it),le.success("Opened action URL")):K?(T(te,me,null,{locked:!0}),le.error("Invalid custom URL format")):lt?(T(te,me,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):T(te,me,null,{locked:!1,autoOpened:!1})}catch(C){R(be),delete O.current[be],J.current[be]?.(),delete J.current[be],window.clearTimeout(de.current[be]),delete de.current[be],le.error(C instanceof Error?C.message:"Failed to run action")}finally{G.current.delete(be)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,Ae,i,c,d,te,x,h,Be,w,A,R,p,P,T,N,ze?.id,l]),We=o.useCallback(async _=>{const be=xs(te,_.id),Ie=A[be];if(!Ie)return;E(be,"stopping");const C=Dg(l,Ie.sessionId,1e3);try{await l.sendInput(Ie.sessionId,"")}catch{}const K=await C;if(Ee.getState().getDirectoryState(Ie.directory)?.tabs.find(me=>me.id===Ie.tabId)?.terminalSessionId===Ie.sessionId&&!K){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:Ie.sessionId})}catch{}else try{await l.close(Ie.sessionId)}catch{}N(Ie.directory,Ie.tabId,null)}R(be),delete O.current[be],J.current[be]?.(),delete J.current[be],window.clearTimeout(de.current[be]),delete de.current[be]},[te,A,R,N,l,E]),Q=o.useCallback(()=>{const _=xe??ye[0];if(!_)return;const be=xs(te,_.id),Ie=A[be];if(Ie?.status!=="stopping"){if(Ie){We(_);return}ot(_)}},[ye,te,ot,A,xe,We]),V=o.useCallback((_,be=!1)=>{if(oe(_.id),!be){ot(_);return}const Ie=xs(te,_.id),C=A[Ie];if(C?.status!=="stopping"){if(C){We(_);return}ot(_)}},[te,ot,A,We]),pe=o.useCallback(()=>{ze?.id&&(g(ze.id),y("projects"),f(!0))},[f,y,g,ze?.id]),q=xe??ye[0]??null,ve=q?A[xs(te,q.id)]:null,we=Ee(_=>ve?_.sessions.get(ve.directory)?.tabs.find(be=>be.id===ve.tabId)?.previewUrl??null:null);if(!i&&c||!ze||!te)return null;const Re=xe??ye[0]??null;if(!Re)return null;const qe=Re.icon||"play",at=Re.id===Jt?"scan-2":pn[qe]||"play",mt=xs(te,Re.id),Le=A[mt],ke=Le?.status==="stopping",Ye=Le?.status==="waiting-for-preview",pt=!!(Le&&we),kt=()=>{!Le||!we||w(Le.directory,we)},bt=Re.id===Jt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:$||ke,className:F("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:Q,"aria-label":Le?`Stop ${Re.name}`:`Run ${Re.name}`,children:ke||Ye?t.jsx(k,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Le?t.jsx(k,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(k,{name:at,className:"h-5 w-5"})})}),bt?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),pt?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:kt,children:t.jsx(k,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(k,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Vt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:pe,children:[t.jsx(k,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(tn,{}),ye.map(_=>{const be=_.icon||"play",Ie=_.id===Jt?"scan-2":pn[be]||"play",C=xs(te,_.id),K=A[C],ee=!!K,ue=K?.status==="stopping";return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{V(_,!0)},children:[t.jsx(k,{name:Ie,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),ue||K?.status==="waiting-for-preview"?t.jsx(k,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):ee?t.jsx(k,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]}):t.jsxs("div",{className:F("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Q,disabled:$||ke,className:F("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":Le?`Stop ${Re.name}`:`Run ${Re.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:ke||Ye?t.jsx(k,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?t.jsx(k,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(k,{name:at,className:"h-4 w-4"})})})}),bt?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),pt?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:kt,className:F(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(k,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",className:F(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(k,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Vt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:pe,children:[t.jsx(k,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(tn,{}),ye.map(_=>{const be=_.icon||"play",Ie=_.id===Jt?"scan-2":pn[be]||"play",C=xs(te,_.id),K=A[C],ee=!!K,ue=K?.status==="stopping";return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{V(_,!0)},children:[t.jsx(k,{name:Ie,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),ue||K?.status==="waiting-for-preview"?t.jsx(k,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):ee?t.jsx(k,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]})},fr="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Og="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Bg=o.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:i,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:F(a??fr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(k,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:n})})]}):null}),_g=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Wt,{children:[t.jsx(Yt,{asChild:!0,children:t.jsx("button",{type:"button",className:F(fr,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(k,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Vt,{align:"end",className:"w-64",children:[t.jsx(iu,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(tn,{}),r.map(d=>{const u=d.user,b=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Ct,{className:"gap-2",disabled:l,onSelect:()=>{b||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(k,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),b?t.jsx(k,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(k,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),zg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:b,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(Wt,{open:a,onOpenChange:y=>{l(y),y&&c()},children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Yt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:F(fr,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(k,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(rt,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Vt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[i?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:b?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(ou,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Ug=(e,s)=>e===s?!0:!e||!s?!1:e.totalTokens===s.totalTokens&&e.percentage===s.percentage&&e.contextLimit===s.contextLimit&&(e.outputLimit??0)===(s.outputLimit??0)&&(e.normalizedOutput??0)===(s.normalizedOutput??0)&&e.thresholdLimit===s.thresholdLimit&&(e.lastMessageId??"")===(s.lastMessageId??""),$g=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Rs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},ra=e=>!e?.isOpen||!Array.isArray(e.tabs)||e.tabs.length===0?null:(e.tabs.find(n=>n.id===e.activeTabId)??e.tabs[e.tabs.length-1])?.mode??null,_x=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{as("ui.header.render");const l=re(I=>I.setSessionSwitcherOpen),c=re(I=>I.toggleSidebar),d=re(I=>I.isSidebarOpen),u=re(I=>I.openContextOverview),b=re(I=>I.closeContextPanel),h=re(I=>I.activeMainTab),x=re(I=>I.setActiveMainTab),y=re(I=>I.shortcutOverrides);re(I=>I.timeFormatPreference);const f=Lt(I=>I.getCurrentModel);nr();const g=_e(I=>I.getContextUsage),w=_e(I=>!!I.newSessionDraft?.open),v=_e(I=>I.currentSessionId),D=tu(),S=Sa(v??""),m=Vd(v),p=o.useMemo(()=>{if(!m)return null;const I=m;return{title:m.title??null,directory:I.directory??null,created:m.time?.created??null,slug:I.slug??null,shareUrl:m.share?.url??null,parentId:m.parentID??null}},[m]),N=Ut(eo(I=>{if(!I.activeProjectId)return null;const fe=I.projects.find(Te=>Te.id===I.activeProjectId);return fe?{id:fe.id,path:fe.path,label:fe.label}:null})),T=o.useMemo(()=>{if(!N)return null;const I=N.label?.trim();if(I)return I;const fe=N.path.split(/[\\/]/).filter(Boolean);return fe[fe.length-1]??null},[N]),{isMobile:A}=Us(),{enabled:P}=ha(),E=!!(P&&a&&i!==void 0),R=o.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"notes",label:"Notes",icon:"sticky-note"}],[]),[L,Y]=o.useState(!1),X=null,oe=o.useRef(null),[$,H]=o.useState(()=>typeof window>"u"?!1:ys()),B=o.useMemo(()=>Da(),[]),O=qd(),[J,de]=o.useState(!1),G=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:Ce,side:Me}=Na(),He=o.useMemo(()=>{if(typeof window>"u")return null;const I=window.__PICHAMBER_MACOS_MAJOR__;if(typeof I=="number"&&Number.isFinite(I)&&I>0)return I;if(typeof navigator>"u")return null;const fe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!fe)return null;const Te=Number.parseInt(fe[1],10),xt=Number.parseInt(fe[2],10);return Number.isNaN(Te)?null:Te===10?xt:Te},[]);Ke.useEffect(()=>{typeof window>"u"||H(ys())},[]);const ze=f(),Be=ze&&typeof ze.limit=="object"&&ze.limit!==null?ze.limit:null,Pe=Be&&typeof Be.context=="number"?Be.context:0,te=Be&&typeof Be.output=="number"?Be.output:0,xe=g(Pe,te),[Ge,Ne]=o.useState(null),ye=!v||D;Ke.useEffect(()=>{if(!v){Ne(I=>I===null?I:null);return}if(xe&&xe.totalTokens>0){Ne(I=>Ug(I,xe)?I:xe);return}Ne(I=>I===null?I:null)},[xe,v,ye]);const Ae=re(I=>I.isSessionSwitcherOpen),ot=null,We=null,Q=[],[V,pe]=o.useState(!1),[q,ve]=o.useState(!1),[we,Re]=o.useState("Local"),[qe,at]=o.useState(!0),[mt,Le]=o.useState(!1),[ke,Ye]=o.useState(null),[pt,kt]=o.useState(!1),[bt,_]=o.useState(null),be=o.useMemo(()=>$g(we),[we]),Ie=h==="chat"&&!!Ge&&Ge.totalTokens>0,C=Ge&&Ge.contextLimit>0?Math.min(999,Ge.totalTokens/Ge.contextLimit*100):0,K=o.useCallback(async()=>{if(!(typeof window>"u"||!$))try{if(yn()){Re("Local"),at(!0);return}at(!1);const I=await Pu(),fe=Qd(),Te=Jd([Xd(fe),...I.hosts]);if(Te.id===Zd){Re("Local"),at(!0);return}Re(Tu(Te.label.trim()||"Instance"))}catch{Re("Local"),at(!0)}},[$]);Ke.useEffect(()=>(K(),Eu(()=>{K()})),[K]);const ee=o.useCallback(async()=>{if(qe){Ye(null),_(null);return}kt(!0),_(null);try{const I=new URLSearchParams({appType:"web",instanceMode:"remote",reportUsage:"false"}),fe=await Xt(`/api/pi/update-check?${I.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!fe.ok)throw new Error(`Server responded with ${fe.status}`);const Te=await fe.json();Ye({available:Te.available??!1,version:Te.version,currentVersion:Te.currentVersion??"unknown",body:Te.body,nextSuggestedCheckInSec:typeof Te.nextSuggestedCheckInSec=="number"?Te.nextSuggestedCheckInSec:void 0,packageManager:Te.packageManager,updateCommand:Te.updateCommand})}catch(I){Ye(null),_(I instanceof Error?I.message:"Failed to check remote instance updates")}finally{kt(!1)}},[qe]);o.useEffect(()=>{Ye(null),_(null),Le(!1)},[qe,we]),o.useEffect(()=>{if(!$||qe)return;const I=3e3,fe=3600*1e3;let Te=!1,xt=null;const Cs=ds=>{xt=window.setTimeout(()=>{if(Te||typeof document<"u"&&document.visibilityState!=="visible"){Cs(fe);return}ee().finally(()=>{Te||Cs(fe)})},ds)};return Cs(I),()=>{Te=!0,xt!==null&&window.clearTimeout(xt)}},[ee,qe,we,$]);const ue=o.useCallback(()=>{if(ke?.available){Le(!0);return}ee()},[ee,ke?.available]),me=v?p??null:null,Se=o.useRef(null),[Ve,ft]=o.useState(0);o.useEffect(()=>{if(!v){Se.current&&(Se.current=null,ft(xt=>xt+1));return}if(me){Se.current={sessionId:v,session:me,expiresAt:Date.now()+2e3};return}const I=Se.current;if(!I||I.sessionId!==v)return;const fe=I.expiresAt-Date.now();if(fe<=0){Se.current=null,ft(xt=>xt+1);return}const Te=window.setTimeout(()=>{Se.current?.sessionId===v&&(Se.current=null),ft(xt=>xt+1)},fe);return()=>{window.clearTimeout(Te)}},[v,me]);const lt=(()=>{if(me)return me;if(!v)return null;const I=Se.current;return I&&I.sessionId===v&&I.expiresAt>Date.now()?I.session:null})(),it=o.useMemo(()=>{const I=typeof lt?.directory=="string"?lt.directory:"";return Rs(I||"")},[lt?.directory]),gt=_e(I=>I.newSessionDraft?.open?Rs(I.newSessionDraft.directoryOverride??""):""),Xe=o.useMemo(()=>it||gt,[gt,it]),Oe=re(o.useCallback(I=>{const fe=Rs(Xe||"");return fe?ra(I.contextPanelByDirectory[fe]):null},[Xe])),vt=wa(Xe||null),Ot=!!(T||vt),Et=o.useMemo(()=>{if(!v)return T??"PiChamber";const I=lt?.title?.trim();return I&&I.length>0?I:"Untitled Session"},[T,lt?.title,v]),jt=ja(),M=mo(),De=_e(I=>I.updateSessionTitle),Fe=_e(I=>I.archiveSessions),Je=_e(I=>I.deleteSessions),[dt,Rt]=o.useState(!1),[z,ie]=o.useState(!1),ge=o.useRef(!1),[et,je]=o.useState(""),[$e,ct]=o.useState(null),At=o.useRef(null);o.useEffect(()=>{ge.current=!1,ie(!1),Rt(!1),je(""),ct(null)},[v]);const _t=o.useCallback(()=>{v&&(je(lt?.title?.trim()||Et),Rt(!0))},[lt?.title,v,Et]),Mt=o.useCallback(async()=>{if(!v)return;const I=et.trim();I&&I!==lt?.title?.trim()&&await De(v,I),Rt(!1)},[lt?.title,v,et,De]);o.useEffect(()=>{if(!dt)return;const I=fe=>{const Te=fe.target;(!Te||!At.current?.contains(Te))&&Mt()};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[dt,Mt]);const Zt=o.useCallback(()=>{v&&gn(v).then(I=>{le[I.ok?"success":"error"](I.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[v]),qt=o.useCallback(async()=>{if(!v||!Xe){le.error("Nothing to export");return}try{await M.syncSession(v)}catch{le.error("Failed to load the complete session history");return}const I=Kr(jt.getState()).list;if(I.length===0){le.error("Nothing to export");return}const fe=ul(I,lt?.title??null),Te=pl(lt?.title??null);await hl(fe,Te)||fl(fe,Te),le.success("Session exported")},[lt?.title,v,jt,Xe,M]);S?.type==="busy"||S?.type;const Nt=o.useCallback(async()=>{if(!v||!$e)return;const I=eu(),fe=[v];for(let ds=0;ds<fe.length;ds+=1){const rn=fe[ds];for(const ms of I)ms.parentID===rn&&!fe.includes(ms.id)&&fe.push(ms.id)}const Te=$e;if(ct(null),(Te==="archive"?await Fe(fe):await Je(fe)).failedIds.length>0){le.error(Te==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Te==="archive"?"Session archived":"Session deleted")},[Fe,v,Je,$e]),Bt=re(I=>I.isArchivePageOpen),U=o.useMemo(()=>Bt?{title:"Archive",subtitle:null}:null,[Bt]),Z=o.useMemo(()=>Rs(Xe||N?.path||""),[N?.path,Xe]),ne=o.useMemo(()=>N?{id:N.id,path:N.path}:null,[N]),ce=o.useRef(null);o.useEffect(()=>{!ne||!Z||(ce.current={projectRef:ne,directory:Z})},[Z,ne]);const he=o.useMemo(()=>ne&&Z?{projectRef:ne,directory:Z}:ce.current,[Z,ne]),ht=o.useCallback(async I=>{},[]),wt=o.useCallback(()=>{if(typeof document>"u")return;const I=document.activeElement;if(!I)return;const fe=I.tagName;(fe==="INPUT"||fe==="TEXTAREA"||fe==="SELECT"||I.isContentEditable)&&I.blur()},[]),Dt=o.useCallback(()=>{if(A){wt(),l(!Ae);return}c()},[wt,A,Ae,l,c]),Kt=o.useCallback(()=>{hn("desktop_open_draft_mini_chat_window",{directory:Rs(Xe||N?.path||""),projectId:N?.id??null,apiBaseUrl:Yr(),clientToken:Wr()}).catch(I=>{console.warn("[header] failed to open draft mini chat window",I)})},[N?.id,N?.path,Xe]),rs=o.useCallback(()=>{if(w){Kt();return}v&&hn("desktop_open_session_mini_chat_window",{sessionId:v,directory:Rs(Xe||N?.path||""),apiBaseUrl:Yr(),clientToken:Wr()}).catch(I=>{console.warn("[header] failed to open session mini chat window",I)})},[N?.path,v,Kt,w,Xe]),Pt=o.useCallback(()=>{const I=Rs(Xe||"");if(!I)return;const fe=re.getState().contextPanelByDirectory[I];if(ra(fe)==="context"){b(I);return}u(I)},[b,u,Xe]),ls=Oe==="context",cs=fr,os=Og,Ds=o.useMemo(()=>n?"sessions":E?r&&i?i:null:r?"git":h,[h,E,n,r,i]),Ss=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&Ae&&l(!1)},[Ae,n,e,s,r,l]),nn=o.useCallback(()=>{e?.()},[e]),W=o.useCallback(()=>{s?.()},[s]),Ue=o.useMemo(()=>$&&G&&!J?"5.5rem":O?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!$||Ce?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[$,J,G,O,Ce]);Ke.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Ue)},[Ue]);const ut=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",St=d?"0px":$&&Ce?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":"2.5rem";Ke.useEffect(()=>{if(!$||!G){de(!1);return}let I=!1;const fe=async()=>{try{const xt=await hn("desktop_is_window_fullscreen");I||de(xt===!0)}catch{I||de(!1)}},Te=()=>{fe()};return fe(),window.addEventListener("pichamber:window-resized",Te),()=>{I=!0,window.removeEventListener("pichamber:window-resized",Te)}},[$,G]);const Tt=o.useMemo(()=>!$||!G||He===null?"":He>=26?"h-12":He<=15?"h-14":"",[$,G,He]),Qt=o.useMemo(()=>{if(!($&&!Ce))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[$,Ce]),es=o.useCallback(()=>{if(typeof document>"u")return;const I=oe.current?.getBoundingClientRect().height;I&&document.documentElement.style.setProperty("--oc-header-height",`${I}px`)},[]);Ke.useEffect(()=>{if(typeof window>"u")return;es();const I=oe.current;if(!I||typeof ResizeObserver>"u")return()=>{};let fe=0;const Te=()=>{fe||(fe=requestAnimationFrame(()=>{fe=0,es()}))},xt=new ResizeObserver(Te);return xt.observe(I),window.addEventListener("resize",Te),window.addEventListener("orientationchange",Te),()=>{fe&&cancelAnimationFrame(fe),xt.disconnect(),window.removeEventListener("resize",Te),window.removeEventListener("orientationchange",Te)}},[es]),Ke.useEffect(()=>{es()},[es,A,Tt]);const ts=o.useCallback(async I=>{const fe=I.target;fe.closest(".app-region-no-drag")||fe.closest("button, a, input, select, textarea")||I.button===0&&$&&await Ru()},[$]),js=o.useMemo(()=>A?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[A]),hr=o.useCallback(I=>po(fn(I,y)),[y]);Ke.useEffect(()=>{!A&&h!=="chat"&&h!=="terminal"&&h!=="diagram"&&x("chat")},[h,A,x]);const ps=o.useMemo(()=>{const I=[];return $&&I.push({value:"instance",label:"Instance",icon:t.jsx(k,{name:"server",className:"h-3.5 w-3.5"})}),I},[$]);Ke.useEffect(()=>{const I=fe=>{if(su(fe)&&!fe.shiftKey&&!fe.altKey){const Te=parseInt(fe.key,10);Te>=1&&Te<=js.length&&(fe.preventDefault(),A&&(wt(),Ss()),x(js[Te-1].id))}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[wt,Ss,A,x,js]),Ke.useEffect(()=>{const I=fe=>{const Te=fn("toggle_services_menu",y);if(ii(fe,Te)){fe.preventDefault(),q?ve(!1):(ve(!0),K());return}const xt=fn("cycle_services_tab",y);if(ii(fe,xt)){if(fe.preventDefault(),ps.length===0)return;ve(!0),K();return}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[y,q,ps,K]);const Cn=I=>{const fe=h===I.id,Te=I.icon==="diff",xt=Te?null:I.icon,Cs=I.id==="chat",ds=ms=>Te?t.jsx(ea,{size:ms}):xt?t.jsx(k,{name:xt,className:`h-${ms/4} w-${ms/4}`}):null,rn=t.jsxs("button",{type:"button",onClick:()=>x(I.id),className:F("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",fe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",Cs&&!A&&"min-w-[100px] justify-center"),"aria-label":I.label,"aria-selected":fe,role:"tab",children:[A?ds(20):t.jsxs(t.Fragment,{children:[ds(16),t.jsx("span",{className:"header-tab-label",children:I.label})]}),I.badge!==void 0&&I.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:I.badge})]});return t.jsx(o.Fragment,{children:rn},I.id)},pr=t.jsxs(t.Fragment,{children:[t.jsx(yg,{directory:Z,className:"mr-1"}),$?t.jsx(zg,{isDesktopApp:$,currentInstanceLabel:we,compactCurrentInstanceLabel:be,currentInstanceIsLocal:qe,isDesktopServicesOpen:q,setIsDesktopServicesOpen:ve,refreshCurrentInstanceLabel:K,shortcutLabel:hr,remoteUpdateInfo:ke,remoteUpdateChecking:pt,remoteUpdateError:bt,onOpenRemoteUpdate:ue}):null,t.jsx(_g,{isMobile:A,githubAuthStatus:X,githubAccounts:Q,githubAvatarUrl:ot,githubLogin:We,isSwitchingGitHubAccount:V,handleGitHubAccountSwitch:ht})]}),kn=B&&(w||!!v),Nn=()=>t.jsxs("div",{onMouseDown:ts,className:F("app-region-drag relative flex h-12 select-none items-center pr-3",Tt),style:Qt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:ut}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:St}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[U?t.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:U.title}),U.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:U.subtitle}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(nu,{align:"start",children:t.jsx("button",{type:"button",className:cs,"aria-label":"Open session switcher",children:t.jsx(k,{name:"history",className:"h-[18px] w-[18px]"})})}),t.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[dt?t.jsxs("form",{ref:At,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:I=>{I.preventDefault(),Mt()},children:[t.jsx("input",{value:et,onChange:I=>je(I.target.value),autoFocus:!0,onKeyDown:I=>{I.stopPropagation(),I.key==="Escape"&&Rt(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>Rt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:w?"New session":Et}),Ot?t.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[T?t.jsx("span",{className:"truncate",children:T}):null,vt?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(k,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:vt})]}):null]}):null]}),t.jsx("div",{className:F("flex h-[18px] shrink-0 items-center justify-center",Ot?"self-start":"self-center"),children:v&&!w&&!dt?t.jsxs(Wt,{open:z,onOpenChange:ie,onOpenChangeComplete:I=>{!I&&ge.current&&(ge.current=!1,_t())},children:[t.jsx(Yt,{asChild:!0,children:t.jsx(Qe,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(k,{name:"more",className:"size-4"})})}),t.jsxs(Vt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Ct,{onClick:()=>{ge.current=!0},children:[t.jsx(k,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Ct,{onClick:Zt,children:[t.jsx(k,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(tn,{}),t.jsxs(Ct,{onClick:()=>{qt()},children:[t.jsx(k,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(tn,{}),t.jsxs(Ct,{onClick:()=>ct("archive"),children:[t.jsx(k,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Ct,{className:"text-destructive focus:text-destructive",onClick:()=>ct("delete"),children:[t.jsx(k,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),js.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:js.map(I=>Cn(I))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[he?t.jsx(na,{projectRef:he.projectRef,directory:he.directory,className:"mr-1"}):null,Ie&&Ge?t.jsx(ru,{totalTokens:Ge.totalTokens,percentage:C,colorPercentage:Ge.percentage,contextLimit:Ge.contextLimit,outputLimit:Ge.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Pt,pressed:ls,className:kn?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,t.jsx(Bg,{visible:kn,title:w?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:w?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:rs,className:F(cs,"mr-1"),Icon:"picture-in-picture-2"}),pr,t.jsx(Aa,{visible:Ce&&Me==="right",position:"right"})]})]})]}),mr=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:ut}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:St}})]}),!P&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:nn,className:F(os,Ds==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(k,{name:"layout-left",className:"h-5 w-5"})}):Ae?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(k,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Dt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(k,{name:"play-list-add",className:"h-5 w-5"})}),!e&&Ae&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Ae||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!E&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:js.map(I=>{const fe=h===I.id,Te=I.icon==="diff",xt=Te?null:I.icon;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(wt(),Ss()),x(I.id)},"aria-label":I.label,"aria-selected":fe,role:"tab",className:F(os,"relative rounded-lg",Ds===I.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Te?t.jsx(ea,{className:"h-5 w-5"}):xt?t.jsx(k,{name:xt,className:"h-5 w-5"}):null,I.badge!==void 0&&I.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:I.badge}),I.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(rt,{children:t.jsx("p",{children:I.label})})]},I.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[E&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:R.map(I=>{const fe=r&&i===I.id;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(wt(),Ss()),Y(!1),a?.(I.id)},"aria-label":I.label,"aria-selected":fe,role:"tab",className:F(os,"relative rounded-lg",fe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(k,{name:I.icon,className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:I.label})})]},I.id)})}),t.jsx(Rh,{open:L,onOpenChange:Y,currentSessionId:v,effectiveDirectory:Xe||null,isNewSessionDraftOpen:w})]}),he&&t.jsx(na,{projectRef:he.projectRef,directory:he.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!E?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:W,className:F(os,"relative",Ds==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(k,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),An=F("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:oe,className:An,style:{"--padding-scale":"1"},children:A?mr():Nn()}),t.jsx(fs,{open:$e!==null,onOpenChange:I=>{I||ct(null)},children:t.jsxs(hs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Is,{children:[t.jsx(vs,{children:$e==="delete"?"Delete session?":"Archive session?"}),t.jsx($s,{children:$e==="delete"?`\\"${Et}\\" will be permanently deleted.`:`\\"${Et}\\" will be archived.`})]}),t.jsxs(Gs,{children:[t.jsx(Qe,{variant:"outline",size:"sm",onClick:()=>ct(null),children:"Cancel"}),t.jsx(Qe,{variant:"destructive",size:"sm",onClick:()=>{Nt()},children:$e==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Ka,{open:mt,onOpenChange:Le,info:ke,downloading:!1,downloaded:!1,progress:null,error:bt,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},oa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",zx=()=>{const e=re(f=>f.isSidebarOpen),s=re(f=>f.toggleSidebar),n=re(f=>f.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=po(fn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=Na(),d=!e,u=l&&c==="left",b=l,h=d||u||b,x=u||b,y=o.useCallback(()=>{hn("desktop_show_app_menu").catch(f=>{console.warn("[titlebar] failed to open app menu",f)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const f=m=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(m)}px`)},g=m=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(m)}px`)};if(!x)return;const w=i.current,v=r.current;if(!w||!v){f(0),g(0);return}const D=()=>{const m=Math.max(w.getBoundingClientRect().width,w.scrollWidth);f(m),g(v.getBoundingClientRect().width)};if(D(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(D);return S.observe(w),S.observe(v),()=>{S.disconnect()}},[x]),h?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 top-0 z-40 flex select-none items-center pr-2",style:{height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[u?t.jsx(Aa,{visible:!0,position:"left"}):null,b?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:y,"aria-label":"Open PiChamber menu",className:F(oa,"shrink-0"),children:t.jsx(k,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,d?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:F(oa,"shrink-0"),children:t.jsx(k,{name:"layout-left",className:"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},$n=200,Gn="cubic-bezier(0.22, 1, 0.36, 1)",Ux=e=>{const s=o.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=o.useState(e);return o.useLayoutEffect(()=>{if(s){r(e);return}if(e){r(!1);let i=0;const a=window.requestAnimationFrame(()=>{i=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(a),window.cancelAnimationFrame(i)}}r(!1)},[e,s]),{slidIn:n,prefersReducedMotion:s,transition:s?"none":`transform ${$n}ms ${Gn}, width ${$n}ms ${Gn}, min-width ${$n}ms ${Gn}, max-width ${$n}ms ${Gn}`}};export{qs as $,Sx as A,wx as B,vx as C,Gi as D,Es as E,Ax as F,fx as G,_x as H,Pf as I,jo as J,cx as K,Df as L,Rh as M,Co as N,dx as O,Rx as P,Zf as Q,Zn as R,Dx as S,Mx as T,Ka as U,Tf as V,Sn as W,jf as X,Cf as Y,Ha as Z,jn as _,cn as a,Nf as a0,ox as a1,mx as a2,kf as a3,Af as a4,px as a5,bx as a6,xx as a7,Ef as a8,Ms as a9,hx as aa,gx as ab,yx as ac,rx as ad,ix as ae,ax as af,lx as ag,Vf as ah,ux as ai,ih as aj,ah as ak,If as al,nx as am,Ix as an,jx as ao,vm as b,Px as c,Vn as d,hh as e,Lx as f,Tx as g,kx as h,jm as i,Nx as j,Cx as k,Ux as l,Ox as m,zx as n,sx as o,eh as p,th as q,Fx as r,Ex as s,sh as t,Wn as u,yi as v,nh as w,eg as x,Bx as y,rh as z};