@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
@@ -0,0 +1,56 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BWmmf5yJ.js","assets/SessionSwitcherDropdown-cFWgy1td.js","assets/index-DEYblXCW.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-DLKBsLKY.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-9aJdtQbh.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-HC9JT4I3.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-BuD14qFL.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-3Hj9i02t.js","assets/isDiffPlainText-LoMmNzmX.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
+ import{_ as _s}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ye,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{bi as Vi,bj as Os,bk as yc,ao as vc,o as qi,D as is,w as as,y as hs,I as k,ay as Cs,bl as Oo,f as O,B as qe,av as an,T as et,q as tt,s as st,bm as Qi,bn as wc,bo as Sc,bp as jc,bq as Cc,h as Oe,br as kc,bs as Bo,bt as Nc,bu as Ac,bv as _o,bw as Ic,bx as Dc,by as Pc,bz as Ec,bA as Ar,bB as Tc,t as ce,as as Yt,at as Vt,au as qt,Y as Gs,bC as Rc,bD as Mc,bE as Fc,bF as Lc,bG as zo,a5 as Mt,bH as Oc,bI as Bc,bJ as _c,bK as zc,bL as $c,bM as Uc,bN as Ir,bO as Ji,bP as Xi,bQ as Gc,bR as Hc,bS as Kc,bT as Wc,bU as Yc,bV as Vc,b1 as Dr,r as zs,bW as As,bX as qc,b3 as Is,b8 as Qc,b9 as Jc,ba as Xc,bb as Zc,bc as ir,bd as qs,bY as $o,az as wt,b as Ot,aV as Ps,bZ as Zi,x as ys,z as Es,A as Ts,b_ as ed,b$ as Qs,c0 as ar,c1 as Uo,c2 as Go,c3 as tn,aC as td,aX as ea,aH as Ho,aF as sd,aE as nd,a$ as ta,g as eo,c4 as rd,c5 as sa,c6 as od,c7 as na,e as _n,c8 as id,C as Wn,K as ra,c9 as ad,ca as zt,aQ as oa,c as Pr,cb as ld,cc as cd,cd as Yn,ce as Tn,cf as ia,_ as ln,$ as cn,Z as dd,cg as ud,ch as Ko,b2 as aa,ci as fd,cj as la,b6 as to,b7 as sn,ck as Wo,cl as Vn,aw as hd,cm as ca,H as pd,cn as so,co as md,cp as gd,j as da,l as xd,cq as bd,cr as yd,k as vd,cs as Er,n as wd,S as Sd,aT as ua,ct as jd,cu as Cd,m as kd,d as Nd,cv as Ad,a as Id,ax as Dd,b5 as Pd,cw as Ed,b4 as Td,cx as Rd,cy as Md,cz as Fd,cA as Ld,af as Od,cB as Yo,cC as Bd,aR as _d,cD as zd,cE as $d,cF as yn,cG as Vo,cH as Ud,cI as qo,cJ as Qo,cK as Gd,aJ as fa,a3 as Hd,E as Kd,cL as ha,u as Wd,cM as Yd,cN as Vd,aA as Hs,p as qd,cO as Qd,cP as pa,cQ as Jd,cR as Xd,cS as Zd,cT as eu,cU as tu,cV as su,cW as Jo,cX as nu,cY as ma,cZ as ru,c_ as ou}from"./SessionSwitcherDropdown-cFWgy1td.js";import{O as Xo,P as iu,Q as Zo,R as au,i as lu,S as cu,N as du,r as Jt,T as dn,b as uu,M as fs,u as fe,U as fu,V as cs,W as no,q as ro,m as Ds,X as gt,Y as oo,Z as io,_ as hu,$ as pu,D as mu,a0 as gu,a1 as xu,a2 as bu,a3 as yu,a4 as ss,a5 as Tr,a as qn,a6 as vu,a7 as wu,a8 as Su,a9 as ju,aa as ga,L as xa,E as nn,H as Rr,e as Mr,d as vn,ab as Cu,ac as ku,ad as Js,ae as lr,af as ba,C as Nu,o as Au,ag as Fr,ah as ks,ai as ei,aj as Lr,ak as ya,al as Or,am as Iu,an as Du,ao as Pu,w as Eu,ap as Tu}from"./index-DEYblXCW.js";import{C as va,a as wa,M as Br,b as _r,c as zr,d as Sa,S as ja,D as Ru,e as Mu,f as Fu,g as Lu,h as Ou,i as Bu,j as _u,k as zu,l as $u}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as Ca,p as ao,u as $r,a as Uu}from"./vendor-zustand-CnsBKjP5.js";import{u as Gu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as Qn,d as un,P as lo,D as Jn,e as Xn,f as ka,b as Hu,a as Ku,T as Wu,M as Yu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as co,v as Na,u as Zn,a as Vu,h as qu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as er}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as Qu}from"./permissionStore-BRcQ9Jgt.js";const Ju=3;let zn=0;const Aa=[],Xu=()=>zn<Ju?(zn+=1,Promise.resolve()):new Promise(e=>{Aa.push(e)}),Zu=()=>{const e=Aa.shift();if(e){e();return}zn=Math.max(0,zn-1)},ef=async e=>{await Xu();try{return await e()}finally{Zu()}},tf="chat";function Ia(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Os.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Os.SETTINGS,n),s}return e.tab!==tf&&s.set(Os.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Os.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=Ia(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(Os.SESSION)&&s.set(Os.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Ur(e,s={}){if(!(typeof window>"u")&&!Vi()&&!(!s.force&&nf(e)))try{const n=Ia(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"],Da={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ti=null;const Pa=()=>(ti??=Promise.all([_s(()=>import("./index-BWmmf5yJ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),_s(()=>import("./workerFactory-tw7cIdmV.js"),[]),_s(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,8,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),ti),fn={},si=new Set,Gr=new Set;let Rn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of Gr)e()},Ea=(e,s)=>{s.setRenderOptions({theme:Rn,lineDiffType:Da[e].lineDiffType})},Hr=e=>{typeof window>"u"||si.has(e)||(si.add(e),Pa().then(s=>{if(fn[e])return;const n=Da[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(),fn[e]=r,Ea(e,r),of()}))},af=e=>(Gr.add(e),()=>Gr.delete(e)),lf=e=>{if(!(Rn.light===e.light&&Rn.dark===e.dark)){Rn=e;for(const s of Object.keys(fn)){const n=fn[s];n&&Ea(s,n)}}},Xg=({children:e})=>{const s=yc(),n=Xo(!1),r=Xo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ye.useEffect(()=>{let d=!1;return Pa().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ye.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Hr("unified"),Hr("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})},Zg=(e="unified")=>{const s=Ye.useSyncExternalStore(af,()=>fn[e],()=>{});return Ye.useEffect(()=>{Hr(e)},[e]),s};function cf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=vc();return e}catch{return"unknown"}}function df(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function uf(){const e=uu();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function ff(e){const s=new URLSearchParams;return s.set("deviceClass",cf()),s.set("arch",df()),s.set("platform",uf()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",dn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function cr(e,s){try{const n=ff(e);s&&n.set("currentVersion",s);const r=await Jt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function hf(){return lu()?"mobile":cu()?"desktop":du()?"web":null}const ni={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=ps()((e,s)=>({...ni,checkForUpdates:async()=>{const n=hf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.3.0",[l,c]=await Promise.allSettled([Zo(),cr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await cr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await cr("mobile","0.3.0"),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 Zo();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await au(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await iu())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ni)}})),ri="https://github.com/RyderAsKing/PiChamber/releases";function pf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function mf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function oi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function gf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function xf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ii=2e3,bf=600*1e3;async function yf(){try{const e=await Jt("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function vf(){try{return(await Jt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function wf(e,s=Math.ceil(bf/ii),n=ii){for(let r=0;r<s;r++){try{const i=await Jt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await vf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ta=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[b,f]=Ye.useState(!1),[y,p]=Ye.useState("idle"),[h,m]=Ye.useState(null),S=n?.version?n.releaseUrl||`${ri}/tag/v${n.version}`:ri,C=n?.downloadUrl||S,N=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",g=u==="mobile",x=n?.updateCommand||"pichamber update";Ye.useEffect(()=>{e||(p("idle"),m(null))},[e]);const A=async()=>{(await an(x)).ok&&(f(!0),setTimeout(()=>f(!1),2e3))},P=Ye.useCallback(async K=>{await qi(K)},[]),D=Ye.useCallback(async()=>{p("updating"),m(null);const K=await yf();if(!K.success){p("error"),m(K.error||"Update failed");return}K.autoRestart&&(p("restarting"),await new Promise(ee=>setTimeout(ee,2e3))),p("reconnecting"),await wf(n?.currentVersion)?window.location.reload():(p("error"),m("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),T=Ye.useCallback(()=>{P(C)},[P,C]),M=y!=="idle"&&y!=="error",E=Ye.useMemo(()=>{if(!n?.body)return null;const K=n.body.trim();if(!K)return null;const Z=xf(K);return Z.length===0?{kind:"raw",title:"What's new",content:oi(K)}:{kind:"sections",title:"What's new",sections:[...Z].sort((te,_)=>gf(te.version,_.version)).map(te=>({version:te.version,dateLabel:pf(te.date),content:oi(mf(te.raw)||K)}))}},[n?.body]);return t.jsx(is,{open:e,onOpenChange:M?void 0:s,children:t.jsxs(as,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(hs,{className:"flex items-center gap-2.5",children:[t.jsx(k,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:y==="restarting"||y==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&M&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(k,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[y==="updating"&&"Installing update...",y==="restarting"&&"Server restarting...",y==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),E&&!M&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Cs,{className:"max-h-[400px] p-0",fillContainer:!1,children:E.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:K=>{const ee=K.target.closest("a");ee&&ee.href&&(K.preventDefault(),K.stopPropagation(),P(ee.href))},children:t.jsx(Oo,{content:E.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:E.sections.map(K=>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",K.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:K.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:Z=>{const te=Z.target.closest("a");te&&te.href&&(Z.preventDefault(),Z.stopPropagation(),P(te.href))},children:t.jsx(Oo,{content:K.content,disableLinkSafety:!0,enableFileReferences:!1})})]},K.version))})})}),v&&y==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:x}),t.jsx("button",{onClick:A,className:O("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"})})]})]}),!v&&!g&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[N,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${N}%`}})})]}),(l||h)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||h})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!g&&!i&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!g&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!g&&i&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),g&&t.jsxs(qe,{onClick:T,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!M&&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(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&M&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Sf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:O("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:O("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),hn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(et,{open:r,onOpenChange:i,children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:O("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(k,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(st,{sideOffset:8,className:O("max-w-sm",n),children:e})]})},ex="w-full min-w-40 max-w-48",jf="settings",Cf="w-full min-w-40 max-w-48",tx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",kf="w-full max-w-[24rem]",sx="min-w-0 flex-1",nx="flex w-full min-w-0 items-center gap-2",rx="typography-meta shrink-0 text-muted-foreground tabular-nums",Ra="space-y-3.5",Nf="space-y-1.5",ox="typography-settings-page-title text-muted-foreground",Af="typography-settings-section-title text-foreground",ix="typography-settings-section-title text-foreground",Ma="typography-settings-group-title text-foreground",uo="typography-settings-field-label text-foreground",If="typography-settings-description text-muted-foreground",pn="typography-meta text-muted-foreground",ax="typography-meta font-medium text-foreground",lx="typography-settings-section-title text-foreground",Df=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const b=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:O("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:Af,children:e}):e,n,r!=null?t.jsx(hn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:If,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:O(d),children:a})]})},cx=({children:e,className:s})=>t.jsx("div",{className:O("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Pf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:O(Ma,s),children:e}),dx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:O("space-y-2",i),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Pf,{children:e}),n!=null?t.jsx(hn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:pn,children:s}):null]}):null,t.jsx("div",{className:O(a),children:r})]}),Bs=({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:pn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:O("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:uo,children:e}),n!=null?t.jsx(hn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:O("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},ux=({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:O("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:uo,children:e}),n!=null?t.jsx(hn,{children:n}):null]}),s!=null?t.jsx("p",{className:O(pn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:O("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),fx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:O("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)},f=r!=null;return t.jsxs("div",{"data-settings-item":l,className:O("group flex cursor-pointer gap-2 py-0.5",f?"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:y=>{(y.key===" "||y.key==="Enter")&&(y.preventDefault(),b())},children:[t.jsx(Qi,{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:uo,children:n}),d,u!=null?t.jsx(hn,{children:u}):null]}),f?t.jsx("span",{className:pn,children:r}):null]})]})},hx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:O("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Sf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:O("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:pn,children:r}):null]})]}),px=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:O(Nf,n),children:s});function mx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:O("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(qe,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Tf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(wc,{className:"w-full max-w-md",children:[t.jsx(Sc,{className:"text-center",children:t.jsxs(jc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(k,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Cc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(qe,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(k,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Rf(e){return t.jsx(Tf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const gx=({active:e=!0,readOnly:s=!1})=>{const n=Oe(r=>r.currentSessionId);return t.jsx(Rf,{sessionId:n||void 0,children:t.jsx(kc,{active:e,readOnly:s},n??"no-session")})};function Mf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const fo=Ye.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:b,endSlot:f,...y},p)=>{const h=Ye.useRef(null),m=Ye.useRef(null),[S,C]=Ye.useState(null),N=c??S,v=Ye.useCallback(x=>{const A=h.current;if(!A)return;m.current={startY:x.clientY,startHeight:A.getBoundingClientRect().height};const P=x.currentTarget;P.setPointerCapture(x.pointerId);const D=M=>{const E=m.current;if(!E)return;const K=E.startHeight+(M.clientY-E.startY),Z=Math.max(82,K);d?d(Z):C(Z)},T=()=>{m.current=null,P.removeEventListener("pointermove",D),P.removeEventListener("pointerup",T),P.removeEventListener("pointercancel",T)};P.addEventListener("pointermove",D),P.addEventListener("pointerup",T),P.addEventListener("pointercancel",T),x.preventDefault()},[d]),g=Ye.useCallback(x=>{if(x.target.closest('textarea, button, [role="separator"]'))return;const P=h.current?.querySelector("textarea");P&&document.activeElement!==P&&(x.preventDefault(),P.focus())},[]);return b?t.jsx(Cs,{as:"textarea",ref:p,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:O("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}):t.jsx("div",{ref:h,onPointerDown:g,style:N!==null?{height:`${N}px`}:void 0,className:O("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:p,className:O("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...y}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[f,t.jsx(Mf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});fo.displayName="Textarea";const ai=(e,s)=>s.updatedAtMs-e.updatedAtMs,$n=ps((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([Dc(),_o()]),i={};for(const a of r.sort(ai))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 _o(),r={};for(const i of n.sort(ai))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Ac({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Ec(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await Bo(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 Bo(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})})),Fa=[{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"}],rn=Object.fromEntries(Fa.map(e=>[e.key,e.Icon])),Kr="pichamber:project-actions-updated",La=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ds=(e,s)=>`${La(e)}::${s}`,Ff=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},li=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Lf=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=li(s.localPort),r=li(s.remotePort);if(!n||!r)return null;const i=Ff(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},Oa=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Lf(n,r);i&&s.push(i)}return s},Of=(e,s)=>{const n=(e||"").trim();return n&&Oa(s).find(a=>a.id===n)?.url||null},Bf=kf,Ba=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Df,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Wr=e=>e.name.trim().length>0&&e.command.trim().length>0,_f=e=>e.name.trim().length===0&&e.command.trim().length===0,zf=e=>!Wr(e)&&!_f(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!Wr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Wr)},Uf=450,Gf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Hf=()=>({id:Gf(),name:"",command:"",icon:"play"}),Kf=({projectRef:e})=>{const s=o.useMemo(()=>fs(),[]),n=$n(x=>x.instances),r=$n(x=>x.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[b,f]=o.useState(new Set),y=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let x=!1;return c(!0),(async()=>{try{const A=await Ar(e);if(x)return;a(A.actions),u(JSON.stringify({actions:A.actions})),f(new Set(A.actions.map(P=>P.id)))}catch{if(x)return;a([]),u(JSON.stringify({actions:[]})),f(new Set)}finally{x||c(!1)}})(),()=>{x=!0}},[e]);const p=o.useMemo(()=>s?Oa(n):[],[n,s]),h=o.useMemo(()=>$f(i,b),[i,b]),m=o.useMemo(()=>JSON.stringify({actions:h.actions}),[h.actions]),S=d!==null&&h.canPersist&&m!==d,C=o.useCallback(async x=>await Tc(e,{actions:x,primaryActionId:null})?(u(JSON.stringify({actions:x})),f(new Set(x.map(P=>P.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Kr,{detail:{projectId:e.id}})),!0):(ce.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!S||l||y.current)return;const x=window.setTimeout(()=>{y.current||(y.current=!0,(async()=>{try{await C(h.actions)}finally{y.current=!1}})())},Uf);return()=>{window.clearTimeout(x)}},[S,l,C,h.actions]);const N=o.useCallback(()=>{const x=Hf();a(A=>[...A,x])},[]),v=o.useCallback(x=>{a(A=>A.filter(P=>P.id!==x))},[]),g=o.useCallback((x,A)=>{a(P=>P.map(D=>D.id===x?A(D):D))},[]);return t.jsx(Ba,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(qe,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:N,children:[t.jsx(k,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:O("space-y-6",Bf),children:i.map((x,A)=>{const P=x.icon||"play",D=rn[P]||"play",T=x.name.trim()||`Action ${A+1}`,M=zf(x);return t.jsxs("div",{className:Ra,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ma,children:T}),t.jsx(qe,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>v(x.id),"aria-label":`Delete ${T}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Bs,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(k,{name:D,className:"h-4 w-4"})})}),t.jsx(qt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Fa.map(E=>{const K=E.Icon,Z=(x.icon||"play")===E.key;return t.jsx("button",{type:"button",onClick:()=>g(x.id,ee=>({...ee,icon:E.key})),className:O("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",Z&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${E.label}`,children:t.jsx(k,{name:K,className:"h-4 w-4"})},E.key)})})})]}),t.jsx(Gs,{value:x.name,onChange:E=>g(x.id,K=>({...K,name:E.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Bs,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(fo,{value:x.command,onChange:E=>g(x.id,K=>({...K,command:E.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),M?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Ef,{checked:x.autoOpenUrl===!0,onChange:E=>g(x.id,K=>({...K,...E?{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 ${T}`}),x.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Bs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Gs,{value:x.openUrl||"",onChange:E=>g(x.id,K=>({...K,openUrl:E.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Bs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:p.length>0?t.jsxs(Rc,{value:x.desktopOpenSshForward&&p.some(E=>E.id===x.desktopOpenSshForward)?x.desktopOpenSshForward:"__none__",onValueChange:E=>{g(x.id,K=>({...K,...E==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:E}}))},children:[t.jsx(Mc,{size:jf,className:"w-full",children:t.jsx(Fc,{placeholder:"Use output/manual URL"})}),t.jsxs(Lc,{children:[t.jsx(zo,{value:"__none__",children:"Use output/manual URL"}),p.map(E=>t.jsx(zo,{value:E.id,children:E.label},E.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},x.id)})})})},Wf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=Mt(M=>M.providers),d=Mt(M=>M.modelsMetadata),u=fe(M=>M.hiddenModels),b=fe(M=>M.providerOrder),f=fe(M=>M.setProviderOrder),y=fe(M=>M.isFavoriteModel),p=fe(M=>M.toggleFavoriteModel),h=fe(M=>M.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:S}=Oc(),[C,N]=o.useState(!1),[v,g]=o.useState("");o.useEffect(()=>{C||g("")},[C]);const x=e?c.find(M=>M.id===e.providerId):void 0,A=e&&x?(Array.isArray(x.models)?x.models:[]).find(M=>M.id===e.modelId):void 0,P=e?Bc(A,e.modelId):s,D=o.useMemo(()=>e?u.filter(M=>!(M.providerID===e.providerId&&M.modelID===e.modelId)):u,[u,e]),T=o.useCallback(M=>{l({providerId:M.providerID,modelId:M.modelID}),N(!1)},[l]);return t.jsxs(Yt,{modal:!1,open:C,onOpenChange:M=>{r||N(M)},children:[t.jsx(Vt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:O(zc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(_c,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:O("truncate",e?"text-foreground":"text-muted-foreground"),children:P})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx($c,{providers:c,favoriteModels:m,recentModels:S,modelsMetadata:d,searchQuery:v,onSearchQueryChange:g,onSelect:T,labels:{...Wf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:D,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),N(!1)},disabled:r,autoFocus:!0,onEscape:()=>N(!1),isFavorite:M=>y(M.providerID,M.modelID),onToggleFavorite:M=>p(M.providerID,M.modelID),onReorderFavorite:(M,E)=>h(M.providerID,M.modelID,E.providerID,E.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:b,onReorderProvider:f,reorderProviderTitle:"Drag to reorder provider"})})]})},dr="w-full max-w-none",Vf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=Mt(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Ba,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ra,children:[t.jsx(Bs,{label:"Name",settingsItem:"projects.name",controlClassName:dr,children:t.jsx(Gs,{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(Bs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:dr,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:dr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},qf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Uc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,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}},Qf=450,Jf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{ce.error("Failed to save project settings")}}finally{l.current=!1}})())},Qf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Xf=({project:e,onIdentitySave:s})=>{const n=qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Jf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Vf,{form:n}),t.jsx(Kf,{projectRef:r})]})};function Zf({...e}){return t.jsx(va,{...e})}function eh({...e}){return t.jsx(wa,{...e})}function th({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(Br,{children:t.jsx(_r,{className:O("app-region-no-drag z-50",s),children:t.jsx(zr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:O(Ir,e),...i,children:n})})})}function ci({className:e,...s}){return t.jsx(Sa,{className:O(Ji,e),...s})}function sh({className:e,...s}){return t.jsx(ja,{className:O(Xi,e),...s})}const js=ps()(Ca(ao((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=ro()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await Jt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await no({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return cs("saving"),await Kc(r),cs("saved"),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return cs("saving"),await Hc(n,a),cs("saved"),await s().loadProfiles(),!0}catch(i){return cs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return cs("saving"),await Gc(n),cs("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return cs("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:fu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=js);const nh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],rh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function oh(e){const s=e.trim().toLowerCase();return nh.find(n=>n.slug===s)??null}function ih(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=rh[s];if(n)return n;const r=oh(s);return r?r.slug:"home"}function xx(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 wn=100;function bx(){const e=fe(D=>D.isArchivePageOpen),s=fe(D=>D.setArchivePageOpen),n=fe(D=>D.setActiveMainTab),r=Oe(D=>D.setCurrentSession),i=Oe(D=>D.unarchiveSession),a=Ds(D=>D.homeDirectory),l=Dr({archived:!0}),[c,d]=o.useState(""),[u,b]=o.useState(null),[f,y]=o.useState(wn),p=c.trim().toLowerCase(),h=o.useMemo(()=>e?[...l].sort((D,T)=>(T.time?.archived??0)-(D.time?.archived??0)):[],[l,e]),m=o.useMemo(()=>{const D=new Map;for(const T of h){const M=gt(zs(T))??"",E=D.get(M);if(E){E.sessions.push(T);continue}D.set(M,{directory:M,label:M?As(M,a)||M:"other projects",sessions:[T]})}return[...D.values()].sort((T,M)=>M.sessions.length-T.sessions.length)},[a,h]),S=o.useMemo(()=>p?h.filter(D=>(D.title??"").toLowerCase().includes(p)):u===null?h:m.find(D=>D.directory===u)?.sessions??[],[m,p,u,h]),C=S.slice(0,f),N=S.length-C.length,v=l.length,g=o.useCallback(D=>{b(D),y(wn)},[]),x=o.useCallback(D=>{const T=gt(zs(D));r(D.id,T??void 0),n("chat"),s(!1)},[n,r,s]),A=o.useCallback(D=>{i(D.id).then(T=>{T?ce.success("Session restored"):ce.error("Failed to restore session")})},[i]);if(!e)return null;const P=(D,T,M,E,K,Z,ee)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:K,title:Z,className:O("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",ee?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",E?"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:T}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),ee?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Is.requestDelete({sessions:ee,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 ${T}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},D);return t.jsx(Ru,{open:e,onOpenChange:s,children:t.jsxs(Mu,{children:[t.jsx(Fu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Lu,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Ou,{className:"sr-only",children:"Archived sessions"}),t.jsx(Bu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(_u,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(k,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[P("__all__","All directories",v,u===null,()=>g(null)),m.map(D=>P(D.directory||"__none__",D.label,D.sessions.length,u===D.directory,()=>g(D.directory),D.directory||void 0,D.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:D=>{d(D.target.value),y(wn)},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:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[C.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:p?"No matching archived sessions":"No archived sessions"})}):C.map(D=>{const T=gt(zs(D))??"",M=T?As(T,a)||T: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:()=>x(D),role:"button",tabIndex:0,onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),x(D))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:D.title||"Untitled Session"}),p&&M?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:T,children:M}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:qc(D.time?.archived??D.time?.updated??D.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),A(D)},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 ${D.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:E=>{E.stopPropagation(),Is.requestDelete({sessions:[D],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 ${D.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},D.id)}),N>0?t.jsx("button",{type:"button",onClick:()=>y(D=>D+wn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const ah=()=>{const[e,s]=Ye.useState(!1),[n,r]=Ye.useState(!1);Ye.useEffect(()=>{s(fs()),r(oo())},[]);const i=Ye.useCallback(async c=>e?await io(c):{success:!0,path:c},[e]),a=Ye.useCallback(async c=>e?await hu():{success:!0},[e]),l=Ye.useCallback(async c=>e?await pu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},lh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ch=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[b,f]=o.useState(""),[y,p]=o.useState(!1),[h,m]=o.useState(!1),[S,C]=o.useState(""),[N,v]=o.useState(!1),g=o.useRef(null),x=o.useCallback(_=>{_.stopPropagation()},[]),A=l.length>1,P=o.useMemo(()=>lh(S),[S]),D=o.useMemo(()=>{const _=b.toLowerCase();return _?s.filter(H=>H.toLowerCase().includes(_)):s},[b,s]),T=o.useMemo(()=>{const _=b.toLowerCase();return _?n.filter(H=>H.toLowerCase().includes(_)):n},[b,n]),M=_=>{if(_===e){u(!1);return}i(_),u(!1),f("")},E=()=>{p(!0),setTimeout(()=>g.current?.focus(),50)},K=async()=>{if(!(!P||N)){if(A){m(!0);return}v(!0);try{await a(P,l[0]),C(""),p(!1),u(!1)}finally{v(!1)}}},Z=async _=>{if(!(!P||N)){v(!0);try{await a(P,_),C(""),p(!1),m(!1),u(!1)}finally{v(!1)}}},ee=()=>{m(!1)},te=()=>{C(""),p(!1),m(!1)};return o.useEffect(()=>{d||(f(""),p(!1),m(!1),C(""))},[d]),t.jsxs(Yt,{open:d,onOpenChange:u,children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Current branch"})]}),t.jsx(qt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(Qc,{className:"h-full min-h-0",children:[t.jsx(Jc,{placeholder:"Search branches...",value:b,onValueChange:f,onKeyDown:x}),t.jsxs(Xc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Zc,{children:"No branches found."}),t.jsx(ir,{children:h?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:ee,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:P})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(_=>t.jsxs("button",{type:"button",onClick:()=>Z(_),disabled:N,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[N?t.jsx(k,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,_.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:_.pushUrl})]},_.name))})]}):y?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:g,placeholder:"New branch name",value:S,onChange:_=>C(_.target.value),onClick:_=>_.stopPropagation(),onKeyDown:_=>{x(_),_.key==="Enter"?(_.preventDefault(),K()):_.key==="Escape"&&(_.preventDefault(),te())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:K,disabled:!P||N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:N?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:te,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(qs,{onSelect:E,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx($o,{}),t.jsxs(ir,{heading:"Local branches",children:[D.map(_=>t.jsxs(qs,{onSelect:()=>M(_),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:_}),(r?.[_]?.ahead||r?.[_]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[_].ahead||0," ahead ·"," ",r[_].behind||0," behind"]})]}),e===_&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${_}`)),D.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx($o,{}),t.jsxs(ir,{heading:"Remote branches",children:[T.map(_=>t.jsx(qs,{onSelect:()=>M(_),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:_})},`remote-${_}`)),T.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},dh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),uh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),b=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},f=async()=>{if(!e||!s||!a.trim())return;const h=dh(a);if(h===e){i(!1);return}d(!0);try{await s(e,h),i(!1),l("")}finally{d(!1)}},y=()=>{i(!1),l("")},p=h=>{h.key==="Enter"?(h.preventDefault(),f()):h.key==="Escape"&&(h.preventDefault(),y())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),f()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:h=>l(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:y,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(qe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:b,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},fh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:b=!1})=>{const f=o.useRef(!1),y=!!l,p=s.find(x=>x.name===u)??s[0],h=d>0&&b,m=a||e!==null||y||!p||h,S=a||e!==null||y||s.length===0,C=c>0||d>0,N=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=h?"Commit or stash your changes before syncing":p?C?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",g=()=>{p&&r(p)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:h?0:void 0,children:t.jsxs("button",{type:"button",onClick:g,disabled:m,className:O("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:N})]})})}),t.jsx(st,{sideOffset:8,children:v})]}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O("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:S,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(qt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(x=>t.jsx(wt,{onSelect:A=>{if(f.current){A.preventDefault(),f.current=!1;return}n(x)},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 ${x.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:x.fetchUrl})]})}),i&&x.name!==u?t.jsx(qe,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||y,onPointerDown:A=>{f.current=!0,A.preventDefault(),A.stopPropagation()},onClick:A=>{f.current=!0,A.preventDefault(),A.stopPropagation(),i(x)},"aria-label":`Remove remote ${x.name}`,title:`Remove remote ${x.name}`,children:l===x.name?t.jsx(k,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(k,{name:"close",className:"size-3.5"})}):null]})},x.name))})]})]})},hh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ph={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function _a(e){return e&&ph[e]||"var(--primary)"}const di=({icon:e,className:s,colorToken:n})=>{const r=hh[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:_a(n)}})},za=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs(qe,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:_a(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(di,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Git identity"})]}),t.jsx(qt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(wt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(di,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(k,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},mh=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(et,{delayDuration:n,children:[t.jsx(tt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(st,{sideOffset:8,children:a})]})},yx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:b,onCreateBranch:f,onRenameBranch:y,activeIdentityProfile:p,availableIdentities:h,onSelectIdentity:m,isApplyingIdentity:S,isWorktreeMode:C,onOpenHistory:N,onOpenGraph:v,onOpenStashes:g,onOpenUpdateBranch:x,onOpenReintegrateCommits:A,pullRequest:P,prChecks:D,onOpenPullRequest:T})=>{if(!e)return null;const M=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:N||v||g||x?t.jsxs(Yt,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsx(qe,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(k,{name:"more-fill",className:"size-4"})})})}),t.jsx(st,{sideOffset:8,children:"Repository views"})]}),t.jsxs(qt,{align:"end",children:[N?t.jsxs(wt,{onSelect:N,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(wt,{onSelect:v,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,g?t.jsxs(wt,{onSelect:g,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,x?t.jsxs(wt,{onSelect:x,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,A?t.jsxs(wt,{onSelect:A,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),E=D?D.state==="success"?"var(--status-success)":D.state==="failure"?"var(--status-error)":"var(--status-warning)":null,K=P?P.state==="merged"?"merged":P.state==="closed"?"closed":P.draft?"draft":D?.state==="failure"||P.mergeable===!1||P.mergeableState==="blocked"||P.mergeableState==="dirty"?"blocked":"open":null,Z=P&&T?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs(qe,{variant:"ghost",size:"sm",onClick:T,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-${K})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${P.number}`}),E?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:E}}):null]})}),t.jsx(st,{sideOffset:8,children:"Open pull request"})]}):null,ee=t.jsx(fh,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),te=e.upstreamComparison?t.jsx(mh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,_=t.jsx(za,{activeProfile:p,identities:h,onSelect:m,isApplying:S,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:C?t.jsx(uh,{currentBranch:e.current,onRename:y}):t.jsx(ch,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:b,onCreate:f,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:[Z?t.jsx("div",{className:"shrink-0",children:Z}):null,t.jsx("div",{className:"min-w-0 flex-1"}),te?t.jsx("div",{className:"min-w-0 shrink",children:te}):null,M,t.jsx("div",{className:"shrink-0",children:ee})]})]})},gh=e=>e==="/",$s=e=>e.replace(/\\/g,"/"),Ks=e=>{if(!e||gh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Us=e=>e.endsWith("/"),Un=e=>{const s=e.trim();return!s||Us(s)?s:`${s}/`},ho=e=>e.lastIndexOf("/"),$a=e=>{if(Us(e))return e;const s=ho(e);return s<0?e:e.slice(0,s+1)},Ua=e=>{const s=ho(e);return e.slice(s+1)},Ga=e=>{const s=Ks(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=ho(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ha=e=>Us(e)&&Ga(e)!==null,xh=e=>{if(!Ha(e))return null;const s=Ks(e.trim());return Ua(s)||s},bh=(e,s)=>`${$a(e)}${s}/`,ws=e=>{if(!e)return null;const s=Ks($s(e.trim()));return s?s.toLowerCase():null},ui=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},yh=(e,s)=>{const n=Ks($s(e.trim())),r=Ks($s(s.trim()));if(!n)return"";if(!r)return Un(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Un(n)},vh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,ur=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},wh=async()=>bu(),Sh=({open:e,onOpenChange:s})=>{const n=Ds(F=>F.homeDirectory),r=Ot(F=>F.projects),i=Ot(F=>F.addProject),a=fe(F=>F.setActiveMainTab),l=fe(F=>F.setSessionSwitcherOpen),c=Oe(F=>F.openNewSessionDraft),d=js(F=>F.profiles),u=js(F=>F.globalIdentity),b=js(F=>F.defaultGitIdentityId),f=js(F=>F.loadProfiles),y=js(F=>F.loadGlobalIdentity),p=js(F=>F.loadDefaultGitIdentityId),{canRequestAccess:h,startAccessing:m}=ah(),{isMobile:S,isTablet:C}=Ps(),N=S||C,v=o.useRef(null),g=o.useRef(new Map),[x,A]=o.useState(""),[P,D]=o.useState("~/"),[T,M]=o.useState([]),[E,K]=o.useState(!1),[Z,ee]=o.useState(!1),[te,_]=o.useState(null),[H,B]=o.useState(0),[z,Y]=o.useState(0),[re,G]=o.useState(!1),[Te,Re]=o.useState(!1),[He,Ke]=o.useState(!1),[Ue,Ae]=o.useState(""),[X,xe]=o.useState(null),[We,Ce]=o.useState(!1),[je,$e]=o.useState("right"),nt=o.useRef("~/"),_e=x||n,q=o.useMemo(()=>new Set(r.map(F=>ws(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;D("~/"),M([]),Y(0),G(!1),Re(!1),Ke(!1),Ae(""),xe(null),Ce(!1),nt.current="~/",$e("right"),N||requestAnimationFrame(()=>ur(v.current));let F=!1;return(async()=>{const Be=await wh();F||(A(Be||n||""),N||requestAnimationFrame(()=>ur(v.current)))})(),()=>{F=!0}},[n,e,N]),o.useEffect(()=>{e&&(f(),y(),p())},[p,f,y,e]);const V=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Se of d)F.set(Se.id,Se);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!He||X!==null)return;const F=typeof b=="string"?b.trim():"";if(F&&V.some(Be=>Be.id===F)){xe(F);return}const Se=V.find(Be=>Be.authType==="ssh"||Be.sshKey);Se&&xe(Se.id)},[V,b,He,e,X]);const be=o.useMemo(()=>V.find(F=>F.id===X)??null,[V,X]),Q=o.useMemo(()=>$a(P),[P]),ve=o.useMemo(()=>Us(P)?"":Ua(P),[P]),pe=o.useMemo(()=>_e?ui(Q,_e):"",[Q,_e]);o.useEffect(()=>{const F=nt.current;F!==Q&&($e(Q.length>=F.length?"right":"left"),nt.current=Q)},[Q]),o.useEffect(()=>{if(!e||!pe){M([]),_(null);return}let F=!1;return K(!0),ee(!1),_(null),mu(pe).then(Se=>{if(F)return;ee(!1),_(null);const Be=Se.filter(ot=>ot.isDirectory).map(ot=>({name:ot.name,path:$s(ot.path)})).sort((ot,L)=>ot.name.localeCompare(L.name));M(Be)}).catch(Se=>{if(!F){M([]);const Be=gu(Se)?Se.reason:"unknown";_(Be),ee(Be==="not-found")}}).finally(()=>{F||K(!1)}),()=>{F=!0}},[pe,H,e]);const De=o.useMemo(()=>{const F=ve.toLowerCase(),Se=We||ve.startsWith(".");return T.filter(Be=>Be.name.toLowerCase().startsWith(F)&&(Se||!Be.name.startsWith(".")))},[ve,T,We]),at=o.useMemo(()=>xh(P),[P]),ht=o.useMemo(()=>Ga(P),[P]),Ve=o.useMemo(()=>{const F=[],Se=ws(pe);Ha(P)&&at&&ht&&F.push({type:"parent",value:"browse:up",name:at,path:ht,alreadyAdded:!!(Se&&q.has(Se))});for(const Be of De){const ot=ws(Be.path);F.push({type:"directory",value:`browse:${Be.path}`,name:Be.name,path:Be.path,alreadyAdded:!!(ot&&q.has(ot))})}return F},[q,pe,at,De,ht,P]);o.useEffect(()=>{Y(0)},[P,Ve.length]);const Me=o.useMemo(()=>_e?Ks(ui(P,_e)):"",[_e,P]),ke=ws(Me),Le=!!(ke&&q.has(ke)),dt=o.useMemo(()=>ve?De.find(F=>F.name===ve)??null:null,[ve,De]),bt=!!(Me&&!Le&&(te===null||te==="not-found")&&(Us(P)&&Z||!Us(P)&&ve.trim().length>0&&dt===null)),rt=!re&&!Te&&!Le&&te!=="os-permission"&&te!=="invalid-response"&&te!=="unknown"&&!!Me,$=rt&&Ue.trim().length>0,me=Ve[z]??null,Ne=!!me,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",W=Le?"Already added":He?re?"Cloning...":"Clone & add":re?"Adding...":bt?"Create & add":"Add folder",se=He?$:rt;o.useLayoutEffect(()=>{const F=v.current;F&&(F.scrollLeft=F.scrollWidth)},[P]),o.useLayoutEffect(()=>{!e||N||ur(v.current)},[e,N]),o.useLayoutEffect(()=>{const F=Ve[z];F&&g.current.get(F.value)?.scrollIntoView({block:"nearest"})},[z,Ve]);const de=o.useCallback(()=>{s(!1)},[s]),we=o.useCallback((F,Se)=>{a("chat"),S&&l(!1),c({selectedProjectId:F,directoryOverride:Se}),de()},[de,S,c,a,l]),Ie=o.useCallback(async F=>{if(!F||re)return;const Se=ws(F);if(Se&&q.has(Se))return;let Be=F;G(!0);try{const ot=!He&&bt&&ws(F)===ws(Me);if(He){const oe=Ue.trim();if(!oe){ce.error("Enter a repository URL before cloning.");return}const he=await Jt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:oe,destinationPath:F,gitIdentityId:be?.id??null})});if(!he.ok)throw new Error("Failed to clone git repository");Be=(await he.json()).path||F}else if(ot&&!(await Jt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:pe?{directory:pe}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const L=i(Be);if(!L){ce.error("Failed to add folder",{description:"Please select a valid directory path."});return}we(L.id,L.path)}catch(ot){ce.error("Failed to select directory",{description:ot instanceof Error?ot.message:"Unknown error occurred."})}finally{G(!1)}},[i,q,pe,Ue,He,re,we,be?.id,bt,Me]),ze=o.useCallback(F=>{D(Un(F))},[]),lt=o.useCallback(F=>{D(bh(P,F.name))},[P]),St=o.useCallback(F=>{if(F){if(F.type==="parent"){ze(F.path);return}lt(F)}},[ze,lt]),Je=o.useCallback(async F=>{const Se=await m(F);if(!Se.success)return ce.error("Failed to open directory",{description:Se.error||"Desktop could not grant file access."}),!1;const Be=_e?yh(F,_e):Un($s(F));return ze(Be),!0},[ze,_e,m]),ct=o.useCallback(async()=>{if(!Te){Re(!0);try{if(oo()){const Se=await io(Me);if(!Se.success||!Se.path){Se.error&&Se.error!=="Directory selection cancelled"&&ce.error("Failed to select directory",{description:Se.error});return}await Je(Se.path);return}const F=await xu(Me);if(F.status==="cancelled")return;if(F.status!=="picked"){ce.error("Couldn't open a folder picker",{description:F.error});return}await Je(F.path)}catch(F){ce.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Re(!1)}}},[Je,Te,Me]),pt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),Y(Se=>Math.min(Ve.length-1,Se+1));return}if(F.key==="ArrowUp"){F.preventDefault(),Y(Se=>Math.max(0,Se-1));return}if(F.key==="Enter"){if(F.preventDefault(),vh(F)){Ie(Me);return}Ne&&St(me);return}F.key==="Backspace"&&P===""&&(F.preventDefault(),de())},[St,Ie,de,Ne,me,P,Ve.length,Me]),Fe=t.jsxs("button",{type:"button",onClick:()=>Ce(F=>!F),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[We?t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Ge=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(Gs,{ref:v,value:P,onChange:F=>D($s(F.target.value)),onKeyDown:pt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(qe,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:re||Te,onMouseDown:F=>F.preventDefault(),onClick:()=>{ct()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),Te?"Opening...":"Browse"]})]})}),mt=Ve.some(F=>F.type==="parent"),Tt=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":He,disabled:re||Te,onClick:()=>Ke(F=>!F),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),He?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(Gs,{value:Ue,onChange:F=>Ae(F.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(za,{activeProfile:be,identities:V,onSelect:F=>xe(F.id),isApplying:re,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:O("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",je==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:E?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):te&&te!=="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:te==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[te==="os-permission"&&h?t.jsx(qe,{size:"xs",onClick:()=>{ct()},disabled:Te,children:"Grant access"}):null,t.jsx(qe,{variant:"outline",size:"xs",onClick:()=>B(F=>F+1),children:"Try again"})]})]}):Ve.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:Ve.map((F,Se)=>{const Be=Se===z,ot=F.type==="directory"&&mt;return t.jsxs("button",{ref:L=>{L?g.current.set(F.value,L):g.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>Y(Se),onMouseDown:L=>L.preventDefault(),onClick:()=>St(F),className:O("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Be&&"bg-interactive-selection text-interactive-selection-foreground",!Be&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:O("flex min-w-0 flex-1 items-center gap-2",ot&&"pl-4"),children:[F.type==="parent"?t.jsx(k,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(k,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:F.name})]}),F.alreadyAdded?t.jsx("span",{className:O("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Be?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(k,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(k,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},Q)]})}),Bt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ge,Tt]}),vt=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(k,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:w}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),jt=t.jsx(qe,{size:S?"xs":"default",onClick:()=>{Ie(Me)},disabled:!se,className:O(S&&"w-full flex-1"),children:W}),kt=()=>t.jsxs(t.Fragment,{children:[S?null:vt,t.jsx("div",{className:O("flex w-full flex-row justify-end gap-2 sm:w-auto",S&&"justify-stretch"),children:jt})]});return S?t.jsx(Zi,{open:e,onClose:de,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:kt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Fe}),Bt]})}):t.jsx(is,{open:e,onOpenChange:s,children:t.jsxs(as,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(ys,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Es,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Fe]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Bt}),t.jsx(Ts,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:kt()})]})})},Sn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,vx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=ed,c=Oe(A=>A.deleteSessions),d=fe(A=>A.showDeletionDialog),u=fe(A=>A.setShowDeletionDialog),{isMobile:b,isTablet:f,hasTouchInput:y}=Ps(),p=b||f||y;o.useEffect(()=>yu(()=>{s(!1)}),[]);const h=o.useCallback(A=>{r({sessions:A.sessions,dateLabel:A.dateLabel})},[]),m=o.useCallback(()=>{r(null),a(!1)},[]),S=o.useCallback(async A=>{if(A.sessions.length===0)return;if(A.sessions.length===1){const M=A.sessions[0];await l(M.id)?ce.success("Session deleted"):ce.error("Failed to delete session");return}const P=A.sessions.map(M=>M.id),{deletedIds:D,failedIds:T}=await c(P);if(D.length>0){const M=T.length>0?T.length===1?`${T.length} session could not be deleted.`:`${T.length} sessions could not be deleted.`:A.dateLabel?`Removed all sessions from ${A.dateLabel}.`:void 0;ce.success(D.length===1?"Deleted {count} session":`Deleted ${D.length} sessions`,{description:Sn(M)})}T.length>0&&ce.error(T.length===1?`Failed to delete ${T.length} session`:`Failed to delete ${T.length} sessions`,{description:Sn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Is.onDeleteRequest(A=>{if(!d){S(A);return}h(A)}),[h,d,S]),o.useEffect(()=>Is.onDirectoryRequest(()=>{s(!0)}),[]);const C=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const A=n.sessions[0];if(!await l(A.id)){ce.error("Failed to delete session"),a(!1);return}ce.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const A=n.sessions.map(M=>M.id),P=await c(A),D=P.deletedIds,T=P.failedIds;if(D.length>0){const M=T.length>0?T.length===1?`${T.length} session could not be deleted.`:`${T.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ce.success(D.length===1?"Deleted {count} session":`Deleted ${D.length} sessions`,{description:Sn(M),action:{label:"OK",onClick:()=>{}}})}if(T.length>0&&(ce.error(T.length===1?`Failed to delete ${T.length} session`:`Failed to delete ${T.length} sessions`,{description:Sn("Please try again in a moment.")}),D.length===0)){a(!1);return}}m()}finally{a(!1)}}},[n,l,c,m]),N=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(A=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:A.title||"Untitled Session"})},A.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,g=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(k,{name:"checkbox-blank",className:"size-4"}):t.jsx(k,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(qe,{variant:"ghost",onClick:m,disabled:i,children:"Cancel"}),t.jsx(qe,{variant:"destructive",onClick:C,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),x=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[p?t.jsx(Zi,{open:!!n,onClose:()=>{i||m()},title:x,footer:t.jsx("div",{className:"flex justify-end gap-2",children:g}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[N&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:N}),v]})}):t.jsx(is,{open:!!n,onOpenChange:A=>{if(!A){if(i)return;m()}},children:t.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:x}),N&&t.jsx(Es,{children:N})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ts,{className:"mt-2 gap-2 pt-1 pb-1",children:g})]})}),t.jsx(Sh,{open:e,onOpenChange:s})]})};function wx(){const e=o.useMemo(()=>Vi(),[]),s=o.useRef(!1),n=o.useRef(!1),r=Oe(f=>f.setCurrentSession),i=fe(f=>f.setActiveMainTab),a=fe(f=>f.setSettingsDialogOpen),l=fe(f=>f.setSettingsPage),c=fe(f=>f.navigateToDiff),d=o.useCallback(async f=>{if(!n.current){n.current=!0;try{if(f.sessionId){const y=Oe.getState().currentSessionId,p=Qs().getState().selectedSessionId;if(f.sessionId!==y||f.sessionId!==p){const m=(e&&typeof window<"u"?new URLSearchParams(window.location.search).get("directory"):null)||Oe.getState().getDirectoryForSession(f.sessionId);r(f.sessionId,m)}}if(f.settingsPath){l(ih(f.settingsPath)),a(!0);return}fe.getState().isSettingsDialogOpen&&a(!1),f.tab&&i(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&c(f.diffFile)}finally{n.current=!1}}},[e,r,i,a,l,c]),u=o.useCallback(()=>{const f=Oe.getState(),y=Qs().getState(),p=fe.getState();return{sessionId:ar({currentSessionId:f.currentSessionId,piSelectedSessionId:y.selectedSessionId,draft:f.newSessionDraft}),tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsPath:p.settingsPage,diffFile:p.pendingDiffFile}},[]),b=o.useCallback((f={})=>{if(e||n.current)return;const y=u();Ur(y,f)},[e,u]);o.useEffect(()=>{if(s.current||(s.current=!0,!Uo()))return;const f=Go();(async()=>(await d(f),e||Ur({...u(),sessionId:f.sessionId??ar({currentSessionId:Oe.getState().currentSessionId,piSelectedSessionId:Qs().getState().selectedSessionId,draft:Oe.getState().newSessionDraft}),tab:f.tab??fe.getState().activeMainTab,settingsPath:f.settingsPath??fe.getState().settingsPage,diffFile:f.diffFile??fe.getState().pendingDiffFile},{replace:!0,force:!0})))()},[d,u,e]),o.useEffect(()=>{if(e)return;const f=()=>{const C=Oe.getState(),N=Qs().getState();return ar({currentSessionId:C.currentSessionId,piSelectedSessionId:N.selectedSessionId,draft:C.newSessionDraft})};let y=f(),p=Oe.getState().newSessionDraft?.open===!0;const h=()=>{const C=Oe.getState(),N=f(),v=C.newSessionDraft?.open===!0;N===y&&v===p||n.current||(y=N,p=v,b({replace:!0}))},m=Oe.subscribe(()=>{h()}),S=Qs().subscribe(()=>{h()});return()=>{m(),S()}},[e,b]),o.useEffect(()=>{if(e)return;let f=fe.getState().activeMainTab,y=fe.getState().isSettingsDialogOpen,p=fe.getState().settingsPage,h=fe.getState().pendingDiffFile;return fe.subscribe(S=>{if(n.current)return;const C=S.activeMainTab!==f,N=S.isSettingsDialogOpen!==y,v=S.settingsPage!==p,g=S.pendingDiffFile!==h&&S.activeMainTab==="diff";f=S.activeMainTab,y=S.isSettingsDialogOpen,p=S.settingsPage,h=S.pendingDiffFile,(C||N||v||g)&&b()})},[e,b]),o.useEffect(()=>{if(typeof window>"u"||e)return;const f=()=>{const y=Go();if(Uo())d(y);else{const p=fe.getState();p.isSettingsDialogOpen&&a(!1),p.activeMainTab!=="chat"&&i("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,e,i,a])}function jh(e=!0){const s=Mn(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=f=>{const y=Math.round(f*1e3);return Math.max(a,Math.min(l,y))},b=f=>{c||(d=window.setTimeout(async()=>{const y=await n.current(),p=typeof y=="number"&&Number.isFinite(y)?u(y):i;b(p)},f))};return b(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Sx(){const e=tn(s=>s.connection==="ready",void 0,"chrome");return jh(e),null}const fi=12,Ch=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],kh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Ch,onComplete:a})=>{const l=Ye.useRef(!1);Ye.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ye.useMemo(()=>Array.from({length:fi},(d,u)=>{const b=Math.PI*2*u/fi;return{x:Math.cos(b),y:Math.sin(b),delay:u*18}}),[]);return e?t.jsx("div",{className:O("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,f)=>{const y=b.x*d.radius,p=b.y*d.radius,h={"--translate-x":`${y}px`,"--translate-y":`${p}px`,"--particle-delay":`${b.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:h},`${d.id}-${f}-${s}`)})},`${d.id}-${s}`)})}):null},Nh=({durationMs:e=3400}={})=>{const[s,n]=Ye.useState({isActive:!1,cycle:0}),r=Ye.useRef(null),i=Ye.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ye.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Ye.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return Ye.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Ka=o.createContext(void 0),jx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Nh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Ka.Provider,{value:a,children:[e,t.jsx(kh,{isActive:s,burstKey:n})]})},Ah={triggerFireworks:()=>{},dismissFireworks:()=>{}},Cx=()=>o.useContext(Ka)??Ah,hi=380,pi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Gn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),jn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(k,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ih=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),b=o.useRef(null),[f,y]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const h=()=>{const C=n.current?.getBoundingClientRect(),N=b.current?.getBoundingClientRect();if(!C||!N){y(null);return}const v=C.left-N.left,g=Math.min(Math.max(v,8),Math.max(8,N.width-hi-8));y(g)};h();const m=b.current;if(typeof ResizeObserver>"u"||!m)return;const S=new ResizeObserver(h);return S.observe(m),()=>S.disconnect()},[n,u,e,a]);const p=u&&f!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const h=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(h)},[e,a]),o.useEffect(()=>{if(!e)return;const h=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),o.useEffect(()=>{if(!e)return;const h=m=>{const S=m.target;if(!(S instanceof Node)){s();return}i.current?.contains(S)||n.current?.contains(S)||s()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("wheel",h,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("wheel",h,!0)}},[n,s,e]),a?t.jsxs("div",{ref: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:O("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",p?"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))",...p?{top:8,left:f??8,width:`min(${hi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(jn,{iconNode:t.jsx(ta,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:O("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(jn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheRead)})}),t.jsx(jn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Gn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(jn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
3
+ @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},Dh=o.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:i,isNewSessionDraftOpen:a}){const l=o.useRef(null),c=td(r??""),d=Mt(_=>_.providers),u=Mt(_=>_.currentProviderId),b=Mt(_=>_.currentModelId),f=Mt(_=>_.getCurrentModel()),y=Mt(_=>_.getModelMetadata);Mt(_=>_.modelsMetadata.size);const p=ea(o.useCallback(_=>r?_.sessionModelSelections.get(r)??null:null,[r])),h=o.useMemo(()=>{for(let _=c.length-1;_>=0;_-=1){const H=c[_]?.info;if(H.role!=="user")continue;const B=H.model,z=B?.providerID??B?.providerId,Y=B?.modelID??B?.modelId,re=typeof z=="string"&&z.trim().length>0?z:void 0,G=typeof Y=="string"&&Y.trim().length>0?Y:void 0;if(re&&G)return{providerID:re,modelID:G}}return null},[c]),m=o.useMemo(()=>{for(let _=c.length-1;_>=0;_-=1){const H=c[_];if(H?.info.role==="assistant"&&Ho(H).total>0)return H}return null},[c]),S=h??(()=>{const _=m?.info.model,H=_?.providerID??_?.providerId,B=_?.modelID??_?.modelId;return H&&B?{providerID:H,modelID:B}:null})()??(p?{providerID:p.providerId,modelID:p.modelId}:null)??(u&&b?{providerID:u,modelID:b}:null),N=(S?d.find(_=>_.id===S.providerID):void 0)?.models.find(_=>_.id===S?.modelID),v=S?y(S.providerID,S.modelID):void 0,g=pi(N?.limit,"context")??v?.limit?.context??pi(f?.limit,"context")??0,x=m?Ho(m):null,A=m?.info?.usage,P=A?sd(A):x?.total??0,D=!a&&P>0&&g>0?Math.min(P/g*100,999):null,T=D!==null?`${Gn(P)}/${Gn(g)}`:null,M=D===null?"":D>=90?"text-[var(--status-error)]":D>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",E=x?.cacheRead??null,K=x?.cacheWrite??null,Z=x?nd({input:x.input,cache:{read:x.cacheRead,write:x.cacheWrite}}):{percent:0,hasInput:!1},ee=Z.hasInput?Z.percent:null,te=D!==null&&T?{percentage:D,tokens:T,colorClass:M,cacheRead:E,cacheWrite:K,cacheHitPercent:ee}: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(_=>!_),style:{touchAction:"manipulation"},children:t.jsx(ta,{percentage:te?.percentage??0})}),t.jsx(Ih,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:te})]})}),mi=600,Ph=1,Eh=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Th=({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(h=>`${h.directory}
12
+ ${h.sessionId}`,[]),f=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(h=>window.clearTimeout(h)),a.current.clear()},[]),y=o.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<Ph&&l.current.length>0;){const h=l.current.shift();if(!h)break;h.generation!==d.current||Oe.getState().currentSessionId===h.sessionId||rd(h.sessionId,h.directory).renderable}},[e,u,i,b]),p=o.useCallback(h=>{const m=h?.id,S=Eh(h);if(!e||u||!m||!S||m===s||typeof window>"u")return;const C={sessionId:m,directory:S,generation:d.current};b(C)},[s,e,u,y,b]);o.useEffect(()=>{f()},[f,s,e,u]),o.useEffect(()=>{if(!e||u||!s||n.length===0)return;const h=window.setTimeout(()=>{const m=n.findIndex(S=>S.id===s);m<0||(p(n[m-1]),p(n[m+1]))},mi);return()=>window.clearTimeout(h)},[s,e,u,p,n]),o.useEffect(()=>{if(!e||u||!s||r.length===0)return;const h=window.setTimeout(()=>{const m=r.findIndex(S=>S.id===s);m<0||(p(r[m-1]),p(r[m+1]))},mi);return()=>window.clearTimeout(h)},[s,e,u,r,p]),o.useEffect(()=>f,[f])},Rh=e=>{const s=Oe(n=>n.currentSessionId);return Th({...e,currentSessionId:s}),null},Mh=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(f=>{if(c.has(f.normalizedPath))return;const y=sa(f.normalizedPath),p=r.archivedSessionsByProject.get(f.id)??[],h=d[y]??[],m=new Map(h.map(S=>[S.name.toLowerCase(),S]));p.forEach(S=>{const C=od(S,f.normalizedPath),N=C.toLowerCase();let v=m.get(N);v||(v=u(y,C),m.set(N,v)),v.sessionIds.includes(S.id)||b(y,v.id,S.id)})})},[s,n,r,i,a,l,c,d,u,b])},Fh=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])}),Lh=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:l,buildGroupedSessions:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:b,buildGroupSearchText:f,foldersMap:y}=e,p=o.useRef(new Map),h=o.useMemo(()=>{const A=p.current,P=new Map;let D=0,T=0;const M=(K,Z)=>K.length===Z.length&&K.every((ee,te)=>ee===Z[te]),E=s.map(K=>{const Z=n(K.id),ee=r(K.id),te=i.has(K.id)?!!i.get(K.id):l,_=a.get(K.id)??null,H=A.get(K.id);if(H&&H.project===K&&M(H.activeSessions,Z)&&M(H.archivedSessions,ee)&&H.rootBranch===_&&H.isRepo===te&&H.buildGroupedSessions===c)return D+=1,P.set(K.id,H),H.section;T+=1;const B=na([...Z,...ee]),z=c(B,K.normalizedPath,[],_,te),Y={project:K,groups:z};return P.set(K.id,{project:K,activeSessions:Z,archivedSessions:ee,rootBranch:_,isRepo:te,buildGroupedSessions:c,section:Y}),Y});return p.current=P,D>0&&ss("ui.sidebar.project_section.reused",D),T>0&&ss("ui.sidebar.project_section.rebuilt",T),E},[s,n,r,i,l,c,a]),m=o.useMemo(()=>h,[h]),S=o.useMemo(()=>{const A=new WeakMap;if(!d)return A;const P=D=>D.reduce((T,M)=>T+1+P(M.children),0);return m.forEach(D=>{D.groups.forEach(T=>{const M=b(T.sessions,u),E=P(M),K=f(T).includes(u),Z=gt(T.directory??null),te=(Z?y[Z]??[]:[]).filter(_=>_.name.toLowerCase().includes(u)).length;A.set(T,{filteredNodes:M,matchedSessionCount:E,folderNameMatchCount:te,groupMatches:K,hasMatch:K||E>0||te>0})})}),A},[d,m,b,u,f,y]),C=o.useMemo(()=>d?m.map(A=>({...A,groups:A.groups.filter(P=>S.get(P)?.hasMatch===!0)})).filter(A=>A.groups.length>0):m,[d,m,S]),N=d?C:m,v=o.useRef(new WeakMap),g=o.useMemo(()=>{const A=v.current;return N.map(P=>{const D=A.get(P);if(D&&D.query===u)return D.section;const T=P.groups.filter(_=>!_.isArchivedBucket),M=P.groups.filter(_=>_.isArchivedBucket),E=T.flatMap(_=>d?S.get(_)?.filteredNodes??[]:_.sessions),K=T.map(_=>({scopeKey:_.folderScopeKey??gt(_.directory??null),directory:_.directory??null})).filter(_=>!!_.scopeKey),Z=T.find(_=>_.isMain)??null,ee={id:"flat",label:Z?.label??"",branch:Z?.branch??null,description:Z?.description??null,isMain:!0,isArchivedBucket:!1,directory:Z?.directory??P.project.normalizedPath,folderScopeKey:Z?.folderScopeKey??P.project.normalizedPath,folderScopes:K,sessions:E};if(d){const _=T.map(H=>S.get(H)).filter(H=>!!H);S.set(ee,{filteredNodes:E,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 te={project:P.project,groups:[ee,...M]};return A.set(P,{query:u,section:te}),te})},[S,d,u,N]),x=o.useMemo(()=>d?N.reduce((A,P)=>A+P.groups.reduce((D,T)=>{const M=S.get(T);if(!M)return D;const E=M.folderNameMatchCount+(M.groupMatches?1:0);return D+M.matchedSessionCount+E},0),0):0,[d,N,S]);return{projectSections:h,visibleProjectSections:m,groupSearchDataByGroup:S,searchableProjectSections:C,sectionsForRender:N,flatSectionsForRender:g,searchMatchCount:x}},Oh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:b,setSessionSwitcherOpen:f}=e,y=o.useMemo(()=>{const h=new Map,m=new Map,S=(C,N,v,g)=>{h.has(C)||h.set(C,new Map);const x=h.get(C);g.forEach(A=>{const P=gt(A.session.directory??v??N);x.set(A.session.id,{directory:P}),m.has(C)||m.set(C,{id:A.session.id,directory:P}),A.children.length>0&&S(C,N,P,A.children)})};return s.forEach(C=>{C.groups.forEach(N=>{S(C.project.id,C.project.normalizedPath,N.directory,N.sessions)})}),{metaByProject:h,firstSessionByProject:m}},[s]),p=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){p.current=n;return}if(p.current===n)return;const h=s.find(A=>A.project.id===n);if(!h)return;p.current=n;const m=y.metaByProject.get(n);if(a&&m&&m.has(a)){i(A=>{if(A.get(n)===a)return A;const P=new Map(A);return P.set(n,a),P});return}const S=a?Array.from(y.metaByProject.entries()).some(([A,P])=>A!==n&&P.has(a)):!1;if(a&&m&&!S)return;if(!m||m.size===0){b("chat"),d&&f(!1),u({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath});return}const C=r.get(n),N=C&&m.has(C)?C:null,v=y.firstSessionByProject.get(n)?.id??null,g=N??v;if(!g||g===a)return;const x=m.get(g)?.directory??null;l(g,x,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,y,b,f,i]),o.useEffect(()=>{if(!n||!a)return;const h=y.metaByProject.get(n);!h||!h.has(a)||i(m=>{if(m.get(n)===a)return m;const S=new Map(m);return S.set(n,a),S})},[n,a,y,i])},Bh=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Oe(c=>c.currentSessionId),i=Oe(c=>!!c.newSessionDraft?.open),[a,l]=o.useState(()=>new Map(e));return Oh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},Cn=e=>!!e.time?.archived,_h=e=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=gt(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=gt(l??null),f=na(a).sort((v,g)=>_n(v,g,e.pinnedSessionIds,e.sessionOrderRanks)),y=new Map(f.map(v=>[v.id,v])),p=new Map;f.forEach(v=>{const g=v.parentID;if(!g)return;const x=y.get(g);if(!x||Cn(x)!==Cn(v))return;const A=p.get(g)??[];A.push(v),p.set(g,A)}),p.forEach(v=>v.sort((g,x)=>_n(g,x,e.pinnedSessionIds,e.sessionOrderRanks)));const h=v=>{const g=p.get(v.id)??[];return{session:v,children:g.map(x=>h(x)),worktree:null}},m=f.filter(v=>{const g=v.parentID;if(!g)return!0;const x=y.get(g);return x?Cn(x)!==Cn(v):!0}),S=[],C=[];m.forEach(v=>{const g=h(v);v.time?.archived?C.push(g):S.push(g)});const N=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:b?id(b,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:b,folderScopeKey:b,sessions:S}];return C.length>0&&N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:b?sa(b):null,sessions:C}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},zh=({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])},$h=e=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((v,g,x)=>{Tr("navigation.session_select"),fe.getState().closeMainSurfaces();const A=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},P=x?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===Oe.getState().currentSessionId){e.allowReselect&&P&&e.onSessionSelected?.(v),A();return}Tr("navigation.session_state_set"),e.setCurrentSession(v,g??null),P&&e.onSessionSelected?.(v),A()},[e]),a=o.useCallback((v,g)=>{e.setEditingId(v),e.setEditTitle(g)},[e]),l=o.useCallback(async v=>{if(!e.editingId)return;const g=(v??e.editTitle).trim();g&&await e.updateSessionTitle(e.editingId,g),e.setEditingId(null),e.setEditTitle("")},[e]),c=o.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=o.useCallback(async(v,g)=>{try{return(await an(v)).ok?(n(g),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=o.useCallback(async v=>{const g=await e.shareSession(v.id);if(!g?.share?.url){ce.error("Unable to share session");return}const x=await d(g.share.url,v.id);ce[x?"success":"warning"]("Session shared",{description:x?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),b=o.useCallback((v,g)=>{d(v,g).then(x=>{x||ce.error("Failed to copy URL")})},[d]),f=o.useCallback(v=>{an(v).then(g=>{if(g.ok){ce.success("Session ID copied");return}ce.error("Failed to copy session ID")}).catch(()=>ce.error("Failed to copy session ID"))},[]),y=o.useCallback(async v=>{await e.unshareSession(v)?ce.success("Session unshared"):ce.error("Unable to unshare session")},[e]),p=o.useCallback(v=>{const g=[],x=A=>{(e.childrenMap.get(A)??[]).forEach(D=>{g.push(D),x(D.id)})};return x(v),g},[e.childrenMap]),h=o.useCallback((v,g)=>g?v:v.filter(x=>!x.time?.archived),[]),m=o.useCallback(async(v,g,x)=>{const A=g?.archivedBucket===!0||g?.hardDelete===!0,P=x?.descendantIds??h(p(v.id),A).map(E=>E.id);if(P.length===0){(A?await e.deleteSession(v.id):await e.archiveSession(v.id))?ce.success(A?"Session deleted":"Session archived"):ce.error(A?"Failed to delete session":"Failed to archive session");return}const D=[v.id,...P];if(A){const{deletedIds:E,failedIds:K}=await e.deleteSessions(D);if(K.length===0){const Z=E.length;ce.success(Z===1?`Deleted ${Z} session`:`Deleted ${Z} sessions`)}else ce.error("Failed to delete session");return}const{archivedIds:T,failedIds:M}=await e.archiveSessions(D);T.length>0&&ce.success(T.length===1?`Archived ${T.length} session`:`Archived ${T.length} sessions`),M.length>0&&ce.error(M.length===1?`Failed to archive ${M.length} session`:`Failed to archive ${M.length} sessions`)},[e,p,h]),S=o.useCallback((v,g)=>{const x=g?.archivedBucket===!0||g?.hardDelete===!0,A=h(p(v.id),x).map(P=>P.id);if(!e.showDeletionDialog||g?.skipConfirm===!0){m(v,g,{descendantIds:A});return}e.setDeleteSessionConfirm({session:v,descendantCount:A.length,descendantIds:A,archivedBucket:x})},[e,p,m,h]),C=o.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:g,descendantIds:x}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await m(v,{archivedBucket:g},{descendantIds:x})},[e,m]),N=o.useCallback(async v=>{await e.unarchiveSession(v.id)?ce.success("Session restored"):ce.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:i,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:b,handleCopySessionId:f,handleUnshareSession:y,handleDeleteSession:S,handleRestoreSession:N,confirmDeleteSession:C}},Uh=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 f=d.current;if(d.current=null,c.current=null,!f)return;const{projects:y}=Ot.getState(),p=y.map(h=>({...h,sidebarCollapsed:f.has(h.id)}));no({projects:p}).catch(()=>{})},[]),b=o.useCallback(f=>{typeof window>"u"||(d.current=f,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 f=s.getItem(n.sessionExpanded);if(f){const p=JSON.parse(f);Array.isArray(p)&&a(new Set(p.filter(h=>typeof h=="string")))}const y=s.getItem(n.projectCollapse);if(y){const p=JSON.parse(y);Array.isArray(p)&&l(new Set(p.filter(h=>typeof h=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const f=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(f))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:b}},Gh=5*6e4,Hh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=e,{git:l}=Wn(),c=ra(f=>f.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(f=>{ef(()=>c(f.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const f=new Map;s.forEach(y=>{f.set(y.id,r.get(y.normalizedPath)?.isGitRepo??null)}),i(f)},[n,s,r,i]);const d=o.useMemo(()=>s.map(f=>{const y=r.get(f.normalizedPath)?.branch??"";return`${f.id}:${y}`}).join("|"),[s,r]),u=o.useRef(new Map),b=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let f=!1;const y=setTimeout(()=>{(async()=>{const h=new Set(s.map(v=>v.id));for(const v of u.current.keys())h.has(v)||(u.current.delete(v),b.current.delete(v));const m=Date.now();if(s.filter(v=>{const g=r.get(v.normalizedPath);if(g?.isGitRepo===!1)return u.current.delete(v.id),b.current.delete(v.id),!1;if(g?.isGitRepo!==!0||g.branch===null)return!1;const x=g.branch.trim(),A=`${v.normalizedPath}\0${x}`,P=u.current.get(v.id);if(P===A){const D=b.current.get(v.id);return D&&(D.at=m),!1}return!(P!==void 0&&m-(b.current.get(v.id)?.at??0)<Gh)}).length===0)return;const C=[];if(s.forEach(v=>{const g=r.get(v.normalizedPath)?.branch?.trim()??"",x=`${v.normalizedPath}\0${g}`;g&&C.push({id:v.id,inputKey:x,branch:g})}),f||C.length===0)return;const N=Date.now();a(v=>{const g=new Map(v);return C.forEach(({id:x,branch:A})=>{A&&g.set(x,A)}),g}),C.forEach(({id:v,inputKey:g,branch:x})=>{u.current.set(v,g),x&&b.current.set(v,{branch:x,at:N})})})()},150);return()=>{f=!0,clearTimeout(y)}},[n,s,d,r,a])},Kh=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}},Wh=e=>{if(e.runtimeKey!==qn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=vu(e.sessionId,e.directory,e.runtimeKey);s&&wu.getState().clearQueue(s),ad.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),zt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),oa.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),Pr.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=ld(e.runtimeKey,e.directory,e.sessionId);n&&cd(n,!0)},Yh=e=>{const s=new Map;for(const n of e){const r=zs(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Vh=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,i)=>{s.has(i)||n.push(r)}),n},qh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=qn(),l=Yh(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of Vh(c,l))Wh({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},Qh=(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,gi=(e,s,n)=>{Qh(e.get(s),n)&&e.set(s,n)},Jh=e=>{const s=e;return gt(s.directory)??gt(s.project?.worktree)},Xh=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)},Zh=(e,s,n,r=[])=>{const i=new Map,a=new Map;for(const p of s){const h=gt(p.normalizedPath);if(!h)continue;const m=a.get(h);(!m||p.id.localeCompare(m.id)<0)&&a.set(h,p),gi(i,h,{projectId:p.id,projectRoot:h,scopeDirectory:h,kind:"project"})}if(n)for(const[p,h]of n){const m=gt(p),S=m?a.get(m):void 0;if(!(!S||!m))for(const C of h||[]){const N=gt(C?.path);N&&gi(i,N,{projectId:S.id,projectRoot:m,scopeDirectory:N,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,b=new Map,f=p=>{if(!p)return null;if(l.has(p))return l.get(p)??null;const h=[];let m=p,S=null;for(;m;){if(l.has(m)){S=l.get(m)??null;break}if(h.push(m),S=i.get(m)??null,S)break;m=Xh(m)}for(const C of h)l.set(C,S);return S},y=(p,h,m)=>{for(const S of p){const C=f(Jh(S));if(!C)continue;c.set(S.id,C);const N=h.get(C.projectId);if(N?N.push(S):h.set(C.projectId,[S]),!m)continue;const v=m.get(C.scopeDirectory);v?v.add(S.id):m.set(C.scopeDirectory,new Set([S.id]))}};return y(e,d,b),y(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:b,directoryResolutions:l.size}},ep=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(f=>{const y=new Set(f);let p=!1;for(const h of b){const m=h.target.dataset.projectId;if(!m)continue;const S=h.rootBounds?.top??d.getBoundingClientRect().top,C=!h.isIntersecting&&h.boundingClientRect.top<S;y.has(m)!==C&&(p=!0,C?y.add(m):y.delete(m))}return p?y:f})},{root:d,threshold:0});return i.current.forEach(b=>{b&&u.observe(b)}),()=>u.disconnect()},[s,n,i,r]),a},tp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(is,{open:e,onOpenChange:s,children:t.jsx(as,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(Cs,{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(Xf,{project:n,onIdentitySave:r}):null})})})});function Wa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:O("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:O("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Yn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const sp=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:b,groupDirectory:f,projectId:y,mobileVariant:p=!1,alwaysShowActions:h=p,isRenaming:m=!1,renameDraft:S="",onRenameDraftChange:C,onRenameSave:N,onRenameCancel:v,droppableRef:g,isDropTarget:x=!1,onNewSession:A,depth:P=0,hideActions:D=!1,archivedBucket:T=!1})=>{const[M,E]=o.useState(!1),[K,Z]=o.useState(""),ee=o.useRef(null),te=m||M,_=m?S:K,H=o.useCallback(()=>{Z(e.name),E(!0)},[e.name]),B=o.useCallback(()=>{const G=_.trim();G&&G!==e.name&&c(G),m&&N&&N(),E(!1),Z("")},[_,e.name,m,c,N]),z=o.useCallback(()=>{m&&v&&v(),E(!1),Z("")},[m,v]),Y=o.useCallback(G=>{m&&C?C(G):Z(G)},[m,C]);o.useEffect(()=>{if(!m)return;const G=()=>{const He=ee.current;He&&(He.focus(),He.select())},Te=requestAnimationFrame(G),Re=window.setTimeout(G,0);return()=>{cancelAnimationFrame(Te),window.clearTimeout(Re)}},[m]);const re=i?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:g,className:O("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",x&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:te?void 0:G=>{G.currentTarget.blur(),l()},role:te?void 0:"button",tabIndex:te?void 0:0,onKeyDown:te?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:O("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",T?h?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":h?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(k,{name:re,className:O(Tn,x?"text-primary":"text-muted-foreground")}),te?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:ee,value:_,onChange:G=>Y(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(),z();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(),z()},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(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:O(ia,x?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(st,{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(Wa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?t.jsx(k,{name:"arrow-right-s",className:O(Tn,"text-muted-foreground")}):t.jsx(k,{name:"arrow-down-s",className:O(Tn,"text-muted-foreground")})]})]}),!te&&(!D||T)?t.jsx("div",{className:O("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",h?"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:[!T&&A?t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),A()},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,T?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":T?`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,f??null,y??null,T,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"})]})]})},np=o.memo(sp),rp=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Hu({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})},op=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Ku({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},ip=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=Qn(un(lo,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,b]=o.useState(null),[f,y]=o.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const p=h=>{l(null),b(null),y(null);const{active:m,over:S}=h;if(!S)return;const C=m.data.current,N=S.data.current;C?.type==="session"&&C.sessionId&&N?.type==="folder"&&N.folderId&&n(C.sessionId,N.folderId)};return t.jsxs(Jn,{sensors:i,collisionDetection:Xn,onDragStart:h=>{const m=h.active.data.current;if(m?.type==="session"&&m.sessionId){l(m.sessionId),d(m.sessionTitle??"Session");const S=h.active.rect.current.initial?.width,C=h.active.rect.current.initial?.height;b(typeof S=="number"?S:null),y(typeof C=="number"?C:null)}},onDragCancel:()=>{l(null),b(null),y(null)},onDragEnd:p,children:[r,t.jsx(ka,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:f?`${f}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})]})},Fn=(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},Ns=({icon:e,children:s,onClick:n,className:r,mobileVariant:i=!1})=>t.jsxs("button",{type:"button",onClick:n,className:O(i?dd:ud,r),children:[t.jsx(k,{name:e,className:O(ln(i),"text-muted-foreground")}),t.jsx("span",{className:O(cn(i),"flex-1 text-muted-foreground"),children:s})]}),xi=(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)},us=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(us(n,s))return!0;return!1},ap=(e,s,n)=>{const r=new Map,i=a=>{const l=zs(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}))},lp=(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})},bi=new WeakMap;let yi=1;const cp=e=>{const s=bi.get(e);if(s!==void 0)return s;const n=yi;return yi+=1,bi.set(e,n),n},Yr=e=>e.children.length===0?"":e.children.map(n=>{const r=cp(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Yr(n)}`}).join("|"),Ya=(e,s,n,r,i,a)=>{const l=qn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const b=d.session.directory??i,f=u.session.directory??a,y=Ko(l,b??"",d.session.id),p=Ko(l,f??"",u.session.id);return(y?n.has(y):!1)!==(p?r.has(p):!1)?!0:d.children.some((h,m)=>c(h,u.children[m]))};return c(e,s)},Hn=(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},Va=(e,s)=>"",dp=ps(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),up=e=>null,po=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,qa=(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=po(i,qa(l,s,n,r)),i==="active")return i;return i},vi=(e,s,n,r)=>{let i=null;for(const a of e)if(i=po(i,qa(a,s,n,r)),i==="active")return i;return i},fp=50,hp=28,kn=(e,s)=>s?e.sessions.some(n=>us(n,s)):!1,pp=(e,s,n)=>e.sessions.some(r=>Ya(r,r,s,n,e.directory,e.directory)),mp=(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)},wi=(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)},gp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},xp=(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)},bp=(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&&pp(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&xp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&mp(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(kn(e.group,e.editingId)||kn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(kn(e.group,e.editingId)||kn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Hn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Hn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&wi(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&wi(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&gp(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 yp(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:b,collapsedFolderIds:f,toggleFolderCollapse:y,renameFolder:p,deleteFolder:h,showDeletionDialog:m,setDeleteFolderConfirm:S,renderSessionNode:C,showMoreGroupSessions:N,resetGroupSessionLimit:v,mobileVariant:g,alwaysShowActions:x,activeProjectId:A,setActiveProjectIdOnly:P,setActiveMainTab:D,setSessionSwitcherOpen:T,openNewSessionDraft:M,addSessionToFolder:E,createFolderAndStartRename:K,renamingFolderId:Z,renameFolderDraft:ee,setRenameFolderDraft:te,setRenamingFolderId:_,pinnedSessionIds:H,expandedParents:B,sessionOrderIndex:z,editingId:Y,openSidebarMenuKey:re,activeActivitySessionIds:G,unreadActivitySessionIds:Te,notifyOnSubtasks:Re,onToggleCollapsedGroup:He,dragHandleProps:Ke,compactBodyPadding:Ue=!1,scrollContainerRef:Ae}=e,X=o.useCallback((U,ne)=>{const le=z.get(U.session.id),ue=z.get(ne.session.id);if(le!==void 0||ue!==void 0){if(le===void 0)return 1;if(ue===void 0)return-1;if(le!==ue)return le-ue}return _n(U.session,ne.session,H,aa)},[H,z]),xe=a?c.get(s):null,We=zt(U=>U.foldersMap),Ce=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const U=gt(s.directory??null),ne=s.branch?.trim();return U&&ne?Va():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const je=la(),$e=o.useMemo(()=>{const U=s.folderScopes?.map(ne=>gt(ne.directory))??[gt(s.directory??null)];return[...new Set(U.filter(ne=>!!ne))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(U=>$e.length>0?je.subscribeBootstrap(U):()=>{},[$e.length,je]),o.useCallback(()=>$e.map(U=>`${U}\0${je.getBootstrapState(U)??""}\0${je.getBootstrapFailure(U)??""}`).join(""),[$e,je]),o.useCallback(()=>"",[]));const nt=$e.some(U=>{const ne=je.getBootstrapState(U);return ne==="queued"||ne==="running"}),_e=$e.find(U=>je.getBootstrapState(U)==="failed")??null,q=_e?je.getBootstrapFailure(_e):void 0,V=q==="os-permission"&&oo(),[be,Q]=o.useState(!1),ve=o.useCallback(()=>{_e&&je.requestBootstrap({directory:_e,priority:Ce?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[je,_e,s.isMain,Ce]),pe=o.useCallback(async()=>{if(!(!_e||!V||be)){Q(!0);try{(await io(_e)).success&&ve()}finally{Q(!1)}}},[V,_e,be,ve]),De=b?10:5,at=Math.max(De,d??De),ht=a?xe?.groupMatches===!0:!1,Ve=a,Me=o.useMemo(()=>[...Ve?xe?.filteredNodes??[]:s.sessions].sort(X),[X,s.sessions,xe?.filteredNodes,Ve]),ke=s.folderScopeKey??gt(s.directory??null),Le=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:ke?[{scopeKey:ke,directory:s.directory??null}]:[],[ke,s.directory,s.folderScopes]),dt=o.useMemo(()=>Le.flatMap(({scopeKey:U,directory:ne})=>(We[U]??[]).map(le=>({folder:le,scopeKey:U,scopeDirectory:ne}))),[Le,We]),bt=o.useMemo(()=>{const U=new Map,ne=le=>{le.forEach(ue=>{U.set(ue.session.id,ue),ue.children.length>0&&ne(ue.children)})};return ne(Me),U},[Me]),rt=o.useMemo(()=>dt.map(({folder:U,scopeKey:ne,scopeDirectory:le})=>{const ue=lp(U.sessionIds,bt).sort(X);return{folder:U,scopeKey:ne,scopeDirectory:le,nodes:ue}}),[dt,bt,X]),$=o.useMemo(()=>{const U=new Map(rt.map(ge=>[ge.folder.id,ge])),ne=new Map;for(const{folder:ge}of rt){if(!ge.parentId)continue;const it=ne.get(ge.parentId);it?it.push(ge.id):ne.set(ge.parentId,[ge.id])}const le=new Map,ue=ge=>{const it=le.get(ge);if(it!==void 0)return it;const Dt=U.get(ge);if(!Dt)return le.set(ge,!1),!1;const yt=ne.get(ge)??[];if(s.isArchivedBucket&&Dt.nodes.length===0){const Pt=yt.some(ns=>ue(ns));return le.set(ge,Pt),Pt}if(!a||Dt.folder.name.toLowerCase().includes(l)||Dt.nodes.length>0)return le.set(ge,!0),!0;const Xt=yt.some(Pt=>ue(Pt));return le.set(ge,Xt),Xt};return rt.filter(({folder:ge})=>ue(ge.id))},[rt,s.isArchivedBucket,a,l]),me=o.useMemo(()=>new Set($.flatMap(U=>U.folder.sessionIds)),[$]),Ne=o.useMemo(()=>Me.filter(U=>!me.has(U.session.id)),[Me,me]),w=o.useMemo(()=>$.filter(({folder:U})=>!U.parentId),[$]),W=o.useMemo(()=>{const U=new Map;return $.forEach(ne=>{if(!ne.folder.parentId)return;const le=U.get(ne.folder.parentId)??[];le.push(ne),U.set(ne.folder.parentId,le)}),U},[$]),se=o.useMemo(()=>{const U=new Map($.map(ue=>[ue.folder.id,ue])),ne=new Map,le=(ue,ge)=>{const it=ne.get(ue);if(it!==void 0)return it;if(ge.has(ue))return null;ge.add(ue);const Dt=U.get(ue);let yt=Dt?vi(Dt.nodes,G,Te,Re):null;for(const Ht of W.get(ue)??[])if(yt=po(yt,le(Ht.folder.id,ge)),yt==="active")break;return ne.set(ue,yt),yt};return $.forEach(({folder:ue})=>le(ue.id,new Set)),ne},[G,$,W,Re,Te]),de="project",we=o.useMemo(()=>{const U=new Set;return xi(Me,Y,U),$.forEach(({nodes:ne})=>{xi(ne,Y,U)}),U},[Me,$,Y]),Ie=o.useMemo(()=>{if(!re)return null;const U=Hn(Me,re,de,!!s.isArchivedBucket);if(U)return U;for(const{nodes:ne}of $){const le=Hn(ne,re,de,!!s.isArchivedBucket);if(le)return le}return null},[re,Me,$,s.isArchivedBucket]),ze=o.useCallback(U=>{const ne=new WeakMap,le=ue=>{ne.set(ue,Yr(ue));for(const ge of ue.children)le(ge)};return U.forEach(le),ne},[]),lt=o.useMemo(()=>ze(Me),[ze,Me]),St=o.useMemo(()=>{const U=new WeakMap;return $.forEach(({nodes:ne})=>{ne.forEach(le=>U.set(le,Yr(le)))}),U},[$]),Je=o.useCallback(U=>lt.get(U)??St.get(U)??"",[lt,St]),ct=o.useCallback(U=>({subtreeContainsEditing:we,menuOpenSessionId:Ie,nodeStructureKey:Je(U)}),[we,Ie,Je]),pt=Ne.length,Fe=s.isArchivedBucket||a?Ne:Ne.slice(0,at),Ge=pt-Fe.length,mt=!s.isArchivedBucket&&!a&&pt>De&&Ge===0,Tt=s.isArchivedBucket===!0&&!a&&Fe.length>=fp,Bt=s.isArchivedBucket?"archived":"active",vt=Tt&&Fe.some(U=>{if(U.children.length===0)return!1;const ne=`project:${Bt}:${U.session.id}`;return B.has(ne)}),jt=o.useRef(null),[kt,F]=o.useState(null),[Se,Be]=o.useState(0),[,ot]=o.useState(0);o.useEffect(()=>{if(!Tt)return;const U=jt.current;if(!U||typeof ResizeObserver>"u")return;const ne=new ResizeObserver(()=>ot(le=>le+1));return ne.observe(U),()=>ne.disconnect()},[Tt]),o.useLayoutEffect(()=>{if(!Tt){kt!==null&&F(null),Se!==0&&Be(0);return}const U=jt.current;if(!U)return;let ne=kt;const le=Ae?.current??null;if(le&&le.contains(U)){if(ne=le,ne!==kt){F(ne);return}}else if(!ne||!ne.contains(U)){let ge=U.parentElement;for(;ge;){const it=window.getComputedStyle(ge);if(it.overflowY==="auto"||it.overflowY==="scroll"){ne=ge;break}ge=ge.parentElement}if(ne!==kt){F(ne);return}}if(!ne)return;const ue=U.getBoundingClientRect().top-ne.getBoundingClientRect().top+ne.scrollTop;Be(ge=>Math.abs(ge-ue)<1?ge:ue)});const L=Tt&&kt!==null,oe=Gu({count:Fe.length,enabled:L,getScrollElement:()=>kt,initialOffset:()=>kt?.scrollTop??0,estimateSize:()=>hp,overscan:vt?20:8,scrollMargin:Se,getItemKey:U=>Fe[U]?.session.id??U}),he=o.useCallback(U=>{const ne=[],le=ue=>{ue.forEach(ge=>{ne.push(ge.session),ge.children.length>0&&le(ge.children)})};return le(U),ne},[]),Xe=o.useMemo(()=>he(Me),[he,Me]),ye=o.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const U=new Map,ne=new Map;for(const{folder:ue}of $){if(!ue.parentId)continue;const ge=ne.get(ue.parentId)??[];ge.push(ue.id),ne.set(ue.parentId,ge)}const le=(ue,ge)=>{if(ge.has(ue))return[];ge.add(ue);const it=$.find(({folder:Ht})=>Ht.id===ue),Dt=it?he(it.nodes):[],yt=ne.get(ue)??[];for(const Ht of yt)Dt.push(...le(Ht,ge));return Dt};for(const{folder:ue}of $)U.set(ue.id,le(ue.id,new Set));return U},[$,he,s.isArchivedBucket]);if(a&&!ht&&w.length===0&&Ne.length===0)return null;const Qe=!s.isMain&&!!s.branch,ut=s.branch&&fd(s.branch,s.label)?{label:s.branch}:null,At=Ce?vi(Me,G,Te,Re):null,Rt=At?t.jsx(Wa,{state:At,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,It=(U,ne)=>{const{folder:le,scopeKey:ue,scopeDirectory:ge,nodes:it}=U,Dt=ye.get(le.id)??[],yt=a?!1:f.has(le.id);return t.jsx(op,{folderId:le.id,children:(Ht,Xt)=>t.jsx(np,{folder:le,displayName:ne,sessions:it,isCollapsed:yt,collapsedActivityState:yt?se.get(le.id)??null:null,onToggle:()=>y(le.id),onRename:Pt=>{p(ue,le.id,Pt)},onDelete:()=>{if(s.isArchivedBucket){Is.requestDelete({sessions:Dt,mode:"session"});return}if(!m){h(ue,le.id);return}const Pt=$.filter(({folder:ls})=>ls.parentId===le.id).length,ns=it.length;S({scopeKey:ue,folderId:le.id,folderName:le.name,subFolderCount:Pt,sessionCount:ns})},renderSessionNode:C,getRenderExtras:Je?Pt=>({subtreeContainsEditing:we,menuOpenSessionId:Ie,nodeStructureKey:Je(Pt),childRenderExtrasFor:ct}):void 0,groupDirectory:ge??s.directory,projectId:r,mobileVariant:g,alwaysShowActions:x,isRenaming:Z===le.id,renameDraft:Z===le.id?ee:void 0,onRenameDraftChange:Pt=>te(Pt),onRenameSave:()=>{const Pt=ee.trim();Pt&&p(ue,le.id,Pt),_(null),te("")},onRenameCancel:()=>{_(null),te("")},droppableRef:Ht,isDropTarget:Xt,depth:0,onNewSession:()=>{r&&r!==A&&P(r),D("chat"),g&&T(!1),M({selectedProjectId:r,directoryOverride:ge??s.directory,targetFolderId:le.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},le.id)},Gt=()=>{const U=new Map;for(const ue of $){const ge=ue.folder.parentId;if(!ge)continue;const it=U.get(ge);it?it.push(ue):U.set(ge,[ue])}const ne=[],le=(ue,ge)=>{const it=ge?`${ge} / ${ue.folder.name}`:ue.folder.name;ne.push(It(ue,it)),!(!a&&f.has(ue.folder.id))&&(U.get(ue.folder.id)??[]).forEach(yt=>le(yt,it))};return w.forEach(ue=>le(ue,"")),ne},_t=x?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",Ct=_e?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:be,onClick:()=>{pe()},children:"Grant access"}):null,t.jsx(qe,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:ve,children:"Try again"})]}):null,Ft=t.jsxs(ip,{scopeKey:Le[0]?.scopeKey??ke,hasFolders:$.length>0,onSessionDroppedOnFolder:(U,ne)=>{const le=$.find(({folder:ge})=>ge.id===ne);if(!le)return;const ue=zt.getState();for(const{scopeKey:ge}of Le)ge!==le.scopeKey&&ue.getSessionFolderId(ge,U)&&ue.removeSessionFromFolder(ge,U);E(le.scopeKey,ne,U)},children:[Gt(),Tt?t.jsx("div",{ref:jt,children:L?t.jsx("div",{style:{height:oe.getTotalSize(),position:"relative"},children:oe.getVirtualItems().map(U=>{const ne=Fe[U.index];return ne?t.jsx("div",{"data-index":U.index,ref:oe.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${U.start-Se}px)`},children:C(ne,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:we,menuOpenSessionId:Ie,nodeStructureKey:Je(ne),childRenderExtrasFor:ct})},ne.session.id):null})}):Fe.map(U=>t.jsx(o.Fragment,{children:C(U,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:we,menuOpenSessionId:Ie,nodeStructureKey:Je(U),childRenderExtrasFor:ct})},U.session.id))}):Fe.map(U=>t.jsx(o.Fragment,{children:C(U,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:we,menuOpenSessionId:Ie,nodeStructureKey:Je(U),childRenderExtrasFor:ct})},U.session.id)),pt===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."}):nt?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…"]})}):Ct?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:Ct}):t.jsx(Ns,{icon:"chat-new",onClick:()=>{M({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,pt>0&&Ct?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:Ct}):null,Ge>0?t.jsx(Ns,{icon:"arrow-down-s",onClick:()=>N(n,Fe.length),children:Ge===1?"Show 1 more session":`Show ${Ge} more sessions`}):null,mt?t.jsx(Ns,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return i?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Ft})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:O("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":Ce?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!Ce,children:[t.jsx("div",{ref:Ke?.setActivatorNodeRef,className:O("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",_t),...Ke?.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:O("size-4 shrink-0 text-muted-foreground",x?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:O("text-muted-foreground size-4 items-center justify-center",x?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ce?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:Fn(s.label,l)}),Rt]}):!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:O("size-4 shrink-0","text-muted-foreground",x?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:O("text-muted-foreground size-4 items-center justify-center",x?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ce?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:Fn(s.label,l)}),Rt,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:Fn(s.label,l)}),Rt]})}),Qe&&ut?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:ut.label})]}):null]})}),s.isArchivedBucket&&Xe.length>0?t.jsx("div",{className:O("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",x?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),Is.requestDelete({sessions:Xe,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(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?t.jsx("div",{className:O("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",x?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),r&&r!==A&&P(r),D("chat"),g&&T(!1),M({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(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]}),Ce?null:t.jsx("div",{className:"oc-group-body",children:Ft})]})}const vp=o.memo(yp,bp);function wp(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:b,setIsSessionSearchOpen:f,sessionSearchInputRef:y,sessionSearchQuery:p,setSessionSearchQuery:h,hasSessionSearchQuery:m,searchMatchCount:S,selectionModeEnabled:C,onToggleSelectionMode:N,mobileVariant:v=!1}=e;if(s)return null;const g=O(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return t.jsx("div",{className:O("select-none flex-shrink-0",v?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:O("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:O("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:O("flex min-w-0 items-center",v?"gap-0.5 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[i?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:g,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!v&&a?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:g,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(k,{name:"server",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:g,"aria-label":"Update",children:t.jsx(k,{name:"download",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,v?null:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:g,"aria-label":"Add project",children:t.jsx(k,{name:"folder-add",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),v?null:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:g,"aria-label":"Archive",children:t.jsx(k,{name:"archive",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:O("flex shrink-0 items-center",v?"gap-0.5":"gap-1.5"),children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>f(x=>!x),className:g,"aria-label":"Search sessions","aria-expanded":b,children:t.jsx(k,{name:"search",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:N,className:O(g,C&&"bg-interactive-hover text-primary"),"aria-label":C?"Exit selection":"Select sessions","aria-pressed":C,children:t.jsx(k,{name:"checkbox-multiple",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:C?"Exit selection":"Select sessions"})})]})]})]}),b?t.jsxs("div",{className:O(v?"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:m?t.jsx("span",{children:S===1?`${S} match`:`${S} 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:y,value:p,onChange:x=>h(x.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:x=>{x.key==="Escape"&&(x.stopPropagation(),m?h(""):f(!1))}}),p.length>0?t.jsx("button",{type:"button",onClick:()=>h(""),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 Sp(e){const s=fe(i=>i.toggleSidebar),n=fe(i=>i.shortcutOverrides),r=to(sn("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, ${Wo})`}}),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, ${Wo})))`}}),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:O("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:O(Tn,"text-current")}),t.jsx("span",{className:ia,children:"New session"})]}),e.showSidebarToggle?t.jsxs(et,{children:[t.jsx(tt,{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(st,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const jp=500,Vr=(e,s)=>O("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"),Cp=({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:f,transition:y,isDragging:p}=Zn({id:e.id,disabled:!i}),[h,m]=o.useState(!1),S=o.useRef(null),C=o.useCallback(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]);o.useEffect(()=>()=>C(),[C]);const N=o.useCallback(()=>{C(),S.current=window.setTimeout(()=>{S.current=null,m(!0)},jp)},[C]);return t.jsx("div",{ref:b,style:{transform:er.Translate.toString(f),transition:y},className:O(p&&"opacity-60"),children:t.jsxs(Zf,{open:h,onOpenChange:m,children:[t.jsxs(eh,{render:t.jsx("button",{type:"button",onClick:()=>{h||a()},onTouchStart:N,onTouchMove:C,onTouchEnd:C,onTouchCancel:C,style:{touchAction:"manipulation"},className:Vr(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:O("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:O(ln(d),"text-muted-foreground")})}),t.jsx("span",{className:cn(d),children:s})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(Yn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsxs(th,{className:"min-w-[160px]",children:[t.jsxs(ci,{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(sh,{}),t.jsxs(ci,{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"})]})]})]})})},kp=({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,f=Ot(m=>m.reorderProjects),y=e.length>1,p=Qn(un(Yu,{activationConstraint:{distance:8}}),un(Wu,{activationConstraint:{delay:200,tolerance:6}})),h=o.useCallback(m=>{const{active:S,over:C}=m;if(!C||S.id===C.id)return;const N=Ot.getState().projects,v=N.findIndex(x=>x.id===S.id),g=N.findIndex(x=>x.id===C.id);v<0||g<0||f(v,g)},[f]);return t.jsxs("div",{className:O("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:Vr(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:ln(u)}),t.jsx("span",{className:cn(u),children:"All Folders"})]})}),t.jsx(Jn,{sensors:p,collisionDetection:Xn,onDragEnd:h,children:t.jsx(co,{items:e.map(m=>m.id),strategy:Na,children:e.map(m=>{const S=s===m.id,C=Vn(m.label?.trim()||As(m.normalizedPath,c)||m.normalizedPath);return t.jsx(Cp,{project:m,label:C,isSelected:S,hasActive:l?.(m.id),canDrag:y,onSelect:()=>n(S?null:m.id),onOpenProjectEditDialog:i,onRemoveProject:a,mobileVariant:u},m.id)})})}),t.jsxs("button",{type:"button",onClick:r,className:Vr(u,!1),children:[t.jsx(k,{name:"add",className:ln(u)}),t.jsx("span",{className:cn(u),children:"Add folder"})]})]})},fr="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 Np({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(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:fr,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:fr,"aria-label":"Shortcuts",children:t.jsx(k,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:fr,"aria-label":"About PiChamber",children:t.jsx(k,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(st,{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 Ap=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Si=ps()(ao(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:Ap})),Ip=({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=ln(r),c=cn(r);return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:O("inline-flex shrink-0 items-center justify-center",l),children:[i?t.jsx("span",{className:O("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:O(l,"text-muted-foreground/80",a)})]}),t.jsx("span",{className:O(c,"text-foreground"),children:e})]})},Dp=({id:e,disabled:s=!1,children:n})=>{const{listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Zn({id:e,disabled:s}),u=o.useMemo(()=>({listeners:r,setActivatorNodeRef:a}),[r,a]);return t.jsx("div",{ref:i,style:{transform:er.Transform.toString(l),transition:c},className:O("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};o.memo(Dp);const Pp=48,Ep=32,Tp=24,ji=(e,s)=>Vn(e.label?.trim()||As(e.normalizedPath,s)||e.normalizedPath);function Rp(e){ss("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=(N,v)=>{const g=n.current,x=g.get(N);if(x&&x.groups===v)return x.ordered;const A=e.getOrderedGroups(N,v);if(g.set(N,{groups:v,ordered:A}),g.size>256){const P=g.keys().next().value;P!==void 0&&g.delete(P)}return A},a=o.useRef(null),l=o.useRef(0),c=o.useCallback(N=>{const g=N.scrollTop>1?Math.min(Ep+N.scrollTop,Pp):0;l.current=g,N.style.setProperty("--scroll-shadow-top-size",`${g}px`),N.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(g-8,0),Tp)}px`)},[]),d=o.useCallback(N=>{N.target.closest("[data-overlay-scrollbar-thumb], [data-sidebar-sticky-header]")||N.clientY-N.currentTarget.getBoundingClientRect().top>=l.current||(N.preventDefault(),N.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 N of e.projectSections)e.stuckProjectHeaders.has(N.project.id)&&(b=N.project);const f=b??(e.hasSharedSessions?null:e.sectionsForRender[0]?.project??null),y=f?ji(f,e.homeDirectory):null,p=o.useMemo(()=>{if(!e.isAllFoldersView)return[];const N=[];for(const v of e.sectionsForRender){const g=ji(v.project,e.homeDirectory);for(const x of v.groups)if(!x.isArchivedBucket)for(const A of x.sessions){const P=!!e.pinnedSessionIds?.has(A.session.id),D=A.session.time?.updated||A.session.time?.created||0;N.push({node:A,project:v.project,projectLabel:g,isPinned:P,timestamp:D})}}return N.sort((v,g)=>v.isPinned!==g.isPinned?v.isPinned?-1:1:g.timestamp-v.timestamp),N},[e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[h,m]=o.useState(30);o.useEffect(()=>{m(30)},[e.hasSessionSearchQuery]);const S=p.slice(0,h),C=p.length-S.length;return e.sharedSessionsOnly?t.jsx(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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(Cs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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(Cs,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!s,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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?N=>c(N.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 N=e.sectionsForRender.find(A=>A.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!N)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const v=N.groups.find(A=>A.isMain&&A.sessions.length>0)??N.groups.find(A=>A.sessions.length>0)??N.groups.find(A=>A.isMain)??N.groups[0];if(!v)return t.jsx(Ns,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:N.project.id,directoryOverride:N.project.normalizedPath}),children:"New session"});const g=N.groups.find(A=>A.isArchivedBucket);return[v,...g&&g.id!==v.id?[g]:[]].map(A=>{const P=`${N.project.id}:${A.id}`,D=A.id===v.id;return t.jsx(o.Fragment,{children:e.renderGroupSessions(A,P,N.project.id,D,null,!0,a)},P)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:p.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[S.map(({node:N,project:v,projectLabel:g})=>{const x=N.session.directory??v.normalizedPath;return t.jsx(o.Fragment,{children:e.renderSessionNode(N,0,x,v.id,!1,{projectLabel:g,showFolderLabel:!0},"project")},N.session.id)}),C>0?t.jsx(Ns,{icon:"arrow-down-s",onClick:()=>m(N=>N+30),children:C===1?"Show 1 more session":`Show ${C} more sessions`}):null,h>30&&p.length>30?t.jsx(Ns,{icon:"arrow-up-s",onClick:()=>m(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(N=>{const v=N.project.id,g=i(v,N.groups),x=g.find(P=>P.isMain)??null,A=x?g.filter(P=>P.id!==x.id):g;return t.jsxs("div",{children:[x?e.renderGroupSessions(x,`${v}:${x.id}`,v,!0,null,void 0,a):null,A.map(P=>{const D=`${v}:${P.id}`;return t.jsx(o.Fragment,{children:e.renderGroupSessions(P,D,v,!1,null,void 0,a)},P.id)})]},v)})})]})}),s&&f&&y?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(Ip,{id:f.id,projectLabel:y,mobileVariant:e.mobileVariant})}):null]})}const Mp=o.memo(Rp);function Fp(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 Lp(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 Op(e){const s=e.info.role==="user"?"User":"Assistant",n=Fp(e.info.time?.created),r=Lp(e),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
13
+
14
+ *${i}*`:`**${s}**`}function Bp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Qa(e){const s=Op(e),n=Bp(e.parts).trim();return n?`${s}
15
+
16
+ ${n}`:""}function Ja(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(Qa).filter(Boolean).join(`
21
+
22
+ ---
23
+
24
+ `),l=[i+a];for(const c of e.children)l.push(Ja(c,s+1));return l.join(`
25
+
26
+ ---
27
+
28
+ `)}function Xa(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(Qa).filter(Boolean).join(`
35
+
36
+ ---
37
+
38
+ `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Ja(u,1)).join(`
39
+
40
+ ---
41
+
42
+ `);c+=`
43
+
44
+ ---
45
+
46
+ `+d}return c}function Za(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 el(e,s){const n=await Su(s,e);return n||null}async function _p(e){const s=ro()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await ju(e)?!0:ga(e)}function zp(){return hd()}function tl(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 $p=(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},$t=ps()((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 y of b)l.delete(y);d===n&&(d=null)}else{for(const y of b)l.add(y);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[f,y]=u<=b?[u,b]:[b,u],p=i.slice(f,y+1),h=$p(p,l),S=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const C of h)S.add(C);e({selectedIds:S,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 qr=!1;const Qr=new Set;let Ci=!1;function Up(){for(const e of Qr)e()}function mo(e){qr!==e&&(qr=e,Up())}function Gp(e){e.key==="Shift"&&mo(!0)}function Hp(e){e.key==="Shift"&&mo(!1)}function Kp(){mo(!1)}function Wp(){Ci||typeof window>"u"||(Ci=!0,window.addEventListener("keydown",Gp),window.addEventListener("keyup",Hp),window.addEventListener("blur",Kp))}function Yp(e){return Wp(),Qr.add(e),()=>{Qr.delete(e)}}function Vp(){return qr}function qp(){return!1}function Qp(){return Ye.useSyncExternalStore(Yp,Vp,qp)}const hr=new WeakMap,Jp=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;hr.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,hr.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,ss("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}),hr.set(n,c),l=window.requestAnimationFrame(d)},Xp=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Qp(),b=u?n:s,f=y=>{if(u||y.shiftKey){d(y);return}c(y)};return t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",className:O("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:f,onKeyDown:y=>y.stopPropagation(),children:t.jsx(k,{name:u?"delete-bin":"archive",className:i})})}),t.jsx(st,{side:"left",sideOffset:8,children:b})]})});function Zp(e){ss("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:f,setEditingId:y,editTitle:p,setEditTitle:h,handleSaveEdit:m,handleCancelEdit:S,toggleParent:C,handleSessionSelect:N,handleSessionDoubleClick:v,togglePinnedSession:g,handleShareSession:x,copiedSessionId:A,handleCopyShareUrl:P,handleCopySessionId:D,handleUnshareSession:T,openSidebarMenuKey:M,setOpenSidebarMenuKey:E,renamingFolderId:K,getFoldersForScope:Z,getSessionFolderId:ee,removeSessionFromFolder:te,addSessionToFolder:_,createFolderAndStartRename:H,openContextPanelTab:B,handleDeleteSession:z,handleRestoreSession:Y,mobileVariant:re,alwaysShowActions:G,renderSessionNode:Te,secondaryMeta:Re,renderContext:He="project",subtreeContainsEditing:Ke,menuOpenSessionId:Ue,childRenderExtrasFor:Ae}=e,X=o.useMemo(()=>xa(),[]),xe=!a&&!re,We=o.useRef(!1),Ce=o.useRef(f);Ce.current=f;const je=o.useRef(null),$e=o.useRef(m);$e.current=m;const[nt,_e]=o.useState(p),q=o.useRef(nt);q.current=nt;const V=o.useRef(null),be=o.useRef(null),Q=s.session,ve=Q,pe=gt(Q.directory??null)??gt(r??null),De=Oe(I=>I.currentSessionId===Q.id),at=ca(pe),ht=pd(pe),Ve=Ot(o.useCallback(I=>{if(Re?.projectLabel||!i)return null;const J=I.projects.find(Ee=>Ee.id===i);return J?J.label?.trim()||As(gt(J.path)??J.path,null)||J.path:null},[i,Re?.projectLabel])),Me=Re?.projectLabel??(Ve?Vn(Ve):null),ke=Re?.branchLabel??s.worktree?.branch??(at&&at!=="HEAD"?at:null),Le=ke,dt=ht===!0||!!(ke||s.worktree),bt=s.children.length,rt=ve.agent;o.useMemo(()=>{const I=s.worktree?.branch?.trim()||ke?.trim(),J=gt(s.worktree?.path??pe);return I&&J?Va():null},[s.worktree,ke,pe]);const $=up();o.useMemo(()=>null,[$]);const me=i??pe??null,Ne=ua(),w=so(),W=$t(I=>I.enabled),se=$t(o.useCallback(I=>I.selectedIds.has(Q.id),[Q.id])),de=$t(I=>I.toggleSelected),we=$t(I=>I.setRange),Ie=o.useCallback(I=>{const J=[],Ee=ft=>{ft.children.forEach(xt=>{J.push(xt.session.id),Ee(xt)})};return Ee(I),J},[]);o.useCallback(I=>{const J=[],Ee=ft=>{ft.children.forEach(xt=>{J.push(xt.session),Ee(xt)})};return Ee(I),J},[]);const[ze,lt]=o.useState(!1),[St,Je]=o.useState(!0),ct=`${He}:${a?"archived":"active"}:${Q.id}`,pt=md(o.useCallback(I=>!!I.sessionMemoryState.get(gd(Q.id))?.isZombie,[Q.id])),Ge=da(Q.id)?.type??"idle",mt=Ge==="busy"||Ge==="retry",Tt=xd(Q.id,mt),Bt=bd(Q.id),vt=ve.title||"Untitled Session",jt=s.children.length>0,kt=yd(l,pe,Q.id),F=ct,Se=d?!0:c.has(F);o.useMemo(()=>ap(s,Se,pe),[Se,s,pe]);const Be=Cd(),ot=!!ve.parentID,oe=vd(Q.id)>0&&(!ot||b),he=ve.time?.updated||ve.time?.created||Date.now(),Xe=kd(he),[ye,Qe]=o.useState(!1),ut=o.useMemo(()=>Ie(s).length,[Ie,s]),At=o.useCallback(async I=>{const J=[];let Ee=0;for(const ft of I)try{if(!pe)throw new Error("Session directory is required for export");await w.loadCompleteHistory?.(ft.session.id,pe);const xt=Er(Ne.getState(),ft.session.id).list,Ut=ft.session.title||"Untitled Sub-agent",Kt=ft.session.agent,rs=await At(ft.children);Ee+=rs.skipped,J.push({title:Ut,agent:Kt,records:xt,children:rs.children})}catch{Ee+=Ie(ft).length+1}return{children:J,skipped:Ee}},[Ie,Ne,pe,w]),Rt=o.useCallback(I=>{I<=0||ce.warning(I===1?`Exported session, but skipped ${I} sub-agent task that could not be loaded.`:`Exported session, but skipped ${I} sub-agent tasks that could not be loaded.`)},[]),It=o.useCallback(async I=>{if(!pe){ce.error("Nothing to export");return}try{await w.loadCompleteHistory?.(Q.id,pe)}catch{ce.error("Failed to load the complete session history");return}const J=Er(Ne.getState(),Q.id).list;if(J.length===0){ce.error("Nothing to export");return}let Ee,ft=0;if(I&&s.children.length>0){const rs=await At(s.children);Ee=rs.children,ft=rs.skipped}const xt=Xa(J,ve.title??null,Ee),Ut=tl(ve.title??null),Kt=await el(xt,Ut);if(Kt){ce.success("Session exported",{action:{label:zp(),onClick:()=>{_p(Kt).then(rs=>{rs||ce.error("Failed to reveal path")})}}}),Rt(ft);return}Za(xt,Ut),ce.success("Session exported"),Rt(ft)},[At,Ne,s.children,ve.title,Q.id,pe,Rt,w]),Gt=o.useCallback(async()=>{if(s.children.length>0){Je(!0),lt(!0);return}await It(!1)},[It,s.children.length]),_t=o.useCallback(()=>{pe&&nn("desktop_open_session_mini_chat_window",{sessionId:Q.id,directory:pe,apiBaseUrl:Mr(),clientToken:Rr()}).catch(I=>{console.warn("[session-sidebar] failed to open mini chat window",I)})},[Q.id,pe]);o.useEffect(()=>{if(f!==Q.id)return;const I=J=>{const ft=J.target?.closest?.(`[data-session-rename-form="${CSS.escape(Q.id)}"]`);be.current&&!ft&&$e.current(q.current)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[f,Q.id]),o.useLayoutEffect(()=>{if(f!==Q.id){V.current===Q.id&&(V.current=null);return}V.current!==Q.id&&(V.current=Q.id,_e(p))},[f,p,Q.id]);const Ct=Bt.length,Ft=!mt&&oe&&!De,U=mt&&Tt,ne=kt,le=t.jsx(k,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),ue=ne?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:le}):null,ge=jt?t.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),C(F)},onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),I.stopPropagation(),C(F))},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":Se?"Collapse subsessions":"Expand subsessions",children:Se?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,it=pt?t.jsx(k,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Dt=I=>{if(!I&&je.current){const{id:J,title:Ee}=je.current;je.current=null,y(J),h(Ee)}},yt=I=>{Qe(I)},Ht=I=>{I.preventDefault(),I.stopPropagation()},Xt=I=>{I.preventDefault(),I.stopPropagation()},Pt=I=>{I.preventDefault(),I.stopPropagation(),E(null),z(Q,{archivedBucket:a})},ns=I=>{I.preventDefault(),I.stopPropagation(),E(null),z(Q,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},ls=I=>{if(We.current){We.current=!1;return}if(W){if(I?.preventDefault(),I?.stopPropagation(),I?.shiftKey){const Ee=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Ut=>Ut.getAttribute("data-session-row")).filter(Ut=>typeof Ut=="string"&&Ut.length>0),ft=$t.getState().anchorId,xt=new Map;xt.set(Q.id,Ie(s)),we(ft,Q.id,Ee,me,xt);return}de(Q.id,me,Ie(s));return}I?.currentTarget&&Jp(I.currentTarget),N(Q.id,pe)},ms=I=>{I.defaultPrevented||I.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||ls(I)},Ws=I=>{(I.button===2||I.button===0&&I.ctrlKey&&!W)&&(We.current=!0)},Ys=({Item:I,Separator:J,Sub:Ee,SubTrigger:ft,SubContent:xt})=>t.jsxs(t.Fragment,{children:[t.jsxs(I,{onClick:()=>{je.current={id:Q.id,title:vt}},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(I,{onClick:()=>D(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(I,{onClick:()=>pe&&g({directory:pe,sessionId:Q.id}),className:"[&>svg]:mr-1",children:[kt?t.jsx(k,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(k,{name:"pushpin",className:"mr-1 h-4 w-4"}),kt?"Unpin session":"Pin session"]}),t.jsxs(I,{onClick:()=>{Gt()},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),t.jsxs(I,{disabled:!pe,onClick:()=>{pe&&B(pe,{mode:"chat",dedupeKey:`session:${Q.id}`,label:vt,sessionTitleFallback:vt})},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"})]}),X?t.jsxs(I,{disabled:!pe,onClick:_t,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(J,{}),a?null:t.jsxs(I,{className:"[&>svg]:mr-1",onClick:()=>z(Q,{archivedBucket:a}),children:[t.jsx(k,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(I,{className:"[&>svg]:mr-1",onClick:()=>Y(Q),children:[t.jsx(k,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(I,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>z(Q,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(k,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]}),R=t.jsx(Br,{children:t.jsx(_r,{className:"app-region-no-drag z-50",children:t.jsx(zr,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(K||Ce.current),style:{color:"var(--surface-elevated-foreground)"},className:O(Ir,"min-w-[180px]"),children:Ys({Item:({className:I,...J})=>t.jsx(Sa,{className:O(Ji,I),...J}),Separator:({className:I,...J})=>t.jsx(ja,{className:O(Xi,I),...J}),Sub:zu,SubTrigger:({className:I,children:J,...Ee})=>t.jsxs($u,{className:O(jd,I),...Ee,children:[J,t.jsx(k,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:I,children:J,...Ee})=>t.jsx(Br,{children:t.jsx(_r,{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:O(Ir,I),...Ee,children:J})})})})})})});return t.jsxs(o.Fragment,{children:[t.jsx(rp,{sessionId:Q.id,sessionDirectory:pe??null,sessionTitle:vt,children:t.jsxs(va,{open:ye,onOpenChange:yt,onOpenChangeComplete:Dt,children:[t.jsxs(wa,{render:t.jsx("div",{"data-session-row":Q.id,"data-session-scope":me??"","data-session-archived":a?"1":"0",onClick:ms,style:n>0?{marginLeft:`${n*14}px`}:void 0,className:O("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",De&&!se&&"bg-interactive-selection",se&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[ge,ue,f===Q.id?t.jsxs("form",{ref:be,"data-session-rename-form":Q.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:I=>I.stopPropagation(),onMouseDown:I=>I.stopPropagation(),onSubmit:I=>{I.preventDefault(),m(nt)},children:[t.jsx("input",{value:nt,onChange:I=>_e(I.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:I=>{I.stopPropagation(),I.key==="Escape"&&S()}}),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:S,"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:Ws,onClick:I=>ls(I),onDoubleClick:I=>{I.stopPropagation(),v(Q.id,vt)},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:O("block min-w-0 flex-1 truncate font-normal typography-ui-label",oe?"text-foreground":"text-foreground/90"),children:Fn(vt,u)})}),Re?.showFolderLabel&&Me||Le||dt||$||bt>0||rt&&rt!=="default"||U||Ct>0||Be>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:[Re?.showFolderLabel&&Me?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Me}):null,Le?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:O("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Le})]}):dt?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,bt>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:bt})]}):null,rt&&rt!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:rt}):null,U?t.jsx(wd,{sessionId:Q.id,running:mt,className:"text-muted-foreground/70"}):null,Ct>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:Ct})]}):null,null]}):null]})]}),kt?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:O("flex items-center justify-end",xe&&(G||ye)?"opacity-0":xe?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:mt?t.jsx(Yn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):Ft?t.jsx(Sd,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:Xe})}),xe?t.jsx("div",{className:O("absolute inset-0 flex items-center justify-end",G||ye?"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(Xp,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Ht,onMouseDown:Xt,onArchive:Pt,onDelete:ns})}):null]}),it&&!re?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:it}):null]}),R]})}),jt&&Se?s.children.map(I=>{const J=Ae?Ae(I):{subtreeContainsEditing:Ke,menuOpenSessionId:Ue,nodeStructureKey:""};return t.jsx(o.Fragment,{children:Te(I,n+1,pe??r,i,a,void 0,He,J)},I.session.id)}):null,t.jsx(is,{open:ze,onOpenChange:lt,children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:"Export Markdown"}),t.jsx(Es,{children:ut===1?`This session has ${ut} sub-agent task. Include it in the export?`:`This session has ${ut} 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:St,onChange:I=>Je(I.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Ts,{children:[t.jsx(qe,{type:"button",onClick:()=>lt(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(qe,{type:"button",onClick:()=>{lt(!1),It(St)},size:"sm",children:"Export"})]})]})})]},Q.id)}const ki=e=>gt(e.session.directory??null),em=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),tm=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},Nn=e=>e.menuOpenSessionId??tm(e),An=(e,s,n)=>s?n.has(e.node.session.id)?!0:us(e.node,s):!1,Jr=(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(Jr(e.children[l],s.children[l],n,r,i))return!0;return!1},sm=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Jr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${e.renderContext??"project"}:${n}:${i.session.id}`)||Jr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},nm=(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||ki(e.node)!==ki(s.node)||!em(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Ya(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&sm(e,s)||e.editingId!==s.editingId&&(An(e,e.editingId,e.subtreeContainsEditing)||An(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(An(e,e.editingId,e.subtreeContainsEditing)||An(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(us(e.node,e.copiedSessionId)||us(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Nn(e),r=Nn(s);if(us(e.node,n)||us(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=Nn(e),r=Nn(s);if(us(e.node,n)||us(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},rm=o.memo(Zp,nm),Ni={selected:0,"active-project":1,expanded:2,visible:3,background:4};function om(e){const s=new Map,n=(r,i,a)=>{const l=gt(r??null);if(!l)return;const c=s.get(l);c&&Ni[c.priority]<=Ni[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 im(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l="Untitled Session";return t.jsx(is,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Es,{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(Ts,{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 am(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(is,{open:!!s,onOpenChange:b=>{b||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:d}),t.jsx(Es,{children:u})]}),t.jsxs(Ts,{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 lm(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(is,{open:!!s,onOpenChange:i=>{i||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:"Delete folder?"}),t.jsx(Es,{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(Ts,{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 cm=({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(et,{children:[t.jsx(tt,{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(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:O("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(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(et,{children:[t.jsx(tt,{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(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},dm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:b,setBulkDeleteConfirm:f}=e,y=$t(H=>H.enabled),p=$t(H=>H.selectedIds.size),h=p>0,m=$t(H=>H.selectedIds),S=$t(H=>H.scopeKey),C=o.useCallback(()=>{$t.getState().toggleMode()},[]),N=o.useCallback(()=>{$t.getState().disable()},[]),v=o.useMemo(()=>{if(!h||typeof document>"u")return!1;let H=!1,B=!1;for(const z of m){const Y=document.querySelectorAll(`[data-session-row="${CSS.escape(z)}"]`);for(const re of Y)re.getAttribute("data-session-archived")==="1"?B=!0:H=!0}return B&&!H},[h,m]),g=o.useMemo(()=>{if(S)return S;if(!h||typeof document>"u")return null;for(const H of m){const z=document.querySelector(`[data-session-row="${CSS.escape(H)}"]`)?.getAttribute("data-session-scope");if(z&&z.length>0)return z}return null},[h,m,S]),x=o.useMemo(()=>{if(!g)return[];const H=i.get(g);return H&&H.length>0?H.map(B=>B.scopeKey):[g]},[g,i]),A=o.useMemo(()=>x.flatMap(H=>r[H]??[]),[r,x]),P=o.useCallback(H=>{for(const B of x)if((r[B]??[]).some(z=>z.id===H))return B;return null},[r,x]),D=o.useMemo(()=>{if(!h)return!1;for(const H of x)for(const B of r[H]??[])for(const z of B.sessionIds)if(m.has(z))return!0;return!1},[r,x,h,m]),T=o.useCallback((H,B)=>{const z=Array.from(m);for(const Y of x)Y!==H&&l(Y,z);a(H,B,z)},[a,l,m,x]),M=o.useCallback(H=>{if(!h)return;const B=P(H);B&&T(B,H)},[h,T,P]),E=o.useCallback(()=>{const H=x[0];if(!H||!h)return;const B=c(H);B&&T(H,B.id)},[c,h,T,x]),K=o.useCallback(()=>{if(!h)return;const H=Array.from(m);for(const B of x)l(B,H)},[l,m,x,h]),Z=o.useCallback(async()=>{const H=Array.from(m);if(H.length!==0){if(v){const{deletedIds:B,failedIds:z}=await b(H);B.length>0&&ce.success(B.length===1?`Deleted ${B.length} session`:`Deleted ${B.length} sessions`),z.length>0&&ce.error(z.length===1?`Failed to delete ${z.length} session`:`Failed to delete ${z.length} sessions`)}else{const{archivedIds:B,failedIds:z}=await d(H);B.length>0&&ce.success(B.length===1?`Archived ${B.length} session`:`Archived ${B.length} sessions`),z.length>0&&ce.error(z.length===1?`Failed to archive ${z.length} session`:`Failed to archive ${z.length} sessions`)}$t.getState().clear()}},[d,v,b,m]),ee=o.useCallback(()=>{if(!h)return;const H=m.size;if(!n){Z();return}f({sessionCount:H,archivedBucket:v})},[v,Z,m,n,f,h]),te=o.useCallback(async()=>{if(!h||!v)return;const H=Array.from(m),{restoredIds:B,failedIds:z}=await u(H);B.length>0&&ce.success(B.length===1?`Restored ${B.length} session`:`Restored ${B.length} sessions`),z.length>0&&ce.error(z.length===1?`Failed to restore ${z.length} session`:`Failed to restore ${z.length} sessions`),$t.getState().clear()},[v,h,m,u]),_=o.useCallback(async()=>{f(null),await Z()},[Z]);return o.useEffect(()=>{if(!y)return;const H=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),B=z=>{if(s)return;const Y=z.target;if(Y&&(Y.tagName==="INPUT"||Y.tagName==="TEXTAREA"||Y.isContentEditable))return;const re=H?z.metaKey:z.ctrlKey;if(z.key==="Escape"){z.preventDefault(),$t.getState().disable();return}if(re&&z.key==="Backspace"){z.preventDefault(),ee();return}if(re&&(z.key==="a"||z.key==="A")){const G=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(G.length===0)return;z.preventDefault();const Re=$t.getState().scopeKey??G[0]?.getAttribute("data-session-scope")??null,He=Ue=>Re?Ue.getAttribute("data-session-scope")===Re:!0,Ke=G.filter(He).map(Ue=>Ue.getAttribute("data-session-row")).filter(Ue=>typeof Ue=="string"&&Ue.length>0);if(Ke.length===0)return;$t.getState().replaceAll(Ke,Re||null)}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[ee,s,y]),{selectionModeEnabled:y,hasSelection:h,selectedIdsSize:p,bulkScopeIsArchived:v,derivedSelectionScope:g,bulkScopeFolders:A,bulkCanRemoveFromFolder:D,handleToggleSelectionMode:C,handleExitSelectionMode:N,handleBulkMoveToFolder:M,handleBulkCreateFolderAndMove:E,handleBulkRemoveFromFolder:K,handleBulkDelete:ee,handleBulkRestore:te,confirmBulkDelete:_}},Ai="oc.sessions.projectCollapse",Ii="oc.sessions.groupOrder",Di="oc.sessions.groupCollapse",Pi="oc.sessions.activeSessionByProject",Ei="oc.sessions.expandedParents.v3",um=(e,s,n)=>{if(e.time?.archived)return!0;const r=Yo(zs(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const i of s)if(Yo(i)===r)return!0;return!1},fm=new Set,pr=[],Zt=e=>{const s=o.useRef(e);return s.current=e,o.useCallback((...n)=>s.current(...n),[])},hm=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l})=>{const c=Oe(d=>d.currentSessionDirectory);return o.useEffect(()=>{s.setBootstrapDemand(e,om({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},pm=({directories:e})=>{const s=o.useMemo(()=>{const r=new Set;return e.forEach(i=>{const a=gt(i)?.toLowerCase();a&&r.add(a)}),r},[e]);return tn(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=gt(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(Yn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},mm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Tr("react.session_sidebar_render"),ss("ui.session_sidebar.render"),ss(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),ss(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,b]=o.useState(""),f=o.useRef(null),y=o.useRef(null),[p,h]=o.useState(null),[m,S]=o.useState(""),[C,N]=o.useState(null),[v,g]=o.useState(new Set),x=o.useMemo(()=>vn(),[]),[A,P]=o.useState(new Set),[D,T]=o.useState(null),[M,E]=o.useState(new Map),[K,Z]=o.useState(new Map),[ee,te]=o.useState(!1),[_,H]=o.useState(null),[B,z]=o.useState(null),[Y,re]=o.useState(""),[G,Te]=o.useState(null),[Re,He]=o.useState(null),[Ke,Ue]=o.useState(null),Ae=Pr(j=>j.ids),X=Nd(o.useCallback(j=>e?j.rankById:aa,[e])),xe=tn(j=>e?Ad(j.catalog):"",void 0,"catalog"),We=o.useMemo(()=>xe?xe.split("|"):pr,[xe]),Ce=o.useMemo(()=>new Set(We),[We]),je=Id($r(j=>e?Object.entries(j.index.session.unseenCount).filter(([,ae])=>ae>0).map(([ae])=>ae).sort():pr)),$e=o.useMemo(()=>new Set(je),[je]),nt=Pr(j=>j.toggle),[_e,q]=o.useState(()=>{try{const j=vn().getItem(Di);if(!j)return new Set;const ae=JSON.parse(j);return new Set(Array.isArray(ae)?ae.filter(ie=>typeof ie=="string"):[])}catch{return new Set}}),[V,be]=o.useState(()=>{try{const j=vn().getItem(Ii);if(!j)return new Map;const ae=JSON.parse(j),ie=new Map;return Object.entries(ae).forEach(([Ze,Nt])=>{Array.isArray(Nt)&&ie.set(Ze,Nt.filter(os=>typeof os=="string"))}),ie}catch{return new Map}}),Q=o.useMemo(()=>{try{const j=vn().getItem(Pi);if(!j)return new Map;const ae=JSON.parse(j),ie=new Map;return Object.entries(ae).forEach(([Ze,Nt])=>{typeof Nt=="string"&&Nt.length>0&&ie.set(Ze,Nt)}),ie}catch{return new Map}},[]),ve=o.useCallback(j=>{try{x.setItem(Pi,JSON.stringify(Object.fromEntries(j.entries())))}catch{}},[x]),[pe,De]=o.useState(new Map),at=o.useRef(new Map),ht=o.useRef(0),Ve=Ds(j=>j.homeDirectory),Me=Ds(j=>j.currentDirectory),ke=Ot(j=>j.projects),Le=Ot(j=>j.activeProjectId),dt=Ot(j=>j.removeProject),bt=Ot(j=>j.setActiveProjectIdOnly),rt=Ot(j=>j.updateProjectMeta),$=Ot(j=>j.reorderProjects),me=fe(j=>j.setActiveMainTab),Ne=fe(j=>j.openContextPanelTab),w=fe(j=>j.setSettingsDialogOpen),W=fe(j=>j.setSettingsPage),se=fe(j=>j.toggleHelpDialog),de=fe(j=>j.setSessionSwitcherOpen),we=fe(j=>j.setArchivePageOpen),Ie=fe(j=>j.notifyOnSubtasks),ze=fe(j=>j.showDeletionDialog),lt=fe(j=>j.setShowDeletionDialog),St=Dd(u,120),Je=o.useMemo(()=>St.trim().toLowerCase(),[St]),ct=Je.length>0,pt=zt(j=>j.collapsedFolderIds),Fe=zt(j=>j.foldersMap),Ge=zt(j=>j.getFoldersForScope),mt=zt(j=>j.createFolder),Tt=zt(j=>j.renameFolder),Bt=zt(j=>j.deleteFolder),vt=zt(j=>j.addSessionToFolder),jt=zt(j=>j.addSessionsToFolder),kt=zt(j=>j.removeSessionFromFolder),F=zt(j=>j.removeSessionsFromFolders),Se=zt(j=>j.toggleFolderCollapse),Be=zt(j=>j.getSessionFolderId);zh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:y,sessionSearchContainerRef:f});const ot=Pd(e),L=so(),oe=la(),he=tn(j=>j.connection,void 0,"chrome"),Xe=tn(j=>{for(const ae of j.catalog.listStatusByDirectory.values())if(ae==="ready")return!0;return!1},void 0,"catalog"),ye=Dr({archived:!1}),Qe=Dr({archived:!0}),ut=`session-sidebar:${o.useId()}`,At=Oe(j=>j.setCurrentSession),Rt=Oe(j=>j.updateSessionTitle),It=Oe(j=>j.shareSession),Gt=Oe(j=>j.unshareSession),_t=Oe(j=>j.availableWorktreesByProject)??new Map,Ct=Oe(j=>j.openNewSessionDraft),Ft=o.useCallback(j=>{fe.getState().closeMainSurfaces(),Ct(j),r?.()},[r,Ct]),U=Mn($r(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}))),ne=o.useMemo(()=>Ed(ke,_t,{includeWorktrees:!0}),[_t,ke]),le=o.useMemo(()=>ye.filter(j=>um(j,ne,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[ye,ne]),ue=o.useMemo(()=>[...le,...Qe],[Qe,le]),ge=qn(),it=o.useMemo(()=>`${ge}|${ke.map(j=>`${j.id}:${gt(j.path)??""}`).join("|")}`,[ke,ge]),[Dt,yt]=o.useState(null),Ht=Dt!==it,[Xt,Pt]=o.useState(new Set),ns=o.useMemo(()=>fs(),[]),{isTablet:ls}=Ps(),ms=s||ls,{buildGroupSearchText:Ws,filterSessionNodesForSearch:Ys,buildGroupedSessions:R}=_h({homeDirectory:Ve,pinnedSessionIds:Ae,sessionOrderRanks:X}),{scheduleCollapsedProjectsPersist:I}=Uh({safeStorage:x,keys:{sessionExpanded:Ei,projectCollapse:Ai,groupOrder:Ii,groupCollapse:Di},groupOrderByProject:V,collapsedGroups:_e,setExpandedParents:g,setCollapsedProjects:P}),J=o.useMemo(()=>Td(le,Ae,X),[Ae,X,le]),Ee=o.useMemo(()=>J.map(j=>j.id).join("|"),[J]),ft=o.useRef(null),xt=o.useMemo(()=>{const j=ft.current;if(j&&j.signature===Ee)return j.map;const ae=new Map(J.map((ie,Ze)=>[ie.id,Ze]));return ft.current={signature:Ee,map:ae},ae},[J,Ee]),Ut=o.useMemo(()=>{const j=new Map;return J.forEach(ae=>{const ie=ae.parentID;if(!ie)return;const Ze=j.get(ie)??[];Ze.push(ae),j.set(ie,Ze)}),j.forEach(ae=>ae.sort((ie,Ze)=>_n(ie,Ze,Ae,X))),j},[J,Ae,X]),Kt=o.useMemo(()=>t.jsx(Ns,{icon:"chat-new",mobileVariant:s,onClick:()=>Ft(),children:"New session"}),[s,Ft]),rs=o.useMemo(()=>ke.find(j=>j.id===C)??null,[ke,C]),ol=o.useCallback(j=>{C&&rt(C,{label:j.label,defaultModel:j.defaultModel??null})},[C,rt]),il=o.useCallback(()=>{const j=Mn.getState();if(j.available&&j.info){te(!0);return}U.checkForUpdates().then(()=>{const{available:ae,error:ie}=Mn.getState();if(ie){ce.error("Failed to check for updates",{description:ie});return}if(!ae){ce.success("You are on the latest version");return}te(!0)})},[U]),Rs=Rd(),go=o.useCallback(()=>{if(s&&de(!1),r?.(),Rs?.openSettings){Rs.openSettings();return}w(!0)},[Rs,s,r,de,w]),al=U.available&&(U.runtimeType==="desktop"||U.runtimeType==="web"),ll=Oe(j=>j.deleteSession),xo=Oe(j=>j.deleteSessions),cl=Oe(j=>j.archiveSession),bo=Oe(j=>j.archiveSessions),dl=Oe(j=>j.unarchiveSession),ul=Oe(j=>j.unarchiveSessions),{copiedSessionId:fl,handleSessionSelect:hl,handleSessionDoubleClick:pl,handleSaveEdit:ml,handleCancelEdit:gl,handleShareSession:xl,handleCopyShareUrl:bl,handleCopySessionId:yl,handleUnshareSession:vl,handleDeleteSession:wl,handleRestoreSession:Sl,confirmDeleteSession:jl}=$h({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:b,setIsSessionSearchOpen:d,setActiveMainTab:me,setSessionSwitcherOpen:de,setCurrentSession:At,updateSessionTitle:Rt,shareSession:It,unshareSession:Gt,deleteSession:ll,deleteSessions:xo,archiveSession:cl,archiveSessions:bo,unarchiveSession:dl,childrenMap:Ut,showDeletionDialog:ze,setDeleteSessionConfirm:Te,deleteSessionConfirm:G,setEditingId:h,setEditTitle:S,editingId:p,editTitle:m}),Cl=o.useCallback(()=>{if(!Re)return;const{scopeKey:j,folderId:ae}=Re;He(null),Bt(j,ae)},[Re,Bt]),yo=o.useCallback(()=>{Is.requestDirectoryDialog()},[]),kl=o.useCallback(j=>{g(ae=>{const ie=Md(ae,j);try{x.setItem(Ei,JSON.stringify(Array.from(ie)))}catch{}return ie})},[x]),vo=o.useCallback((j,ae)=>{if(!j)return null;ae&&pt.has(ae)&&Se(ae);const ie=mt(j,"New folder",ae);return z(ie.id),re(ie.name),ie},[pt,Se,mt]),wo=Zt(hl),Nl=Zt(pl),Al=Zt(ml),Il=Zt(gl),Dl=Zt(xl),Pl=Zt(bl),El=Zt(yl),Tl=Zt(vl),Rl=Zt(wl),Ml=Zt(Sl),sr=Zt(vo),So=o.useCallback((j,ae)=>{Z(ie=>{const Ze=new Map(ie);return Ze.set(j,ae+7),Ze})},[]),mn=o.useCallback(j=>{Z(ae=>{if(!ae.has(j))return ae;const ie=new Map(ae);return ie.delete(j),ie})},[]),jo=o.useCallback(j=>{Z(ae=>{let ie=!1;const Ze=new Map(ae),Nt=`${j}:`;for(const os of Ze.keys())os.startsWith(Nt)&&(Ze.delete(os),ie=!0);return ie?Ze:ae})},[]),Fl=o.useCallback(j=>{ht.current=Date.now()+150,jo(j),P(ae=>{const ie=new Set(ae);ie.has(j)?ie.delete(j):ie.add(j);try{x.setItem(Ai,JSON.stringify(Array.from(ie)))}catch{}return I(ie),ie})},[jo,x,I]),gs=o.useMemo(()=>ke.map(j=>({...j,normalizedPath:gt(j.path)})).filter(j=>!!j.normalizedPath),[ke]),Ll=o.useMemo(()=>gs.map(j=>j.normalizedPath),[gs]),Co=Fd(e?Ll:pr);Hh({enabled:e,normalizedProjects:gs,gitRepoStatus:Co,setProjectRepoStatus:E,setProjectRootBranches:De});const Ol=Oe(j=>j.isLoading),ko=o.useMemo(()=>Zh(le,gs,_t,Qe),[Qe,_t,gs,le]);qh({enabled:e,hasAuthoritativeGlobalSessions:Xe,sessions:ue});const{getSessionsForProject:Bl,getArchivedSessionsForProject:_l}=Kh({ownership:ko});Mh({enabled:e,normalizedProjects:gs,ownership:ko,isSessionsLoading:Ol,hasAuthoritativeGlobalSessions:Xe,isWorktreeTopologyLoading:Ht,unresolvedWorktreeProjectPaths:Xt,foldersMap:Fe,createFolder:mt,addSessionToFolder:vt});const No=o.useRef(!1);Le&&M.has(Le)&&(No.current=!!M.get(Le));const zl=Si(j=>j.showArchivedSessions),Ao=Si(j=>j.stickyZoneHeaders),nr=Ot(j=>j.manualProjectOrder),Io=o.useRef(new Set),gn=Ld(Io.current,v,"project");Io.current=gn;const rr={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:ls,catalogSessions:ye,archivedSessions:Qe,projects:ke,activeProjectId:Le,manualProjectOrder:nr,currentDirectory:Me,availableWorktreesByProject:_t,pinnedSessionIds:Ae,sessionOrderRanks:X,foldersMap:Fe,collapsedFolderIds:pt,gitBranches:ot,gitRepoStatus:Co,updateStore:U,showArchivedSessions:zl,projectRepoStatus:M,projectRootBranches:pe,resolvedWorktreeTopologyKey:Dt,unresolvedWorktreeProjectPaths:Xt,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:p,editTitle:m,editingProjectDialogId:C,expandedParents:v,collapsedProjects:A,visibleSessionCountByGroup:K,updateDialogOpen:ee,openSidebarMenuKey:_,renamingFolderId:B,renameFolderDraft:Y,deleteSessionConfirm:G,deleteFolderConfirm:Re,bulkDeleteConfirm:Ke,collapsedGroups:_e},Do=o.useRef(null),Po=Do.current;if(Po){let j=!1;for(const ae of Object.keys(rr))Object.is(Po[ae],rr[ae])||(ss(`ui.session_sidebar.source.${ae}`),j=!0);j||ss("ui.session_sidebar.source.parent_or_context")}Do.current=rr;const $l=o.useMemo(()=>{const j=new Map(nr.map((ae,ie)=>[ae,ie]));return[...gs].sort((ae,ie)=>(j.get(ae.id)??1/0)-(j.get(ie.id)??1/0))},[nr,gs]),{projectSections:Et,groupSearchDataByGroup:Eo,flatSectionsForRender:xn,searchMatchCount:Ul}=Lh({normalizedProjects:$l,getSessionsForProject:Bl,getArchivedSessionsForProject:_l,projectRepoStatus:M,projectRootBranches:pe,lastRepoStatus:No.current,buildGroupedSessions:R,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Je,filterSessionNodesForSearch:Ys,buildGroupSearchText:Ws,foldersMap:Fe}),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:Hl}=Fh(V),To=o.useRef(!1);o.useEffect(()=>{if(To.current||Et.length===0)return;const j=Et.flatMap(ae=>ae.groups.filter(ie=>ie.isArchivedBucket).map(ie=>`${ae.project.id}:${ie.id}`));j.length>0&&q(ae=>new Set([...ae,...j])),To.current=!0},[Et]),o.useMemo(()=>{const j=new Map,ae=new Map;return Et.forEach(ie=>{const Ze=Vn(ie.project.label?.trim()||As(ie.project.normalizedPath,Ve)||ie.project.normalizedPath);ie.groups.forEach(Nt=>{const os=Nt.branch&&Nt.branch!=="HEAD"&&Nt.branch!==Ze?Nt.branch:null,Vs={projectLabel:Ze,branchLabel:os},vs=xc=>{xc.forEach(Ms=>{const Lo=ie.project.normalizedPath.length,bc=ae.get(Ms.session.id)??-1;Lo<bc||(j.set(Ms.session.id,{node:Ms,projectId:ie.project.id,groupDirectory:Nt.directory,secondaryMeta:Vs}),ae.set(Ms.session.id,Lo),Ms.children.length>0&&vs(Ms.children))})};vs(Nt.sessions)})}),j},[Et,Ve]);const or=o.useMemo(()=>xn.map(j=>j.groups.some(ae=>ae.isArchivedBucket)?{...j,groups:j.groups.filter(ae=>!ae.isArchivedBucket)}:j),[xn]),Kl=o.useMemo(()=>D?or.filter(j=>j.project.id===D):or,[or,D]),Wl=o.useMemo(()=>{let j=0;for(const ae of Et)for(const ie of ae.groups)ie.isArchivedBucket||(j+=ie.sessions.length);return j},[Et]),Yl=o.useMemo(()=>{const j=new Map;for(const ae of Et){let ie=0;for(const Ze of ae.groups)Ze.isArchivedBucket||(ie+=Ze.sessions.length);j.set(ae.project.id,ie)}return j},[Et]),Vl=o.useCallback(j=>{const ae=Et.find(ie=>ie.project.id===j);return ae?ae.groups.some(ie=>ie.isArchivedBucket?!1:ie.sessions.some(Ze=>Ce.has(Ze.session.id))):!1},[Ce,Et]),ql=o.useCallback(j=>{const ae=Et.find(ie=>ie.project.id===j);return ae?ae.groups.some(ie=>ie.isArchivedBucket?!1:ie.sessions.some(Ze=>$e.has(Ze.session.id))):!1},[Et,$e]),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=ep({enabled:e&&Ao,isDesktopShellRuntime:ns,projectSections:Et,projectHeaderSentinelRefs:at}),bn=Zt((j,ae=0,ie,Ze,Nt=!1,os,Vs="project",vs)=>t.jsx(rm,{node:j,depth:ae,groupDirectory:ie,projectId:Ze,archivedBucket:Nt,pinnedSessionIds:Ae,expandedParents:gn,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Je,notifyOnSubtasks:Ie,editingId:p,setEditingId:h,editTitle:m,setEditTitle:S,handleSaveEdit:Al,handleCancelEdit:Il,toggleParent:kl,handleSessionSelect:wo,handleSessionDoubleClick:Nl,togglePinnedSession:nt,handleShareSession:Dl,copiedSessionId:fl,handleCopyShareUrl:Pl,handleCopySessionId:El,handleUnshareSession:Tl,openSidebarMenuKey:_,setOpenSidebarMenuKey:H,renamingFolderId:B,getFoldersForScope:Ge,getSessionFolderId:Be,removeSessionFromFolder:kt,addSessionToFolder:vt,createFolderAndStartRename:sr,openContextPanelTab:Ne,handleDeleteSession:Rl,handleRestoreSession:Ml,mobileVariant:s,alwaysShowActions:ms,renderSessionNode:bn,secondaryMeta:os,renderContext:Vs,subtreeContainsEditing:vs?.subtreeContainsEditing??fm,menuOpenSessionId:vs?.menuOpenSessionId??null,nodeStructureKey:vs?.nodeStructureKey??"",childRenderExtrasFor:vs?.childRenderExtrasFor})),Zl=o.useMemo(()=>{const j=new Map;return xn.forEach(ae=>{const ie=ae.groups.find(Ze=>!Ze.isArchivedBucket);ie?.folderScopes&&ie.folderScopes.length>0&&j.set(ae.project.id,ie.folderScopes)}),j},[xn]),ec=o.useCallback((j,ae)=>{const ie=[];return ae.forEach(Ze=>{Ze.isArchivedBucket||(ie.push(Ze.directory),Ze.folderScopes?.forEach(Nt=>ie.push(Nt.directory)))}),t.jsx(pm,{directories:ie})},[]),Ro=o.useCallback(j=>{mn(j),q(ae=>{const ie=new Set(ae);return ie.has(j)?ie.delete(j):ie.add(j),ie})},[mn]),tc=o.useCallback((j,ae,ie,Ze,Nt,os,Vs)=>t.jsx(vp,{group:j,groupKey:ae,projectId:ie,hideGroupLabel:Ze,dragHandleProps:Nt,compactBodyPadding:os,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Je,groupSearchDataByGroup:Eo,visibleSessionCount:K.get(ae),collapsedGroups:_e,hideDirectoryControls:a,collapsedFolderIds:pt,toggleFolderCollapse:Se,renameFolder:Tt,deleteFolder:Bt,showDeletionDialog:ze,setDeleteFolderConfirm:He,renderSessionNode:bn,showMoreGroupSessions:So,resetGroupSessionLimit:mn,mobileVariant:s,alwaysShowActions:ms,activeProjectId:Le,setActiveProjectIdOnly:bt,setActiveMainTab:me,setSessionSwitcherOpen:de,openNewSessionDraft:Ft,addSessionToFolder:vt,createFolderAndStartRename:sr,renamingFolderId:B,renameFolderDraft:Y,setRenameFolderDraft:re,setRenamingFolderId:z,pinnedSessionIds:Ae,expandedParents:gn,sessionOrderIndex:xt,editingId:p,editTitle:m,openSidebarMenuKey:_,activeActivitySessionIds:Ce,unreadActivitySessionIds:$e,notifyOnSubtasks:Ie,onToggleCollapsedGroup:Ro,scrollContainerRef:Vs}),[ct,Je,Eo,K,_e,a,pt,Se,Tt,Bt,ze,bn,So,mn,s,ms,Le,bt,me,de,Ft,vt,sr,B,Y,Ae,gn,xt,p,m,_,Ce,$e,Ie,Ro]),Mo=!!(B||p||C),{selectionModeEnabled:Fo,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}=dm({isInlineEditing:Mo,showDeletionDialog:ze,foldersMap:Fe,folderScopesByProject:Zl,addSessionsToFolder:jt,removeSessionsFromFolders:F,createFolderAndStartRename:vo,archiveSessions:bo,unarchiveSessions:ul,deleteSessions:xo,setBulkDeleteConfirm:Ue}),gc=o.useCallback(()=>{fe.getState().closeMainSurfaces(),me("chat"),s&&de(!1),Ct(),r?.()},[s,r,Ct,me,de]);return t.jsx(Od,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:f,className:O("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(hm,{owner:ut,childStores:oe,projectSections:Et,activeProjectId:Le,collapsedProjects:A,collapsedGroups:_e,currentDirectory:Me}),t.jsx(Bh,{projectSections:Et,activeProjectId:Le,initialActiveSessionByProject:Q,persistActiveSessionByProject:ve,handleSessionSelect:wo,mobileVariant:s,openNewSessionDraft:Ct,setActiveMainTab:me,setSessionSwitcherOpen:de}),t.jsx(Rh,{enabled:e,sortedSessions:J,prefetchSession:async j=>{await L.syncSession(j)}}),!a&&!s?t.jsx(Sp,{onNewSession:gc,showSidebarToggle:!0}):null,t.jsx(wp,{hideDirectoryControls:a,handleOpenDirectoryDialog:yo,onOpenArchive:()=>{s&&de(!1),we(!0)},onOpenSettings:s?go:void 0,onOpenInstances:s?Rs?.openInstances:void 0,instanceLabel:s?Rs?.instanceLabel:void 0,onOpenUpdate:s?Rs?.openUpdate:void 0,headerActionIconClass:Jl,headerActionButtonClass:Ql,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:y,sessionSearchQuery:u,setSessionSearchQuery:b,hasSessionSearchQuery:ct,searchMatchCount:Ul,selectionModeEnabled:Fo,onToggleSelectionMode:lc,mobileVariant:s}),he==="error"||he==="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&&Et.length>0?t.jsx(kp,{projects:Et.map(j=>j.project),selectedProjectId:D,onSelectProject:j=>{T(j),j&&bt(j)},onOpenDirectoryDialog:yo,onOpenProjectEditDialog:N,onRemoveProject:dt,totalSessionCount:Wl,getSessionCountForProject:j=>Yl.get(j)??0,hasActiveSessionByProject:Vl,hasUnseenByProject:ql,homeDirectory:Ve,mobileVariant:s}):null,t.jsx(Mp,{sectionsForRender:Kl,projectSections:Et,activeProjectId:Le,showOnlyMainWorkspace:l,hasSessionSearchQuery:ct,emptyState:Kt,searchEmptyState:Gl,isAllFoldersView:D===null,pinnedSessionIds:Ae,renderSessionNode:bn,renderGroupSessions:tc,homeDirectory:Ve,collapsedProjects:A,hideDirectoryControls:a,projectRepoStatus:M,isDesktopShellRuntime:ns,stickyZoneHeaders:Ao,stuckProjectHeaders:Xl,mobileVariant:s,alwaysShowActions:ms,toggleProject:Fl,setActiveProjectIdOnly:bt,setActiveMainTab:me,setSessionSwitcherOpen:de,openNewSessionDraft:Ft,openProjectEditDialog:N,removeProject:dt,projectHeaderSentinelRefs:at,reorderProjects:$,getOrderedGroups:Hl,setGroupOrderByProject:be,renderProjectStatusIndicator:ec,openSidebarMenuKey:_,setOpenSidebarMenuKey:H,isInlineEditing:Mo}),Fo&&sc?t.jsx(cm,{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(Np,{onOpenSettings:go,onOpenShortcuts:se,onOpenAbout:()=>{W("about"),w(!0)},onOpenUpdate:il,showRuntimeButtons:!0,showUpdateButton:al}),t.jsx(Ta,{open:ee,onOpenChange:te,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(tp,{open:!!rs,onOpenChange:j=>{j||N(null)},project:rs,onSave:ol}),t.jsx(im,{value:G,setValue:Te,showDeletionDialog:ze,setShowDeletionDialog:lt,onConfirm:jl}),t.jsx(lm,{value:Re,setValue:He,onConfirm:Cl}),t.jsx(am,{value:Ke,setValue:Ue,showDeletionDialog:ze,setShowDeletionDialog:lt,onConfirm:mc})]})})},kx=o.memo(mm),Ti=6,es=.18,Zs=1.2,en=.38,Ln=48,gm=(e,s)=>e==="left"?s<0:s>0,Nx=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Ax=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,Ri=(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)),Ix=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<-es:c>es,u=s==="left"?c>es:c<-es;return d||!u&&a<en}return Math.abs(n)>=Ln&&Math.abs(r)<=Math.abs(n)*Zs&&gm(s,n)},xm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:i,progress:a}=e,l=r/Math.max(1,i);return s==="left"?n?l<-es?!1:l>es?!0:a>en:l>es?!0:l<-es?!1:a>en:n?l>es?!1:l<-es?!0:a>en:l<-es?!0:l>es?!1:a>en},bm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',ym=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(bm);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let i=e;for(;i&&i!==s;){if(i instanceof HTMLElement&&i.scrollWidth>i.clientWidth){const a=getComputedStyle(i).overflowX;if(a==="auto"||a==="scroll")return!0}i=i.parentElement}return!1},vm=({value:e,options:s,disabled:n,onChange:r})=>{const i=e||"Default",a=t.jsxs("div",{className:O("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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:a}),t.jsxs(qt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(wt,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:O("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(wt,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:O("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Mi=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function wm(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:i=!1,onConfirm:a}=e,l=Mt(g=>g.loadProviders),c=Mt(g=>g.loadAgents),d=Mt(g=>g.providers),u=Mt(g=>g.currentProviderId),b=Mt(g=>g.currentModelId),f=Mt(g=>g.currentVariant||""),y=Mt(g=>g.currentAgentName||""),[p,h]=o.useState(()=>Mi({providerID:u,modelID:b,variant:f,agent:y}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&h(Mi({providerID:u,modelID:b,variant:f,agent:y}))},[s,u,b,f,y]),o.useEffect(()=>{if(!s||d.length===0)return;const g=d.find(D=>D.id===p.providerID)??d[0],x=Array.isArray(g?.models)?g.models:[],A=x.some(D=>D.id===p.modelID),P=x[0]?.id??"";g?.id===p.providerID&&A||h(D=>({...D,providerID:typeof g?.id=="string"?g.id:"",modelID:typeof P=="string"?A?D.modelID:P:"",variant:""}))},[s,d,p.providerID,p.modelID]),o.useCallback(g=>Bd(g.mode),[]);const m=o.useMemo(()=>{const x=d.find(A=>A.id===p.providerID)?.models?.find(A=>A.id===p.modelID);return x?.variants?Object.keys(x.variants):[]},[d,p.providerID,p.modelID]),S=m.length>0;o.useEffect(()=>{S||!p.variant||h(g=>({...g,variant:""}))},[S,p.variant]);const C=p.providerID.trim().length>0&&p.modelID.trim().length>0,N=o.useCallback(()=>{!C||i||a(p)},[C,i,a,p]);return o.useEffect(()=>{if(!s)return;const g=x=>{(x.metaKey||x.ctrlKey)&&x.key==="Enter"&&(x.preventDefault(),N())};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s,N]),t.jsx(is,{open:s,onOpenChange:g=>{i||n(g)},children:t.jsxs(as,{className:"max-w-md overflow-visible",children:[t.jsx(ys,{children:t.jsx(hs,{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(vm,{value:p.variant,options:m,disabled:!S,onChange:g=>h(x=>({...x,variant:g}))})]})}),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:N,disabled:!C||i,children:i?"Sending":"Send"})]})})]})})}const Xr=5,sl=15,In=new Map,On=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},Sm=(e,s)=>{const n=On(s);return Math.max(n*Xr,Math.min(n*sl,n*e))},jm=async(e,s)=>{const n=await Gd(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Cm=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Fi=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],Li=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},km=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Zn({id:e});return t.jsx("li",{ref:i,style:{transform:er.Transform.toString(l),transition:c},className:O(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},Nm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[b,f]=o.useState(""),[y,p]=o.useState(null),[h,m]=o.useState(()=>new Set),[S,C]=o.useState([]),[N,v]=o.useState(null),[g,x]=o.useState(!1),[A,P]=o.useState(0),D=o.useRef(!1),T=o.useRef(""),M=o.useRef(null),E=fe(w=>w.todoPanelHeight),K=fe(w=>w.setTodoPanelHeight),Z=fe(w=>w.notesPanelHeight),ee=fe(w=>w.setNotesPanelHeight),[te,_]=o.useState(!1),H=o.useRef(0),B=o.useRef(E),z=Oe(w=>w.currentSessionId),Y=Oe(w=>w.createSession),re=Oe(w=>w.initializeNewPiChamberSession),G=Oe(w=>w.sendMessage),Te=Oe(w=>w.setCurrentSession),Re=_d(w=>w.setPendingInputText),He=Ds(w=>w.currentDirectory),Ke=fe(w=>w.openContextPanelTab),Ue=fe(w=>w.setActiveMainTab),Ae=fe(w=>w.setSessionSwitcherOpen),X=fe(w=>w.padding),xe=o.useCallback(async(w,W)=>{if(!e)return!1;const se=e.id,we=(In.get(se)??Promise.resolve()).catch(()=>{}).then(()=>zd(e,{notes:w,todos:W}));In.set(se,we);try{const Ie=await we;return Ie||ce.error("Failed to save project notes"),Ie}finally{In.get(se)===we&&In.delete(se)}},[e]);o.useEffect(()=>{if(!e){c(""),u([]),C([]),f(""),m(new Set);return}let w=!1;return a(!0),(async()=>{try{const W=await $d(e),se=await Promise.all(W.plans.map(de=>jm(de,"Plan")));if(w)return;c(W.notes),u(Fi(W.todos)),C(se),T.current=W.notes,D.current=!0,f(""),m(new Set)}catch{w||(ce.error("Failed to load project notes"),c(""),u([]),C([]),T.current="",D.current=!0)}finally{w||a(!1)}})(),()=>{w=!0}},[A,e]),o.useEffect(()=>{if(!e)return;const w=W=>{const se=W.detail;se?.projectId&&se.projectId!==e.id||P(de=>de+1)};return window.addEventListener("pichamber:project-plan-saved",w),window.addEventListener("pichamber:project-notes-updated",w),()=>{window.removeEventListener("pichamber:project-plan-saved",w),window.removeEventListener("pichamber:project-notes-updated",w)}},[e]),o.useEffect(()=>{if(d.length<7)return;const w=Sm(d.length,X),W=On(X)*Xr;E!==w&&(E<W||E>w)&&K(w)},[d.length,X,E,K]),o.useEffect(()=>{if(!te)return;const w=se=>{const de=se.clientY-H.current,we=Math.min(On(X)*sl,Math.max(On(X)*Xr,B.current+de));K(we)},W=()=>{_(!1)};return window.addEventListener("pointermove",w),window.addEventListener("pointerup",W,{once:!0}),window.addEventListener("pointercancel",W,{once:!0}),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",W),window.removeEventListener("pointercancel",W)}},[te,X,K]);const We=o.useCallback(w=>{_(!0),H.current=w.clientY,B.current=E,w.preventDefault()},[E]),Ce=o.useCallback(()=>{M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),je=o.useCallback(()=>{Ce(),T.current=l,xe(l,d)},[Ce,l,xe,d]);o.useEffect(()=>{if(!(!e||!D.current)&&l!==T.current)return M.current=window.setTimeout(()=>{M.current=null,T.current=l,xe(l,d)},400),()=>{Ce()}},[Ce,l,xe,e,d]),o.useEffect(()=>()=>Ce(),[Ce]);const $e=o.useCallback(()=>{const w=b.trim();if(!w)return;const W=Li(d,{id:Cm(),text:w.slice(0,yn),completed:!1,createdAt:Date.now()});u(W),f(""),xe(l,W)},[b,l,xe,d]),nt=o.useCallback(w=>{m(W=>{const se=new Set(W);return se.has(w)?se.delete(w):se.add(w),se})},[]),_e=o.useCallback((w,W)=>{const se=d.find(ze=>ze.id===w);if(!se||se.completed===W)return;const de=d.filter(ze=>ze.id!==w),we={...se,completed:W},Ie=W?[...de,we]:Li(de,we);u(Ie),xe(l,Ie)},[l,xe,d]),q=o.useCallback(w=>{const W=d.filter(se=>se.id!==w);u(W),xe(l,W)},[l,xe,d]),V=o.useCallback(()=>{const w=d.filter(W=>!W.completed);w.length!==d.length&&(u(w),xe(l,w))},[l,xe,d]),be=o.useCallback(w=>{const{active:W,over:se}=w;if(!se||W.id===se.id)return;const de=d.findIndex(ze=>ze.id===W.id),we=d.findIndex(ze=>ze.id===se.id);if(de===-1||we===-1)return;const Ie=Fi(Vu(d,de,we));u(Ie),xe(l,Ie)},[l,xe,d]),Q=Qn(un(lo,{activationConstraint:{distance:8}})),ve=b.slice(0,yn),pe=d.reduce((w,W)=>w+(W.completed?1:0),0),De=o.useCallback(()=>{Ue("chat"),Ae(!1)},[Ue,Ae]),at=o.useCallback((w,W)=>{!e||y!==null||v({todoId:w,todoText:W})},[e,y]),ht=o.useCallback(w=>{if(!z){ce.error("No active session selected");return}De();const W=`\`\`\`md
47
+ ${w}
48
+ \`\`\``;Re(W,"append"),ce.success("Todo sent to current session"),n?.()},[z,n,De,Re]),Ve=o.useCallback(async w=>{if(!e||!N)return;const W=await Vo("plan.todo.visible",{todo_text:N.todoText}),de=[{synthetic:!0,text:await Vo("plan.todo.instructions",{todo_text:N.todoText})}];x(!0),p(N.todoId);try{De();const we=await Y(void 0,e.path,null);if(!we?.id){ce.error("Failed to create session");return}const Ie=we.id,ze=we.directory??e.path;re(we.id,Mt.getState().agents??[]);const lt=ea.getState();lt.saveSessionModelSelection(Ie,w.providerID,w.modelID),w.agent.trim()&&(lt.saveSessionAgentSelection(Ie,w.agent),lt.saveAgentModelForSession(Ie,w.agent,w.providerID,w.modelID),lt.saveAgentModelVariantForSession(Ie,w.agent,w.providerID,w.modelID,w.variant||void 0)),Te(Ie,ze),await G(W,w.providerID,w.modelID,w.agent.trim()||void 0,void 0,void 0,de,w.variant||void 0),ce.success("Todo sent to new session"),v(null),n?.()}catch{ce.error("Failed to send note")}finally{x(!1),p(null)}},[Y,re,n,N,e,De,G,Te]),Me=o.useRef(null),[ke,Le]=o.useState(!1),[dt,bt]=o.useState(null),rt=o.useCallback(async w=>{if(!(!e||dt)){bt(w);try{if(!await Ud(e,w)){ce.error("Failed to delete plan");return}C(se=>se.filter(de=>de.id!==w)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{bt(null)}}},[dt,e]),$=o.useCallback(async()=>{if(!e||ke)return;const w=await Cu({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(w.success&&w.path){Le(!0);try{const W=new URLSearchParams({path:w.path,allowOutsideWorkspace:"true"});w.outsideFileGrant&&W.set("outsideFileGrant",w.outsideFileGrant);const se=await Jt(`/api/fs/read?${W.toString()}`,{cache:"no-store"});if(!se.ok){ce.error("Failed to read plan file");return}const de=await se.text();if(!de.trim()){ce.error("Plan file is empty");return}const we=w.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await qo(e,de,we)){ce.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),ce.success("Plan imported")}catch(W){const se=W instanceof Error?W.message:void 0;ce.error("Failed to read plan file",se?{description:se}:void 0)}finally{Le(!1)}}else w.error==="Native file picker not available"&&Me.current?.click()},[ke,e]),me=o.useCallback(async w=>{if(!(!e||!w)){Le(!0);try{const W=await w.text();if(!W.trim()){ce.error("Plan file is empty");return}const se=w.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await qo(e,W,se)){ce.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),ce.success("Plan imported")}catch(W){const se=W instanceof Error?W.message:void 0;ce.error("Failed to read plan file",se?{description:se}:void 0)}finally{Le(!1)}}},[e]),Ne=o.useCallback(w=>{const W=e?.path?.trim(),se=He?.trim()||W;se&&Ke(se,{mode:"file",targetPath:w.path,dedupeKey:w.path,label:w.title})},[He,Ke,e]);return e?t.jsxs("div",{className:O("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,"/",Qo]})]}),t.jsx(fo,{value:l,onChange:w=>c(w.target.value.slice(0,Qo)),onBlur:je,placeholder:"Capture context, reminders, or links",resizedHeight:Z,onResizeHeightChange:ee,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||pe===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,"/",yn]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Gs,{value:ve,onChange:w=>f(w.target.value.slice(0,yn)),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),$e())},placeholder:"Add a todo",disabled:i,className:"h-8"}),t.jsx("button",{type:"button",onClick:$e,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:O("overflow-y-auto rounded-lg border border-border/60 bg-background/40",te&&"transition-none"),style:d.length<7?void 0:{height:`${E}px`,maxHeight:`${E}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(Jn,{sensors:Q,collisionDetection:Xn,onDragEnd:be,children:t.jsx(co,{items:d.map(w=>w.id),strategy:Na,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(w=>{const W=h.has(w.id);return t.jsx(km,{id:w.id,children:se=>t.jsxs("div",{className:O("flex gap-1.5 px-2.5 py-1.5",W?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:se.setActivatorNodeRef,...se.attributes,...se.listeners,onClick:de=>{de.preventDefault(),de.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 \\"${w.text}\\"`,title:`Reorder \\"${w.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(Qi,{checked:w.completed,onChange:de=>_e(w.id,de),ariaLabel:`Mark \\"${w.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>nt(w.id),className:O("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",W?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",w.completed&&"text-muted-foreground line-through"),title:W?void 0:w.text,"aria-label":W?`Collapse todo \\"${w.text}\\"`:`Expand todo \\"${w.text}\\"`,children:w.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>q(w.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 \\"${w.text}\\"`,title:`Delete \\"${w.text}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:y===w.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 \\"${w.text}\\"`,title:`Send \\"${w.text}\\"`,children:t.jsx(k,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(qt,{align:"end",className:"w-56",children:[t.jsx(wt,{onClick:()=>ht(w.text),children:"Send to current session"}),t.jsx(wt,{onClick:()=>at(w.id,w.text),children:"Send to new session"})]})]})]})]})},w.id)})})})})}),d.length>=7&&t.jsx("div",{className:O("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",te&&"bg-[var(--interactive-border)]"),onPointerDown:We,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:S.length===1?`${S.length} file`:`${S.length} files`})]}),t.jsx("input",{ref:Me,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:w=>{const W=w.target.files?.[0]??null;me(W),w.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:S.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:S.map(w=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>Ne(w),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:w.title}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(w.createdAt).toLocaleDateString("en-US")})]}),t.jsx("button",{type:"button",onClick:()=>{rt(w.id)},disabled:dt===w.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 \\"${w.title}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id))})})]}),t.jsx(wm,{open:N!==null,onOpenChange:w=>{!w&&!g&&v(null)},projectDirectory:e?.path??null,submitting:g,onConfirm:Ve})]}):t.jsx("div",{className:O("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."})})},Dx=({onActionComplete:e})=>{const s=Ot(c=>c.activeProjectId),n=Ot(c=>c.projects),r=Ds(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()||As(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(Nm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Bn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Zr=512*1024,Am=new TextEncoder,Im=new TextDecoder,mr=e=>{const s=Am.encode(e);if(s.byteLength<=Zr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Zr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Im.decode(r),byteLength:r.byteLength}},Fs=(e,s)=>`${e}\0${s}`,gr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},Dm="terminal-store";let Oi=!1,Bi=0;const Dn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Bi+=1,`tab-${Date.now().toString(36)}-${Bi.toString(36)}`),xr=e=>typeof e=="object"&&e!==null,Pm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function Lt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Em=/^Terminal(?: (\d+))?$/,Tm=e=>{let s=0;for(const n of e){const r=Em.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}`},br=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),yr=e=>({tabs:[e],activeTabId:e.id}),ts=(e,s)=>e.tabs.findIndex(n=>n.id===s);let vr=null,wr=null;const Rm=e=>{if(wr&&vr?.sessions===e.sessions&&vr.nextTabId===e.nextTabId)return wr;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 vr={sessions:e.sessions,nextTabId:e.nextTabId},wr=s,s},Mm=()=>{const e=Uu(()=>ku());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))}},Pe=ps()(Ca(ao((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Lt(n);r&&e(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=Dn(),c=br(l,"Terminal");return a.set(r,yr(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=Lt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=Lt(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(Fs(Lt(n),r))??Bn,createTab:n=>{const r=Lt(n);if(!r)return"tab-invalid";const i=Dn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Tm(c?.tabs??[]),b=br(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,b]}):l.set(r,yr(b)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=Lt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||ts(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=Lt(n),l=i.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const b=ts(u,r);if(b<0||u.tabs[b]?.label===l)return c;const f=[...u.tabs];return f[b]={...f[b],label:l},d.set(a,{...u,tabs:f}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=Lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ts(d,r);if(u<0)return l;const b=i?.trim()||null;if(d.tabs[u]?.iconKey===b)return l;const f=[...d.tabs];return f[u]={...f[u],iconKey:b},c.set(a,{...d,tabs:f}),{sessions:c}})},closeTab:(n,r)=>{const i=Lt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ts(c,r);if(d<0)return a;const u=c.tabs.filter(m=>m.id!==r),b=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,m])=>!(m.directory===i&&m.tabId===r))),f=Object.keys(b).length!==Object.keys(a.projectActionRuns).length,y=Fs(i,r),p=a.buffers.has(y)?gr(a.buffers,m=>m===y):null;if(u.length===0){const m=Dn(),S=br(m,"Terminal");return l.set(i,yr(S)),{sessions:l,nextTabId:a.nextTabId+1,...p?{buffers:p}:{},...f?{projectActionRuns:b}:{}}}let h=c.activeTabId;return c.activeTabId===r&&(h=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:h}),{sessions:l,...p?{buffers:p}:{},...f?{projectActionRuns:b}:{}}})},setTabSessionId:(n,r,i)=>{const a=Lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ts(d,r);if(u<0)return l;const b=d.tabs[u],f=i!==null&&b.terminalSessionId!==i,y=i?"running":b.terminalSessionId?"exited":b.lifecycle,p={...b,terminalSessionId:i,lifecycle:y,isConnecting:!1},h=Fs(a,r),m=f&&l.buffers.has(h)?gr(l.buffers,C=>C===h):null,S=[...d.tabs];return S[u]=p,c.set(a,{...d,tabs:S}),{sessions:c,...m?{buffers:m}:{}}})},setTabLifecycle:(n,r,i)=>{const a=Lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ts(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=Lt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ts(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=Lt(n);e(c=>{const d=c.sessions.get(l);if(!d||ts(d,r)<0)return c;const u=Fs(l,r),b=c.buffers.get(u)??Bn;if(b.lastSequence>a)return c;const f=mr(i);if(b.lastSequence===a&&b.byteLength===f.byteLength&&b.chunks.map(h=>h.data).join("")===f.text)return c;const y=c.nextChunkId,p=new Map(c.buffers);return p.set(u,{chunks:f.text?[{id:y,data:f.text,byteLength:f.byteLength}]:[],byteLength:f.byteLength,lastSequence:a}),{buffers:p,nextChunkId:f.text?y+1:y}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=Lt(n);e(d=>{const u=d.sessions.get(c);if(!u||ts(u,r)<0)return d;const b=Fs(c,r),f=d.buffers.get(b)??Bn;if(a!==void 0&&a<=f.lastSequence)return d;const y=d.nextChunkId,p=mr(i),h=l!==void 0&&l!==i?mr(l).text:void 0,m={id:y,data:p.text,...h!==void 0?{replayData:h}:{},byteLength:p.byteLength},S=[...f.chunks,m];let C=f.byteLength+m.byteLength;for(;C>Zr&&S.length>1;){const v=S.shift();if(!v)break;C-=v.byteLength}const N=new Map(d.buffers);return N.set(b,{chunks:S,byteLength:C,lastSequence:a??f.lastSequence}),{buffers:N,nextChunkId:y+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=Lt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const b=ts(u,r);if(b<0)return c;const f=u.tabs[b],y=a.autoOpened??f.previewAutoOpened,p=a.locked??f.previewUrlLocked;if(f.previewUrl===i&&f.previewAutoOpened===y&&f.previewUrlLocked===p)return c;const h=[...u.tabs];return h[b]={...f,previewUrl:i,previewAutoOpened:y,previewUrlLocked:p},d.set(l,{...u,tabs:h}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=Lt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ts(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=Lt(n);e(i=>{const a=new Map(i.sessions);a.delete(r);const l=Fs(r,""),c=gr(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:Dm,storage:Mm(),partialize:Rm,merge:(e,s)=>{if(!xr(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"||!xr(u))continue;const b=Array.isArray(u.tabs)?u.tabs:[],f=[],y=new Map;for(const S of b){if(!xr(S))continue;const C=typeof S.id=="string"?S.id:null;if(!C)continue;const N=Pm(C);N!==null&&(i=Math.max(i,N));const v=N===null?C:Dn();y.set(C,v),f.push({id:v,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(f.length===0)continue;const p=typeof u.activeTabId=="string"?u.activeTabId:null,h=p?y.get(p)??p:null,m=h?f.some(S=>S.id===h):!1;r.set(d,{tabs:f,activeTabId:m?h:f[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"&&!Oi){Oi=!0;const e=Pe.persist,s=()=>{Pe.getState().hasHydrated||Pe.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Fm(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 Lm(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 Sr=["\x1B[0m","\x1B[m"],Om=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},_i=e=>{const s=Om(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},Bm=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...Sr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);Sr.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 Sr)c=c.replaceAll(d,n);return{data:c,carry:l}},_m=(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))}},zm=(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 $m=null;const Um=()=>$m??=_s(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,8])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Gm=2e3,Hm=()=>{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,Gm))]).then(()=>{})},Km=(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))}},nl=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},f)=>{const y=o.useRef(null),p=o.useRef(null),h=o.useRef(null),m=o.useRef(n),S=o.useRef(r),C=o.useRef(null),N=o.useRef(null),v=o.useRef(null),g=o.useRef(""),x=o.useRef(""),A=o.useRef(_i(i.background)),P=o.useRef(!1),D=o.useRef(0),T=o.useRef(b),M=o.useRef(!1),[E,K]=o.useState(0),[Z,ee]=o.useState(0);m.current=n,S.current=r,T.current=b,A.current=_i(i.background),o.useLayoutEffect(()=>{const B=y.current;if(!B)return;const z=Km(B,a,l);N.current=z,z&&S.current(z.cols,z.rows)},[a,l]);const te=o.useCallback(()=>{const B=y.current,z=p.current;if(!B||!z||!h.current||!T.current)return;const Y=B.getBoundingClientRect();if(!(Y.width<24||Y.height<24))try{h.current.fit();const re={cols:z.cols,rows:z.rows};(!C.current||C.current.cols!==re.cols||C.current.rows!==re.rows)&&(C.current=re,S.current(re.cols,re.rows)),M.current||(M.current=!0,K(G=>G+1))}catch{}},[]),_=o.useCallback(()=>{if(P.current||!g.current||!p.current)return;const B=p.current,z=g.current;g.current="";const Y=Bm(z,x.current,A.current);if(x.current=Y.carry,!Y.data){g.current&&_();return}P.current=!0;const re=D.current;B.write(Y.data,()=>{p.current!==B||D.current!==re||(P.current=!1,g.current&&_())})},[]),H=o.useCallback(()=>{v.current=null,g.current="",x.current="",P.current=!1,D.current+=1;const B=p.current;if(!B){ee(z=>z+1);return}try{B.reset();const z=A.current;z&&B.write(`${z}\x1B[2J\x1B[H`)}catch{ee(z=>z+1)}},[]);return o.useEffect(()=>{const B=y.current;if(!B)return;let z=!1,Y=null,re=null,G=null,Te=null,Re=[];const He=()=>{Y&&T.current&&(Y.options.cursorBlink=!0)},Ke=X=>{X.relatedTarget instanceof Node&&B.contains(X.relatedTarget)||Y&&(Y.options.cursorBlink=!1)},Ue=()=>{Y&&T.current&&B.contains(document.activeElement)&&(Y.options.cursorBlink=!0)},Ae=()=>{Y&&(Y.options.cursorBlink=!1)};return B.addEventListener("focusin",He),B.addEventListener("focusout",Ke),window.addEventListener("focus",Ue),window.addEventListener("blur",Ae),Promise.all([Um(),Hm()]).then(([{module:X,ghostty:xe}])=>{if(z)return;Y=new X.Terminal({...Lm(a,l,i,xe,!1),...N.current??{}});const We=new X.FitAddon;Y.loadAddon(We),Y.open(B),p.current=Y,h.current=We,Re=[Y.onData(je=>m.current(je))],re=new ResizeObserver(()=>{G&&clearTimeout(G),G=setTimeout(te,80)}),re.observe(B),te();const Ce=A.current;Ce&&Y.write(`${Ce}\x1B[2J\x1B[H`),Te=requestAnimationFrame(te)}),()=>{z=!0;const X=document.activeElement;X instanceof HTMLElement&&B.contains(X)&&(X.blur(),window.Capacitor?.getPlatform?.()==="android"&&_s(async()=>{const{Keyboard:We}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:We}},__vite__mapDeps([113,114])).then(({Keyboard:We})=>We.hide()).catch(()=>{})),re?.disconnect(),G&&clearTimeout(G),Te!==null&&cancelAnimationFrame(Te),B.removeEventListener("focusin",He),B.removeEventListener("focusout",Ke),window.removeEventListener("focus",Ue),window.removeEventListener("blur",Ae),Re.forEach(xe=>xe.dispose()),Y?.dispose(),p.current=null,h.current=null,C.current=null,v.current=null,g.current="",x.current="",P.current=!1,D.current+=1,M.current=!1}},[te,a,l,Z,i]),o.useEffect(()=>{const B=p.current,z=y.current;!B||!z||(B.options.cursorBlink=b&&document.hasFocus()&&z.contains(document.activeElement))},[b,E]),o.useEffect(()=>{if(!p.current)return;if(s.length===0){v.current!==null&&H();return}const z=v.current;let Y=-1;if(z!==null){for(let Te=s.length-1;Te>=0;Te-=1){const Re=s[Te].id;if(Re===z){Y=Te;break}if(Re<z)break}if(Y<0){H();return}}const re=Y<0,G=Y>=0?s.slice(Y+1):s;g.current+=G.map(Te=>re?Te.replayData??Te.data:Te.data).join(""),v.current=s.at(-1)?.id??null,_()},[s,_,E,H]),o.useEffect(()=>{if(!u||!b)return;const B=requestAnimationFrame(()=>p.current?.focus());return()=>cancelAnimationFrame(B)},[u,b,E,e]),o.useEffect(()=>{const B=y.current;if(!d||!B)return;const z=Y=>{const re=Y;if(!re.isComposing)switch(re.inputType){case"insertText":re.data&&m.current(re.data);break;case"insertLineBreak":case"insertParagraph":m.current("\r");break;case"deleteContentBackward":m.current("");break}};return B.addEventListener("beforeinput",z),()=>B.removeEventListener("beforeinput",z)},[d,E]),o.useEffect(()=>{const B=y.current,z=p.current;if(!d||!B||!z)return;let Y=null,re=null,G="idle",Te=0,Re=0,He=0,Ke=0,Ue=null;const Ae=Math.max(12,l+2),X=()=>{window.Capacitor?.getPlatform?.()==="android"&&_s(async()=>{const{Keyboard:be}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:be}},__vite__mapDeps([113,114])).then(({Keyboard:be})=>be.show()).catch(()=>{})},xe=()=>{re&&(clearTimeout(re),re=null)},We=(V,be)=>{const Q=B.querySelector("canvas");return Q?_m(V,be,Q.getBoundingClientRect(),z.cols,z.rows):null},Ce=(V,be)=>{const Q=B.querySelector("canvas");if(!Q)return;const ve=Q.getBoundingClientRect(),pe=ve.left+(be.column+.5)/z.cols*ve.width,De=ve.top+(be.row+.5)/z.rows*ve.height;Q.dispatchEvent(new MouseEvent(V,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:pe,clientY:De}))},je=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},$e=V=>{V.pointerType!=="touch"||Y!==null||(Y=V.pointerId,G="pending",Te=V.clientX,Re=V.clientY,He=V.clientY,Ke=0,Ue=null,B.setPointerCapture(V.pointerId),re=setTimeout(()=>{if(re=null,Y!==V.pointerId||G!=="pending")return;const be=We(Te,Re);if(!be)return;const Q=z.buffer.active,ve=Math.max(0,Q.length-z.rows-Q.viewportY+be.row),pe=Q.getLine(ve),De=Array.from({length:z.cols},(Ve,Me)=>pe?.getCell(Me)?.getChars()??""),at=zm(De,be.column),ht={column:at.startColumn,row:be.row};Ue={column:at.endColumn,row:be.row},G="selecting",Ce("mousedown",ht),Ce("mousemove",Ue)},350))},nt=V=>{if(Y!==V.pointerId)return;if(G==="selecting"){const ve=We(V.clientX,V.clientY);ve&&(!Ue||ve.column!==Ue.column||ve.row!==Ue.row)&&(Ue=ve,Ce("mousemove",ve)),V.cancelable&&V.preventDefault();return}if(G==="pending"){if(Math.hypot(V.clientX-Te,V.clientY-Re)<8)return;xe(),G="scrolling"}if(G!=="scrolling")return;const be=He-V.clientY;He=V.clientY,Ke+=be;const Q=Math.trunc(Ke/Ae);Q&&(z.scrollLines(Q),Ke-=Q*Ae),V.cancelable&&V.preventDefault()},_e=V=>{if(Y!==V.pointerId)return;const be=G==="pending",Q=G==="selecting";xe(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),Y=null,G="idle",Q&&je(),be&&(z.focus(),X())},q=V=>{if(Y!==V.pointerId)return;const be=G==="selecting";xe(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),Y=null,G="idle",be&&je()};return B.addEventListener("pointerdown",$e),B.addEventListener("pointermove",nt,{passive:!1}),B.addEventListener("pointerup",_e),B.addEventListener("pointercancel",q),()=>{xe(),B.removeEventListener("pointerdown",$e),B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",_e),B.removeEventListener("pointercancel",q)}},[d,l,E]),o.useImperativeHandle(f,()=>({focus:()=>p.current?.focus(),fit:te,getSelection:()=>{const B=p.current,z=B?.getSelectionPosition(),Y=B?.getSelection()??"";return!z||!Y.trim()?null:{text:Y,startLine:z.start.y+1,endLine:z.end.y+1}}}),[te]),t.jsx("div",{ref:y,"data-terminal-owner":"main",className:O("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});nl.displayName="TerminalViewport";const Wm=280,zi=4,Ym=({transform:e})=>({...e,y:0}),Vm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=Zn({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:er.Transform.toString(l),transition:c},className:O("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},qm=({id:e,children:s,className:n})=>t.jsx("div",{className:O("h-full",n),"data-sortable-tab-id":e,children:s}),Qm=({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:f=!0,nonCompositedIndicator:y=!1,className:p})=>{const h=fe(q=>q.isMobile),{isTablet:m}=Ps(),S=h||m,C=o.useRef(null),[N,v]=o.useState({left:!1,right:!1}),g=o.useMemo(()=>e.map(q=>q.id),[e]),x=a==="scrollable",A=l==="default",P=l==="active-pill",T=P||l==="animated",M=A,E=T||M,K=P&&x,Z=T,ee=b??T,te=typeof i=="function",_=te?Vm:qm,H=o.useRef(new Map),[B,z]=o.useState(null),[Y,re]=o.useState(!1),[G,Te]=o.useState(null),Re=o.useRef(!1),He=o.useRef(0),Ke=o.useRef(s),Ue=o.useRef(null),Ae=o.useMemo(()=>{if(!E||!G||!s||G===s)return 0;const q=e.findIndex(be=>be.id===G),V=e.findIndex(be=>be.id===s);return q<0||V<0?0:q>V?zi:-zi},[s,e,G,E]),X=Qn(un(lo,{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,[]),We=o.useCallback((q,V)=>{if(V){H.current.set(q,V);return}H.current.delete(q)},[]),Ce=o.useCallback(()=>{if(!E||!s){z(De=>De===null?De:null);return}const q=C.current,V=H.current.get(s);if(!q||!V){z(De=>De===null?De:null);return}let be=0,Q=0,ve=V;for(;ve&&ve!==q;)be+=ve.offsetLeft,Q+=ve.offsetTop,ve=ve.offsetParent;const pe={left:be,top:Q,width:V.offsetWidth,height:V.offsetHeight};z(De=>xe(De,pe)?De:pe)},[s,xe,E]),je=o.useCallback(()=>{if(!x){v({left:!1,right:!1});return}const q=C.current;if(!q){v({left:!1,right:!1});return}v({left:q.scrollLeft>2,right:q.scrollLeft+q.clientWidth<q.scrollWidth-2})},[x]);o.useEffect(()=>{if(!x){v({left:!1,right:!1});return}const q=C.current;if(!q)return;je(),q.addEventListener("scroll",je,{passive:!0});const V=new ResizeObserver(je);return V.observe(q),()=>{q.removeEventListener("scroll",je),V.disconnect()}},[x,e.length,je]),o.useEffect(()=>{if(!E){z(null);return}Ce();const q=C.current;if(!q)return;const V=new ResizeObserver(()=>{performance.now()-He.current>Wm&&re(!1),Ce()});if(V.observe(q),s){const be=H.current.get(s);be&&V.observe(be)}return()=>{V.disconnect()}},[s,e.length,Ce,E]),o.useLayoutEffect(()=>{Ce()});const $e=g.join("\0");o.useLayoutEffect(()=>{if(!E){Re.current=!1,re(!1);return}const q=Ue.current!==$e;if(Ue.current=$e,!Re.current){Re.current=!0,Ke.current=s;return}const V=Ke.current!==s;if(Ke.current=s,!V||q){re(!1);return}He.current=performance.now(),re(!0)},[s,$e,E]),o.useEffect(()=>{if(!x||!s)return;const q=C.current;if(!q)return;const V=window.requestAnimationFrame(()=>{const be=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),Q=q.querySelector(`[data-sortable-tab-id="${be}"]`);Q&&(Q.scrollIntoView({block:"nearest",inline:"nearest"}),je())});return()=>{window.cancelAnimationFrame(V)}},[s,x,e.length,je]);const nt=o.useCallback(q=>{if(!i)return;const{active:V,over:be}=q;!be||V.id===be.id||i(String(V.id),String(be.id))},[i]),_e=t.jsxs("div",{className:O("relative flex h-full min-w-0 flex-1",p),children:[x&&N.left?t.jsx("div",{className:O("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",T?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,x&&N.right?t.jsx("div",{className:O("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",T?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:C,className:O("relative flex h-full min-w-0 flex-1",T?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",T&&"@container/pill-tabs",T&&"pill-tabs__track",T&&(c??"gap-0.5 py-0.5"),M&&"items-center overflow-y-hidden",Z&&"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",x?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:x?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[T&&B?t.jsx("div",{className:O("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)]",ee&&Y&&(y?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:y?{left:`${B.left+Ae}px`,top:`${B.top}px`,width:`${B.width}px`,height:`${B.height}px`}:{transform:`translate3d(${B.left+Ae}px, ${B.top}px, 0)`,width:`${B.width}px`,height:`${B.height}px`}}):null,M&&B?t.jsx("div",{className:O("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",Y&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${B.left+Ae}px, 0, 0)`,width:`${B.width}px`},"aria-hidden":!0}):null,e.map(q=>{const V=q.id===s,be=u&&T&&!V&&!!q.icon,Q=!be,ve=!!q.icon,pe=u&&T&&V&&!x&&!K,De=q.closable!==!1&&!!r,at=De&&!!q.icon,ht=x||K?void 0:T?pe?"flex-none basis-auto":h?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",Ve=De?ke=>{ke.button===1&&(ke.preventDefault(),ke.stopPropagation(),r?.(q.id))}:void 0,Me=De?ke=>{ke.button===1&&ke.preventDefault()}:void 0;return t.jsx(_,{id:q.id,className:ht,children:t.jsxs("div",{ref:ke=>We(q.id,ke),onAuxClick:Ve,onMouseDown:Me,className:O("group flex h-full min-w-0 flex-nowrap items-center",x||K?"shrink-0":T?"w-full":"w-full min-w-0",T?"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":be?q.title??q.label:void 0,onClick:()=>n(q.id),onPointerDown:E?()=>{re(!0),Te(q.id)}:void 0,onPointerUp:E?()=>Te(null):void 0,onPointerLeave:E?()=>Te(null):void 0,onPointerCancel:E?()=>Te(null):void 0,className:O(T?"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",T&&f?"lowercase":null,T&&(be?"gap-0":"gap-1.5"),T?K?"shrink-0 whitespace-nowrap px-3 text-center":x?"max-w-56 shrink-0 px-3 text-center":be?"px-2 !min-w-0 text-center":pe?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":x?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",T?d??(P?h?"h-[38px]":"h-[31px]":"h-7"):null,T?V?"text-foreground":"text-muted-foreground hover:text-foreground":null,T?"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:T?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:O("flex items-center justify-center transition-opacity",at&&(S?"opacity-0":"group-hover:opacity-0")),children:q.icon}),at?t.jsx("span",{role:"button",tabIndex:-1,className:O("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",S?"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:O("flex min-w-0 flex-nowrap items-center gap-1.5",!x&&"justify-center"),children:[ve?t.jsxs("span",{className:O("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:O("flex items-center justify-center transition-opacity",at&&(S?"opacity-0":"group-hover:opacity-0")),children:q.icon}),at?t.jsx("span",{role:"button",tabIndex:-1,className:O("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",S?"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})]})}),De&&!at?t.jsx("button",{type:"button",onPointerDown:ke=>{ke.stopPropagation()},onClick:ke=>{ke.stopPropagation(),r?.(q.id)},className:O("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",T?"-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",T?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 te?t.jsxs(Jn,{sensors:X,collisionDetection:Xn,onDragEnd:nt,modifiers:[Ym],children:[t.jsx(co,{items:g,strategy:qu,children:_e}),t.jsx(ka,{dropAnimation:null})]}):_e},Jm="\x1B",Xm=new RegExp(`${Jm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Zm=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,eg=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,tg=/Serving HTTP on .*? port (\d{2,5})/i,sg=new Set([".",",",";",":","!","?"]),ng=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(sg.has(n)){s=s.slice(0,-1);continue}break}return s},$i=e=>{let s=ng(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},rg=e=>{if(!e)return null;const s=e.replace(Xm,""),n=s.match(tg);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(!eg.test(i))continue;const a=Array.from(i.matchAll(Zm));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL($i(c[1])).port}catch{return!1}});return $i((l??a[0])[1])}return null},og=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 Jt("/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)}},ig={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ag=(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 ig[e]},rl=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},lg=(e,s)=>e&&(s==="ctrl"?rl(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Ui={cols:80,rows:24},Px=({visible:e})=>{const{terminal:s,runtime:n}=Wn(),{currentTheme:r}=fa(),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}=Hd(),l=fe(L=>L.terminalFontSize),c=fe(L=>L.terminalShell),d=fe(L=>L.terminalLoginShells.includes(L.terminalShell)),{isMobile:u,isTablet:b,hasTouchOnlyPointer:f}=Ps(),y=u||b,p=(y||f)&&n.platform==="web",h=!0,m=fe(L=>L.showTerminalQuickKeysOnDesktop),S=y||m,C=Oe(L=>L.currentSessionId),N=Oe(L=>L.newSessionDraft),v=C!==null||N?.open===!0,g=Kd()??null,x=Pe(L=>g?L.sessions.get(g):void 0),A=Pe(L=>L.hasHydrated),P=Pe(L=>L.ensureDirectory),D=Pe(L=>L.createTab),T=Pe(L=>L.setActiveTab),M=Pe(L=>L.closeTab),E=Pe(L=>L.setTabSessionId),K=Pe(L=>L.setTabLifecycle),Z=Pe(L=>L.setConnecting),ee=Pe(L=>L.appendToBuffer),te=Pe(L=>L.replaceBuffer),_=Pe(L=>L.setTabPreviewUrl),H=oa(L=>L.addDraft),B=fe(L=>L.openContextPreview),z=o.useMemo(()=>x?x.activeTabId??x.tabs[0]?.id??null:null,[x,h]),Y=o.useMemo(()=>{if(x)return z?x.tabs.find(L=>L.id===z)??x.tabs[0]:x.tabs[0]},[x,z]),re=o.useMemo(()=>(x?.tabs??[]).map(L=>({icon:(()=>{const oe=L.iconKey?rn[L.iconKey]??"terminal":"terminal";return t.jsx(k,{name:oe,className:"h-4 w-4"})})(),id:L.id,label:L.label,title:L.label,closeLabel:"Close tab"})),[x?.tabs]),G=Y?.terminalSessionId??null,Te=Y?.lifecycle??"idle",Re=Pe(L=>g&&z?L.getBuffer(g,z).chunks:Bn.chunks),He=Y?.isConnecting??!1,Ke=Y?.previewUrl??null,[Ue,Ae]=o.useState(null),[X,xe]=o.useState(!1),[We,Ce]=o.useState(!1),[je,$e]=o.useState(null),[nt,_e]=o.useState(!1),q=o.useRef(null),V=o.useRef(null),be=o.useRef(z),Q=o.useRef(G),ve=o.useRef(g),pe=o.useRef(null),De=o.useRef(null),at=o.useRef(new Set),ht=o.useRef(""),Ve=o.useRef(new Set),Me=o.useRef(0),ke=o.useCallback(()=>{ht.current="",Ve.current.clear(),Me.current+=1},[]),Le=o.useCallback(()=>{p||typeof document<"u"&&!document.hasFocus()||pe.current?.focus()},[p]),dt=o.useCallback(()=>{p||pe.current?.focus()},[p]),rt=fe(L=>L.activeMainTab)==="terminal",$=e??rt,[me,Ne]=o.useState($);o.useEffect(()=>{$&&Ne(!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(()=>{be.current=z,ke()},[z,ke]),o.useEffect(()=>{ve.current=g},[g]),o.useEffect(()=>{!S&&je!==null&&$e(null)},[S,je,$e]),o.useEffect(()=>{!G&&je!==null&&$e(null)},[G,je,$e]);const w=o.useCallback(()=>{q.current?.(),q.current=null,V.current=null,Ce(!1)},[]);o.useEffect(()=>()=>{w(),Q.current=null},[w]);const W=o.useCallback((L,oe,he)=>{if(!he)return;const Xe=`${ht.current}${he}`.replace(/\r\n|\r/g,`
50
+ `),ye=Xe.split(`
51
+ `),Qe=Xe.endsWith(`
52
+ `)?ye.join(`
53
+ `):ye.slice(0,-1).join(`
54
+ `);if(ht.current=Xe.endsWith(`
55
+ `)?"":(ye[ye.length-1]??"").slice(-1024),!Qe)return;const ut=rg(Qe);if(!ut||Ve.current.has(ut))return;const At=Me.current;Ve.current.add(ut),og(ut).then(Rt=>{if(Ve.current.delete(ut),!Rt||Me.current!==At)return;const It=Pe.getState().getDirectoryState(L)?.tabs.find(Gt=>Gt.id===oe);!It||It.previewUrlLocked||It.previewUrl===ut||_(L,oe,ut,{locked:!1,autoOpened:!1})})},[_]),se=o.useCallback((L,oe,he)=>{if(V.current===he)return;w(),V.current=he;const Xe=s.connect(he,{onEvent:ye=>{if(V.current===he)switch(ye.type){case"snapshot":{Z(L,oe,!1),Ae(null),xe(!1),Ce(!1),Le(),te(L,oe,ye.data??"",ye.sequence??0),W(L,oe,ye.data??""),ye.status==="exited"&&K(L,oe,"exited");break}case"reconnecting":{Ae(null),xe(!1),Ce(!0);break}case"data":{ye.data&&(ee(L,oe,ye.data,ye.sequence,ye.replayData),W(L,oe,ye.data));break}case"exit":{const Qe=typeof ye.exitCode=="number"?ye.exitCode:null,ut=typeof ye.signal=="number"?ye.signal:null,Rt=!!Pe.getState().getDirectoryState(L)?.tabs.find(It=>It.id===oe)?.label?.startsWith("Action:");ee(L,oe,`\\r\\n[Process exited${Qe!==null?` with code ${Qe}`:""}${ut!==null?` (signal ${ut})`:""}]\\r\\n`),K(L,oe,"exited"),Z(L,oe,!1),Ae(Rt?null:"Terminal session ended"),xe(!1),Ce(!1),w();break}}},onError:(ye,Qe)=>{if(V.current===he){if(!Qe){Ae(null),xe(!1);return}if(Ce(!1),ye.code==="SESSION_NOT_FOUND"&&!Pe.getState().getDirectoryState(L)?.tabs.find(At=>At.id===oe)?.label?.startsWith("Action:")){Ae(null),xe(!1),Z(L,oe,!1),E(L,oe,null),K(L,oe,"idle"),w();return}Ae(`Connection failed: ${ye.message}`),xe(!0),Z(L,oe,!1),K(L,oe,"exited"),E(L,oe,null),w()}}});q.current=()=>{Xe.close(),V.current=null}},[ee,te,w,Le,W,Z,K,E,s]);o.useEffect(()=>{let L=!1;if(!A||!me)return;if(!g){Ae(v?"No working directory available for terminal.":"Select a session to open the terminal."),w();return}return(async()=>{const he=g;if(!ve.current||ve.current!==he)return;if(!Pe.getState().getDirectoryState(he)){P(he);return}const ye=Pe.getState().getDirectoryState(he);if(!ye||ye.tabs.length===0)return;const Qe=ye.activeTabId??ye.tabs[0]?.id??null;if(!Qe)return;const ut=ye.tabs.find(Ct=>Ct.id===Qe)??ye.tabs[0],At=ut?.terminalSessionId??null,Rt=ut?.lifecycle??"idle",It=!!ut?.label?.startsWith("Action:"),Gt=Pe.getState().getBuffer(he,Qe),_t=Gt.byteLength>0||Gt.chunks.length>0;if(!At){if(Rt==="exited"){Z(he,Qe,!1);return}if(It&&_t){Z(he,Qe,!1);return}const Ct=`${he}\0${Qe}`;if(at.current.has(Ct))return;const Ft=De.current??Ui;at.current.add(Ct),Ae(null),xe(!1),Ce(!1),Z(he,Qe,!0);try{const U=await s.createSession({cwd:he,sessionId:Qe,cols:Ft.cols,rows:Ft.rows,shell:c,loginShell:d,...i.current}),ne=!L&&ve.current===he&&be.current===Qe;if(!Pe.getState().getDirectoryState(he)?.tabs.find(ge=>ge.id===Qe)){try{await s.close(U.sessionId)}catch{}return}if(E(he,Qe,U.sessionId),!ne)return;const ue=De.current;ue&&(ue.cols!==Ft.cols||ue.rows!==Ft.rows)&&s.resize({sessionId:U.sessionId,...ue}).catch(()=>{});return}catch(U){const ne=Pe.getState().getDirectoryState(he)?.tabs.find(le=>le.id===Qe);if(!ne||ne.terminalSessionId||(Z(he,Qe,!1),ve.current!==he||be.current!==Qe))return;Ae(U instanceof Error?U.message:"Failed to start terminal session"),xe(!0),Ce(!1);return}finally{at.current.delete(Ct)}}!At||L||(Q.current=At,se(he,Qe,At))})(),()=>{L=!0,Q.current=null,w()}},[v,g,G,Te,z,me,h,A,P,Z,K,E,se,w,s,d,c]),o.useEffect(()=>{if(!$||p)return;if(typeof window>"u"){Le();return}const L=window.requestAnimationFrame(()=>{Le()});return()=>{window.cancelAnimationFrame(L)}},[z,Le,$,p]);const de=o.useCallback(async()=>{if(!g||nt)return;const L=Pe.getState().getDirectoryState(g),oe=z??L?.activeTabId??L?.tabs[0]?.id??null;if(!oe)return;const he=L?.tabs.find(Xe=>Xe.id===oe)?.terminalSessionId??null;if(!(!he||!s.restartSession)){_e(!0),Ae(null),xe(!1),Ce(!1),w(),ke();try{const Xe=De.current??Ui,ye=await s.restartSession(he,{cwd:g,shell:c,loginShell:d,...Xe,...i.current});if(Pe.getState().getDirectoryState(g)?.tabs.find(ut=>ut.id===oe)?.terminalSessionId!==he||(E(g,oe,ye.sessionId),K(g,oe,"running"),ve.current!==g||be.current!==oe))return;Q.current=ye.sessionId,se(g,oe,ye.sessionId)}catch(Xe){if(Pe.getState().getDirectoryState(g)?.tabs.find(Qe=>Qe.id===oe)?.terminalSessionId!==he||ve.current!==g||be.current!==oe)return;Ae(Xe instanceof Error?Xe.message:"Failed to restart terminal"),xe(!1),Ce(!1),Q.current=he,se(g,oe,he)}finally{_e(!1)}}},[z,w,g,h,nt,ke,K,E,se,s,d,c]),we=o.useCallback(async()=>{await de()},[de]),Ie=o.useCallback(()=>{if(!g)return;const L=D(g);T(g,L),Ae(null),xe(!1),Ce(!1),w()},[D,w,g,T]),ze=o.useCallback(()=>{const L=pe.current?.getSelection(),oe=C??(N?.open?"draft":null);!L||!oe||!Y||!g||H({directory:g,sessionKey:oe},{source:"terminal",fileLabel:Y.label,startLine:L.startLine,endLine:L.endLine,code:L.text,language:Y.terminalSessionId??Y.id,text:""})},[Y,H,C,g,N?.open]),lt=o.useCallback(L=>{g&&(T(g,L),Ae(null),xe(!1),Ce(!1),w())},[w,g,T]),St=o.useCallback(L=>{if(!g)return;L===z&&w(),Ae(null),xe(!1),Ce(!1);const oe=Pe.getState().getDirectoryState(g)?.tabs.find(he=>he.id===L)?.terminalSessionId;(async()=>{oe&&await s.close(oe),M(g,L)})().catch(he=>Ae(he instanceof Error?he.message:"Terminal session ended"))},[z,M,w,g,s]),Je=o.useCallback(L=>{if(!L||We)return;let oe=L,he=!1;je&&L.length>0&&(oe=lg(L,je),he=!0);const Xe=Q.current;Xe&&(s.sendInput(Xe,oe).catch(ye=>{We||Ae(ye instanceof Error?ye.message:"Failed to send input")}),he&&($e(null),dt()))},[je,dt,We,$e,s]),ct=o.useCallback((L,oe)=>{const he=De.current;if((!he||he.cols!==L||he.rows!==oe)&&(De.current={cols:L,rows:oe}),!$)return;const Xe=Q.current;Xe&&s.resize({sessionId:Xe,cols:L,rows:oe}).catch(()=>{})},[$,s]),pt=o.useCallback(L=>{$e(oe=>oe===L?null:L),dt()},[dt,$e]),Fe=o.useCallback(L=>{const oe=ag(L,je);oe&&(Je(oe),$e(null),dt())},[je,dt,Je,$e]),Ge=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),mt=o.useCallback(L=>{if(L.repeat)return;const oe=L.key;if(!oe||oe==="Control"||oe==="Meta"||oe==="Alt"||oe==="Shift")return;const he=oe.length===1?oe.toLowerCase():oe;if(he in Ge){L.preventDefault(),L.stopPropagation(),Fe(Ge[he]);return}if(je!=="ctrl")return;const Xe=L.code??"",ye=oe.length===1&&/[a-zA-Z]/.test(oe)?oe.toUpperCase():Xe.startsWith("Key")&&Xe.length===4?Xe.slice(3).toUpperCase():null;if(ye&&ye.length===1&&ye>="A"&&ye<="Z"){const Qe=rl(ye);if(!Qe)return;L.preventDefault(),L.stopPropagation(),Je(Qe),$e(null),dt()}},[je,dt,Fe,Je,Ge,$e]);o.useEffect(()=>{if(!(!S||!je||!G))return window.addEventListener("keydown",mt),()=>window.removeEventListener("keydown",mt)},[je,mt,S,G]);const Tt=o.useMemo(()=>{const L=Js[lr].stack;if(typeof window>"u")return(Js[a]??Js[lr]).stack;const he=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return he&&he.trim().length>0?he.trim():(Js[a]??Js[lr]).stack??L},[a]),Bt=o.useMemo(()=>Fm(r),[r]),vt=`${g??"no-dir"}::${z??"no-tab"}`;if(o.useEffect(()=>{if(!$||p)return;const L=pe.current;if(!L)return;const oe=()=>{L.fit()};if(typeof window<"u"){const he=window.requestAnimationFrame(()=>{oe(),Le()}),Xe=[220,400].map(ye=>window.setTimeout(oe,ye));return()=>{window.cancelAnimationFrame(he),Xe.forEach(ye=>window.clearTimeout(ye))}}oe()},[Le,$,p,vt,G]),o.useEffect(()=>{if(!$||!p)return;let L=null;const oe=()=>{L!==null&&window.cancelAnimationFrame(L),L=window.requestAnimationFrame(()=>{L=null,pe.current?.fit()})};return window.addEventListener("oc:keyboard-settled",oe),()=>{window.removeEventListener("oc:keyboard-settled",oe),L!==null&&window.cancelAnimationFrame(L)}},[$,vt,p]),!v)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(!g)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:de,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const jt=!G||He||nt||We,kt=me,F=y?"lg":"xs",Se=y?"w-10 p-0":"w-9 p-0",Be=L=>{y&&L.preventDefault()},ot=t.jsxs(t.Fragment,{children:[t.jsx(qe,{type:"button",size:F,variant:"outline",onPointerDown:Be,onClick:()=>Fe("esc"),disabled:jt,children:"Esc"}),t.jsxs(qe,{type:"button",size:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("tab"),disabled:jt,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:F,variant:"chip","aria-pressed":je==="ctrl",className:y?"px-3":"px-2",onPointerDown:Be,onClick:()=>pt("ctrl"),disabled:jt,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:F,variant:"chip","aria-pressed":je==="alt",className:y?"px-3":"px-2",onPointerDown:Be,onClick:()=>pt("alt"),disabled:jt,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:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("arrow-up"),disabled:jt,children:[t.jsx(k,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(qe,{type:"button",size:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("arrow-left"),disabled:jt,children:[t.jsx(k,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(qe,{type:"button",size:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("arrow-down"),disabled:jt,children:[t.jsx(k,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(qe,{type:"button",size:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("arrow-right"),disabled:jt,children:[t.jsx(k,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(qe,{type:"button",size:F,variant:"outline",className:Se,onPointerDown:Be,onClick:()=>Fe("enter"),disabled:jt,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:O("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",y?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[x?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:O("min-w-0 flex-1",y?"h-8":"h-7"),children:t.jsx(Qm,{items:re,activeId:z,onSelect:lt,onClose:St,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(qe,{type:"button",size:"xs",variant:"ghost",className:O("shrink-0",y?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ie,title:"New tab",children:t.jsx(k,{name:"add",className:`${y?"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:()=>{de()},disabled:nt,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:ze,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(k,{name:"attachment-2",className:"h-4 w-4"})}),Ke?t.jsxs(qe,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{g&&B(g,Ke)},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,!y&&S&&h&&x?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:ot}):null,!y&&S&&!x?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:ot}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Bt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:kt?t.jsx(nl,{ref:L=>{pe.current=L},sessionKey:vt,chunks:Re,onInput:Je,onResize:ct,theme:Bt,fontFamily:Tt,fontSize:l,enableTouchScroll:p,autoFocus:$,isVisible:$},vt):null}),!We&&Ue&&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:Ue}),X&&y&&t.jsx(qe,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:we,disabled:nt,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),y&&S?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:ot})}):null]})},cg=ps(()=>({statusById:new Map})),Ex=()=>{ba(),ha()},Tx=e=>{Oe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),fe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ba(),Pe.getState().clearAll(),Ds.getState().resetForRuntimeSwitch(),Mt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),Ot.getState().resetForRuntimeSwitch(),Wd.getState().resetForRuntimeSwitch(),cg.setState({statusById:new Map}),Yd(),Vd(),Qu.getState().reset(),Nu.getState().resetForRuntimeSwitch(),ra.getState().resetForRuntimeSwitch(e.runtimeKey),dp.getState().resetForRuntimeSwitch(),zt.getState().resetForRuntimeSwitch(e.runtimeKey),Au.getState().resetForRuntimeSwitch(e.runtimeKey),Oe.getState().restoreForRuntimeSwitch(e.runtimeKey),fe.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=fe.getState();Ur({sessionId:Oe.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),ha()},dg=48,ug=96,Wt=(e,...s)=>{try{e?.(...s)}catch{}},jr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Rx=(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"?ug:dg;let d=!1,u=!1,b=!1,f=null,y=!1,p=0,h=0,m=0,S=0;const C=()=>{d=!1,u=!1,b=!1,f=null},N=()=>{const T=n.current,M=f,E=y;u&&M&&(Wt(M==="left"?T.onLeftProgress:T.onRightProgress,E?1:0),Wt(T.onDragEnd,M,E)),C()},v=()=>{N(),u||C()},g=T=>{const M=n.current;if(M.enabled===!1){u&&f?N():C();return}if(T.touches.length!==1){u&&f?N():C();return}const E=T.touches[0],K=i.getBoundingClientRect(),Z=i.clientWidth,ee=!!M.leftOpen,te=!!M.rightOpen,_=H=>ym(H,i);if(ee||te){if(_(T.target)){C();return}if(ee&&te){const H=E.clientX<=K.left+c;E.clientX>=K.right-c?(f="right",y=!0):H?(f="left",y=!0):(f=ee?"left":"right",y=!0)}else ee?(f="left",y=!0):(f="right",y=!0);S=jr(f==="left"?M.leftWidth:M.rightWidth,Z),S<10&&(S=Z||window.innerWidth||320),S<10&&(S=320),d=!0}else{if(_(T.target)){C();return}f=null,y=!1,S=0,d=!0}p=E.clientX,h=E.clientY,m=Date.now(),u=!1,b=!1},x=T=>{if(!d)return;if(T.touches.length!==1){v();return}const M=T.touches[0],E=M.clientX-p,K=M.clientY-h;if(!b){if(Math.abs(E)<Ti&&Math.abs(K)<Ti)return;if(Math.abs(K)>Math.abs(E)*Zs){C();return}if(!f){const te=n.current;f=E>0?"left":"right",S=jr(f==="left"?te.leftWidth:te.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(f==="left"){if(!y&&E<=0){C();return}if(y&&E>=0){C();return}}else{if(!y&&E>=0){C();return}if(y&&E<=0){C();return}}b=!0,u=!0,Wt(n.current.onDragStart,f)}if(!u)return;T.cancelable&&T.preventDefault();const Z=n.current,ee=Ri(f,y,E,S);Wt(f==="left"?Z.onLeftProgress:Z.onRightProgress,ee)},A=(T,M)=>{if(!d){C();return}const E=T-p,K=M-h;if(!f&&!y&&Math.abs(E)>=Ln&&Math.abs(K)<=Math.abs(E)*Zs){const B=n.current;f=E>0?"left":"right",S=jr(f==="left"?B.leftWidth:B.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(!f){C();return}const Z=Math.max(1,Date.now()-m),ee=n.current;if(!u){const B=Math.abs(E),z=Math.abs(K);B>=Ln&&z<=B*Zs?f==="left"&&!y&&E>0?(Wt(ee.onLeftProgress,1),Wt(ee.onLeftOpen)):f==="right"&&!y&&E<0?(Wt(ee.onRightProgress,1),Wt(ee.onRightOpen)):Wt(f==="left"?ee.onLeftProgress:ee.onRightProgress,y?1:0):Wt(f==="left"?ee.onLeftProgress:ee.onRightProgress,y?1:0);const Y=f;C(),Wt(ee.onDragEnd,Y);return}const te=Ri(f,y,E,S),_=xm({side:f,isOpenAtStart:y,dx:E,dt:Z,progress:te}),H=f;Wt(H==="left"?_?ee.onLeftOpen:ee.onLeftClose:_?ee.onRightOpen:ee.onRightClose),C(),Wt(ee.onDragEnd,H,_)},P=T=>{const M=T.changedTouches[0];if(!M){C();return}const E=M.clientX-p,K=M.clientY-h;d&&(u||Math.abs(E)>=Ln&&Math.abs(K)<=Math.abs(E)*Zs)&&T.cancelable&&T.preventDefault(),A(M.clientX,M.clientY)},D=()=>{v()};return i.addEventListener("touchstart",g,{passive:!0}),i.addEventListener("touchmove",x,{passive:!1}),i.addEventListener("touchend",P,{passive:!1}),i.addEventListener("touchcancel",D,{passive:!0}),()=>{try{u&&f&&N()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",g),i.removeEventListener("touchmove",x),i.removeEventListener("touchend",P),i.removeEventListener("touchcancel",D)}},[e,r])};function Mx({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 Gi({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 Cr=()=>ks.filter(e=>Lr.has(e.id)).map(e=>({...ya(e)})),fg=()=>{if(typeof window>"u")return Or;const e=window.localStorage.getItem("openInAppId");return e&&Fr(e)?e:Or};let kr=!1,Ls=!1,xs=!1,bs=0,on=null;const Hi=()=>{on&&(clearTimeout(on),on=null)},Ss=ps()((e,s)=>({selectedAppId:fg(),availableApps:Cr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(kr||typeof window>"u")return;kr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Cr(),hasLoadedApps:u});return}const b=new Set(d.map(h=>h.name)),f=new Map(d.map(h=>[h.name,h.iconDataUrl??void 0])),p=ks.filter(h=>b.has(h.appName)||Lr.has(h.id)).map(h=>({...ya(h),iconDataUrl:f.get(h.appName)}));e({availableApps:p,hasLoadedApps:!0})},r=async d=>{if(!fs()||!dn()||Ls||s().hasLoadedApps&&!d)return;const b=ks.map(f=>f.appName);Hi(),Ls=!0,xs=!1,e({isScanning:!0});try{const{apps:f,success:y,hasCache:p,isCacheStale:h}=await ei(b,d),m=y&&!p&&f.length===0&&bs<3;if(e({isCacheStale:p?h:!1}),n(f,y?!m:!1),y){if(m){const C=[800,1600,3200][bs]??3200;bs+=1,xs=!0,on=setTimeout(()=>{r()},C);return}bs=0,xs=!1;return}if(bs<3){const C=[1e3,3e3,7e3][bs]??7e3;bs+=1,xs=!0,on=setTimeout(()=>{r()},C)}}finally{Ls=!1,xs||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,b=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Fr(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)&&(bs=3,xs=!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(kr||s().initialize(),!fs()||!dn()||Ls||s().hasLoadedApps&&!n)return;const i=ks.map(a=>a.appName);Hi(),n&&e({hasLoadedApps:!1}),Ls=!0,xs=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await ei(i,n),d=new Set(a.map(y=>y.name)),u=new Map(a.map(y=>[y.name,y.iconDataUrl??void 0])),f=ks.filter(y=>d.has(y.appName)||Lr.has(y.id)).map(y=>({...y,iconDataUrl:u.get(y.appName)}));e({availableApps:f.length>0?f:Cr(),hasLoadedApps:f.length>0,isCacheStale:l?c:!1})}finally{Ls=!1,xs||e({isScanning:!1})}},selectApp:async n=>{Fr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await no({openInAppId:n}))}})),hg="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",pg="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",Nr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?hg:e.id==="terminal"?pg:void 0}),Ki=({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:O("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},mg=({directory:e,className:s})=>{const n=Ss(h=>h.selectedAppId),r=Ss(h=>h.availableApps),i=Ss(h=>h.isCacheStale),a=Ss(h=>h.isScanning),l=Ss(h=>h.initialize),c=Ss(h=>h.loadInstalledApps),d=Ss(h=>h.selectApp);o.useEffect(()=>{l()},[l]);const u=fs()&&dn(),b=o.useMemo(()=>{const h=r.find(m=>m.id===n)??r.find(m=>m.id===Or)??r[0]??ks[0];return Nr(h||ks[0])},[r,n]);if(!u||!e||r.length===0)return null;const f=async h=>{await Iu(e,h.id,h.appName)||await ga(e,h.appName)},y=async h=>{await d(h.id),await f(h)},p=async()=>{(await an(e)).ok&&ce.success("Path copied to clipboard")};return t.jsxs("div",{className:O("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:()=>{f(b)},className:O("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(Ki,{label:b.label,iconDataUrl:b.iconDataUrl,fallbackIconDataUrl:b.fallbackIconDataUrl})}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O("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(qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(wt,{className:"flex items-center gap-2",onClick:()=>{p()},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(Hs,{}),r.map(h=>{const m=Nr(h);return t.jsxs(wt,{className:"flex items-center gap-2",onClick:()=>{y(h)},children:[t.jsx(Ki,{label:h.label,iconDataUrl:h.iconDataUrl,fallbackIconDataUrl:m.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:h.label}),b.id===h.id?t.jsx(k,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},h.id)}),i?t.jsxs(wt,{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]})]})]})},gg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],xg=["dev","start","preview","serve"];async function bg(e,s,n){if(!e)return null;const r=wg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=Sg(n);if(i){const a=await jg(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 yg(e)){const i=await vg(),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 yg(e){const s=`${e}/index.html`,n=await Kn(s,e);return typeof n=="string"&&n.trim().length>0}async function vg(){try{const e=await Jt("/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 wg(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(xg.some(i=>n.includes(i)))return s}return null}function Sg(e){for(const{pattern:s}of gg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function jg(e){const s=await Kn(`${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 Kn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function Kn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await Jt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=ro()?.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 Jt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Cg(e){try{const s=await Kn(`${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 kg=(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)}),Ng="\x1B",Ag=new RegExp(`${Ng}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ig=/https?:\/\/[^\s<>'"`]+/gi,Qt="__pichamber_auto_discover_preview__",Dg=15e3,Pg=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},Eg=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}},Tg=e=>{const n=e.replace(Ag,"").match(Ig);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||"/",f=b.split("/").filter(Boolean).length,y=b==="/"||b==="",p=!!(c.search||c.hash);let h=0;return u&&(h+=50),y&&(h+=30),h-=Math.min(f*5,20),p&&(h-=10),h};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Wi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=fa(),{terminal:l}=Wn(),{isMobile:c}=Ps(),d=o.useMemo(()=>fs(),[]),u=$n($=>$.instances),b=$n($=>$.load),f=fe($=>$.terminalShell),y=fe($=>$.terminalLoginShells.includes($.terminalShell)),p=fe($=>$.setSettingsPage),h=fe($=>$.setSettingsDialogOpen),m=fe($=>$.setSettingsProjectsSelectedId),S=fe($=>$.openContextPreview),C=Pe($=>$.ensureDirectory),N=Pe($=>$.setTabLabel),v=Pe($=>$.setTabIconKey),g=Pe($=>$.setActiveTab),x=Pe($=>$.setConnecting),A=Pe($=>$.setTabSessionId),P=Pe($=>$.setTabPreviewUrl),D=Pe($=>$.projectActionRuns),T=Pe($=>$.setProjectActionRun),M=Pe($=>$.updateProjectActionRunStatus),E=Pe($=>$.removeProjectActionRun),[K,Z]=o.useState([]),[ee,te]=o.useState(null),[_,H]=o.useState(!1),B=o.useRef({}),z=o.useRef({}),Y=o.useRef({}),re=o.useRef({}),G=o.useRef(new Set),Te=o.useRef(0),Re=e?.id??null,He=e?.path??"",Ke=o.useMemo(()=>Re?{id:Re,path:He}:null,[Re,He]);o.useEffect(()=>{d&&b().catch(()=>{})},[d,b]);const Ue=o.useCallback(async $=>{await qi($)},[]),Ae=o.useCallback(async()=>{if(!Ke)return;const $=Te.current+1;Te.current=$,H(!0);try{const me=await Ar(Ke);if(Te.current!==$)return;const Ne=me.actions;Z(Ne),te(w=>w===Qt||w&&Ne.some(W=>W.id===w)?w:null)}catch{if(Te.current!==$)return}finally{Te.current===$&&H(!1)}},[Ke]),X=o.useMemo(()=>La(s||Ke?.path||""),[s,Ke?.path]),xe=o.useMemo(()=>ee?K.find($=>$.id===ee)??null:null,[K,ee]),We=o.useMemo(()=>({id:Qt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Ce=!c,je=o.useMemo(()=>Ce?[We,...K]:K,[K,We,Ce]);o.useEffect(()=>{Ae()},[Ae]),o.useEffect(()=>{if(typeof window>"u")return;const $=me=>{const Ne=me.detail;Re&&(Ne?.projectId&&Ne.projectId!==Re||Ae())};return window.addEventListener(Kr,$),()=>{window.removeEventListener(Kr,$)}},[Ae,Re]),o.useEffect(()=>{ee&&(ee===Qt&&Ce||K.some($=>$.id===ee)||te(null))},[K,Ce,ee]),o.useEffect(()=>{const $=()=>{const me=Pe.getState(),Ne=me.sessions,w=me.projectActionRuns;for(const[W,se]of Object.entries(w)){const we=Ne.get(se.directory)?.tabs.find(Ge=>Ge.id===se.tabId);if(!we||we.terminalSessionId!==se.sessionId){E(W);continue}const Ie=z.current[W]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};z.current[W]=Ie;const ze=je.find(Ge=>Ge.id===se.actionId),lt=me.getBuffer(se.directory,se.tabId).chunks;if(!ze||lt.length===0)continue;const St=lt.filter(Ge=>Ie.lastSeenChunkId===null||Ge.id>Ie.lastSeenChunkId);if(St.length===0)continue;const Je=St.map(Ge=>Ge.data).join(""),ct=`${Ie.tail}${Je}`,pt=!Ie.openedUrl&&ze.autoOpenUrl===!0?Tg(ct):null,Fe=St[St.length-1]?.id??Ie.lastSeenChunkId;if(Ie.lastSeenChunkId=Fe,Ie.tail=ct.slice(-512),pt)if(Ie.openedUrl=!0,Ie.openInPreview){const Ge=w[W];Ge&&(P(Ge.directory,Ge.tabId,pt,{locked:!1,autoOpened:!1}),Ge.status==="waiting-for-preview"&&M(W,"running"),window.clearTimeout(re.current[W]),delete re.current[W],S(Ge.directory,pt))}else Ue(pt),ce.success("Opened URL from action output");z.current[W]=Ie}for(const W of Object.keys(z.current))w[W]||(delete z.current[W],window.clearTimeout(re.current[W]),delete re.current[W])};return $(),Pe.subscribe((me,Ne)=>{(me.sessions!==Ne.sessions||me.buffers!==Ne.buffers)&&$()})},[je,S,Ue,D,E,P,M]);const $e=o.useCallback(async($,me={})=>{if(!X)throw new Error("No active directory");const Ne=ds(X,$.id);C(X);const w=Pe.getState(),W=w.getDirectoryState(X);let se=B.current[Ne]||null;const de=se?!!W?.tabs.some(ze=>ze.id===se):!1;(!se||!de)&&(se=w.createTab(X),B.current[Ne]=se),N(X,se,`Action: ${$.name}`),v(X,se,$.icon||"play"),g(X,se),me.revealTerminal!==!1&&fe.getState().openContextPanelTab(X,{mode:"terminal"});const Ie=Pe.getState().getDirectoryState(X)?.tabs.find(ze=>ze.id===se);return{key:Ne,tabId:se,sessionId:Ie?.terminalSessionId??null}},[C,X,g,v,N]),nt=o.useCallback(async $=>{if(!i&&c)return;if(!X){ce.error("No active directory for action");return}const me=ds(X,$.id),Ne=D[me];if(!(Ne&&Ne.status==="running")&&!G.current.has(me)){G.current.add(me);try{const w=$.id===Qt?await(async()=>{const[Fe,Ge]=await Promise.all([Ar({id:Ke?.id??"",path:X}),Cg(X)]),mt=await bg(X,Fe.actions,Ge);if(!mt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Qt,name:"Auto-discover",command:mt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:mt.previewUrlHint||""}})():$,W=w.autoOpenUrl===!0&&(w.openUrl||"").trim().length>0,se=!W&&$.id!==Qt,{key:de,tabId:we,sessionId:Ie}=await $e(w,{revealTerminal:se});let ze=Ie;if(!ze){x(X,we,!0);try{ze=(await l.createSession({cwd:X,sessionId:we,shell:f,loginShell:y,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,A(X,we,ze)}finally{x(X,we,!1)}}if(!ze)throw new Error("Failed to create terminal session");Y.current[de]?.(),x(X,we,!0);const lt=l.connect(ze,{onEvent:Fe=>{Fe.type==="snapshot"&&(Pe.getState().replaceBuffer(X,we,Fe.data??"",Fe.sequence??0),Pe.getState().setConnecting(X,we,!1)),Fe.type==="data"&&typeof Fe.data=="string"&&Fe.data.length>0&&Pe.getState().appendToBuffer(X,we,Fe.data,Fe.sequence,Fe.replayData),Fe.type==="exit"&&(Pe.getState().setTabLifecycle(X,we,"exited"),Pe.getState().setConnecting(X,we,!1),Pe.getState().removeProjectActionRun(de),delete z.current[de],Y.current[de]?.(),delete Y.current[de],window.clearTimeout(re.current[de]),delete re.current[de])},onError:(Fe,Ge)=>{Pe.getState().setConnecting(X,we,!1),Ge&&(Pe.getState().setTabLifecycle(X,we,"exited"),Pe.getState().setTabSessionId(X,we,null),Pe.getState().removeProjectActionRun(de))}});Y.current[de]=lt.close;const St=w.autoOpenUrl===!0&&d&&(w.desktopOpenSshForward||"").trim().length>0,Je=w.autoOpenUrl?Eg(w.openUrl):null,ct=w.autoOpenUrl&&d?Of(w.desktopOpenSshForward,u):null;T({key:de,directory:X,actionId:w.id,tabId:we,sessionId:ze,status:w.id===Qt&&!Je?"waiting-for-preview":"running"}),window.clearTimeout(re.current[de]),delete re.current[de],w.id===Qt&&!Je&&(re.current[de]=window.setTimeout(()=>{const Fe=Pe.getState(),Ge=Fe.projectActionRuns[de];Fe.updateProjectActionRunStatus(de,"running"),Ge&&(Fe.setActiveTab(Ge.directory,Ge.tabId),fe.getState().openContextPanelTab(Ge.directory,{mode:"terminal"})),delete re.current[de]},Dg)),z.current[de]={lastSeenChunkId:null,openedUrl:!!ct||!!Je||W,tail:"",openInPreview:w.id===Qt};const pt=Pg(w.command.trim().replace(/\r\n|\r/g,`
56
+ `));await l.sendInput(ze,`${pt}\r`),ct?(P(X,we,null,{locked:!0}),Ue(ct),ce.success("Opened forwarded URL")):Je?(P(X,we,Je,{locked:!0,autoOpened:!0}),S(X,Je),ce.success("Opened action URL")):W?(P(X,we,null,{locked:!0}),ce.error("Invalid custom URL format")):St?(P(X,we,null,{locked:!0}),ce.error("Selected desktop SSH forward is unavailable")):P(X,we,null,{locked:!1,autoOpened:!1})}catch(w){E(me),delete z.current[me],Y.current[me]?.(),delete Y.current[me],window.clearTimeout(re.current[me]),delete re.current[me],ce.error(w instanceof Error?w.message:"Failed to run action")}finally{G.current.delete(me)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,$e,i,c,d,X,y,f,Ue,S,D,E,x,T,P,A,Ke?.id,l]),_e=o.useCallback(async $=>{const me=ds(X,$.id),Ne=D[me];if(!Ne)return;M(me,"stopping");const w=kg(l,Ne.sessionId,1e3);try{await l.sendInput(Ne.sessionId,"")}catch{}const W=await w;if(Pe.getState().getDirectoryState(Ne.directory)?.tabs.find(we=>we.id===Ne.tabId)?.terminalSessionId===Ne.sessionId&&!W){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:Ne.sessionId})}catch{}else try{await l.close(Ne.sessionId)}catch{}A(Ne.directory,Ne.tabId,null)}E(me),delete z.current[me],Y.current[me]?.(),delete Y.current[me],window.clearTimeout(re.current[me]),delete re.current[me]},[X,D,E,A,l,M]),q=o.useCallback(()=>{const $=xe??je[0];if(!$)return;const me=ds(X,$.id),Ne=D[me];if(Ne?.status!=="stopping"){if(Ne){_e($);return}nt($)}},[je,X,nt,D,xe,_e]),V=o.useCallback(($,me=!1)=>{if(te($.id),!me){nt($);return}const Ne=ds(X,$.id),w=D[Ne];if(w?.status!=="stopping"){if(w){_e($);return}nt($)}},[X,nt,D,_e]),be=o.useCallback(()=>{Ke?.id&&(m(Ke.id),p("projects"),h(!0))},[h,p,m,Ke?.id]),Q=xe??je[0]??null,ve=Q?D[ds(X,Q.id)]:null,pe=Pe($=>ve?$.sessions.get(ve.directory)?.tabs.find(me=>me.id===ve.tabId)?.previewUrl??null:null);if(!i&&c||!Ke||!X)return null;const De=xe??je[0]??null;if(!De)return null;const at=De.icon||"play",ht=De.id===Qt?"scan-2":rn[at]||"play",Ve=ds(X,De.id),Me=D[Ve],ke=Me?.status==="stopping",Le=Me?.status==="waiting-for-preview",dt=!!(Me&&pe),bt=()=>{!Me||!pe||S(Me.directory,pe)},rt=De.id===Qt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:_||ke,className:O("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":Me?`Stop ${De.name}`:`Run ${De.name}`,children:ke||Le?t.jsx(k,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Me?t.jsx(k,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(k,{name:ht,className:"h-5 w-5"})})}),rt?t.jsx(st,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),dt?t.jsxs(et,{children:[t.jsx(tt,{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:bt,children:t.jsx(k,{name:"global",className:"h-4 w-4"})})}),t.jsx(st,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Yt,{children:[t.jsx(Vt,{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(qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(wt,{className:"flex items-center gap-2",onClick:be,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(Hs,{}),je.map($=>{const me=$.icon||"play",Ne=$.id===Qt?"scan-2":rn[me]||"play",w=ds(X,$.id),W=D[w],se=!!W,de=W?.status==="stopping";return t.jsxs(wt,{className:"flex items-center gap-2",onClick:()=>{V($,!0)},children:[t.jsx(k,{name:Ne,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:$.name}),de||W?.status==="waiting-for-preview"?t.jsx(k,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(k,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},$.id)})]})]})]}):t.jsxs("div",{className:O("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(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:q,disabled:_||ke,className:O("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":Me?`Stop ${De.name}`:`Run ${De.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:ke||Le?t.jsx(k,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Me?t.jsx(k,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(k,{name:ht,className:"h-4 w-4"})})})}),rt?t.jsx(st,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),dt?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:bt,className:O(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(st,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O(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(qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(wt,{className:"flex items-center gap-2",onClick:be,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(Hs,{}),je.map($=>{const me=$.icon||"play",Ne=$.id===Qt?"scan-2":rn[me]||"play",w=ds(X,$.id),W=D[w],se=!!W,de=W?.status==="stopping";return t.jsxs(wt,{className:"flex items-center gap-2",onClick:()=>{V($,!0)},children:[t.jsx(k,{name:Ne,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:$.name}),de||W?.status==="waiting-for-preview"?t.jsx(k,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(k,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},$.id)})]})]})]})},tr="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",Rg="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",Mg=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(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:O(a??tr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(k,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(st,{children:t.jsx("p",{children:n})})]}):null}),Fg=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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O(tr,"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(qt,{align:"end",className:"w-64",children:[t.jsx(ou,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Hs,{}),r.map(d=>{const u=d.user,b=!!d.current,f=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(wt,{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:f})]}):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"})})}),Lg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:b,remoteUpdateError:f,onOpenRemoteUpdate:y}){return t.jsxs(Yt,{open:a,onOpenChange:p=>{l(p),p&&c()},children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:O(tr,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(st,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(qt,{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...":f||"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:y,children:"Update"}):null]})}),t.jsx(ru,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Og=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},Xs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Fx=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{ss("ui.header.render");const l=fe(R=>R.setSessionSwitcherOpen),c=fe(R=>R.toggleSidebar),d=fe(R=>R.isSidebarOpen),u=fe(R=>R.activeMainTab),b=fe(R=>R.setActiveMainTab),f=fe(R=>R.shortcutOverrides);fe(R=>R.timeFormatPreference),Wn();const y=Oe(R=>!!R.newSessionDraft?.open),p=Oe(R=>R.currentSessionId),h=da(p??""),m=qd(p),S=o.useMemo(()=>{if(!m)return null;const R=m;return{title:m.title??null,directory:R.directory??null,created:m.time?.created??null,slug:R.slug??null,shareUrl:m.share?.url??null,parentId:m.parentID??null}},[m]),C=Ot($r(R=>{if(!R.activeProjectId)return null;const I=R.projects.find(J=>J.id===R.activeProjectId);return I?{id:I.id,path:I.path,label:I.label}:null})),N=o.useMemo(()=>{if(!C)return null;const R=C.label?.trim();if(R)return R;const I=C.path.split(/[\\/]/).filter(Boolean);return I[I.length-1]??null},[C]),{isMobile:v}=Ps(),{enabled:g}=eo(),x=!!(g&&a&&i!==void 0),A=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"}],[]),[P,D]=o.useState(!1),T=null,M=o.useRef(null),[E,K]=o.useState(()=>typeof window>"u"?!1:fs()),Z=o.useMemo(()=>xa(),[]),ee=Qd(),[te,_]=o.useState(!1),H=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:B,side:z}=pa(),Y=o.useMemo(()=>{if(typeof window>"u")return null;const R=window.__PICHAMBER_MACOS_MAJOR__;if(typeof R=="number"&&Number.isFinite(R)&&R>0)return R;if(typeof navigator>"u")return null;const I=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!I)return null;const J=Number.parseInt(I[1],10),Ee=Number.parseInt(I[2],10);return Number.isNaN(J)?null:J===10?Ee:J},[]);Ye.useEffect(()=>{typeof window>"u"||K(fs())},[]);const re=fe(R=>R.isSessionSwitcherOpen),G=null,Te=null,Re=[],[He,Ke]=o.useState(!1),[Ue,Ae]=o.useState(!1),[X,xe]=o.useState("Local"),[We,Ce]=o.useState(!0),[je,$e]=o.useState(!1),[nt,_e]=o.useState(null),[q,V]=o.useState(!1),[be,Q]=o.useState(null),ve=o.useMemo(()=>Og(X),[X]),pe=o.useCallback(async()=>{if(!(typeof window>"u"||!E))try{if(dn()){xe("Local"),Ce(!0);return}Ce(!1);const R=await Du(),I=Jd(),J=Xd([Zd(I),...R.hosts]);if(J.id===eu){xe("Local"),Ce(!0);return}xe(Pu(J.label.trim()||"Instance"))}catch{xe("Local"),Ce(!0)}},[E]);Ye.useEffect(()=>(pe(),Eu(()=>{pe()})),[pe]);const De=o.useCallback(async()=>{if(We){_e(null),Q(null);return}V(!0),Q(null);try{const R=new URLSearchParams({appType:"web",instanceMode:"remote"}),I=await Jt(`/api/pi/update-check?${R.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!I.ok)throw new Error(`Server responded with ${I.status}`);const J=await I.json();_e({available:J.available??!1,version:J.version,currentVersion:J.currentVersion??"unknown",body:J.body,nextSuggestedCheckInSec:typeof J.nextSuggestedCheckInSec=="number"?J.nextSuggestedCheckInSec:void 0,packageManager:J.packageManager,updateCommand:J.updateCommand})}catch(R){_e(null),Q(R instanceof Error?R.message:"Failed to check remote instance updates")}finally{V(!1)}},[We]);o.useEffect(()=>{_e(null),Q(null),$e(!1)},[We,X]),o.useEffect(()=>{if(!E||We)return;const R=3e3,I=3600*1e3;let J=!1,Ee=null;const ft=xt=>{Ee=window.setTimeout(()=>{if(J||typeof document<"u"&&document.visibilityState!=="visible"){ft(I);return}De().finally(()=>{J||ft(I)})},xt)};return ft(R),()=>{J=!0,Ee!==null&&window.clearTimeout(Ee)}},[De,We,X,E]);const at=o.useCallback(()=>{if(nt?.available){$e(!0);return}De()},[De,nt?.available]),ht=p?S??null:null,Ve=o.useRef(null),[Me,ke]=o.useState(0);o.useEffect(()=>{if(!p){Ve.current&&(Ve.current=null,ke(Ee=>Ee+1));return}if(ht){Ve.current={sessionId:p,session:ht,expiresAt:Date.now()+2e3};return}const R=Ve.current;if(!R||R.sessionId!==p)return;const I=R.expiresAt-Date.now();if(I<=0){Ve.current=null,ke(Ee=>Ee+1);return}const J=window.setTimeout(()=>{Ve.current?.sessionId===p&&(Ve.current=null),ke(Ee=>Ee+1)},I);return()=>{window.clearTimeout(J)}},[p,ht]);const Le=(()=>{if(ht)return ht;if(!p)return null;const R=Ve.current;return R&&R.sessionId===p&&R.expiresAt>Date.now()?R.session:null})(),dt=o.useMemo(()=>{const R=typeof Le?.directory=="string"?Le.directory:"";return Xs(R||"")},[Le?.directory]),bt=Oe(R=>R.newSessionDraft?.open?Xs(R.newSessionDraft.directoryOverride??""):""),rt=o.useMemo(()=>dt||bt,[bt,dt]),me=ca(rt||null),Ne=!!(N||me),w=o.useMemo(()=>{if(!p)return N??"PiChamber";const R=Le?.title?.trim();return R&&R.length>0?R:"Untitled Session"},[N,Le?.title,p]),W=ua(),se=so(),de=Oe(R=>R.updateSessionTitle),we=Oe(R=>R.archiveSessions),Ie=Oe(R=>R.deleteSessions),[ze,lt]=o.useState(!1),[St,Je]=o.useState(!1),ct=o.useRef(!1),[pt,Fe]=o.useState(""),[Ge,mt]=o.useState(null),Tt=o.useRef(null);o.useEffect(()=>{ct.current=!1,Je(!1),lt(!1),Fe(""),mt(null)},[p]);const Bt=o.useCallback(()=>{p&&(Fe(Le?.title?.trim()||w),lt(!0))},[Le?.title,p,w]),vt=o.useCallback(async()=>{if(!p)return;const R=pt.trim();R&&R!==Le?.title?.trim()&&await de(p,R),lt(!1)},[Le?.title,p,pt,de]);o.useEffect(()=>{if(!ze)return;const R=I=>{const J=I.target;(!J||!Tt.current?.contains(J))&&vt()};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[ze,vt]);const jt=o.useCallback(()=>{p&&an(p).then(R=>{ce[R.ok?"success":"error"](R.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ce.error("Failed to copy session ID"))},[p]),kt=o.useCallback(async()=>{if(!p||!rt){ce.error("Nothing to export");return}try{await se.syncSession(p)}catch{ce.error("Failed to load the complete session history");return}const R=Er(W.getState()).list;if(R.length===0){ce.error("Nothing to export");return}const I=Xa(R,Le?.title??null),J=tl(Le?.title??null);await el(I,J)||Za(I,J),ce.success("Session exported")},[Le?.title,p,W,rt,se]);h?.type==="busy"||h?.type;const F=o.useCallback(async()=>{if(!p||!Ge)return;const R=tu(),I=[p];for(let xt=0;xt<I.length;xt+=1){const Ut=I[xt];for(const Kt of R)Kt.parentID===Ut&&!I.includes(Kt.id)&&I.push(Kt.id)}const J=Ge;if(mt(null),(J==="archive"?await we(I):await Ie(I)).failedIds.length>0){ce.error(J==="archive"?"Failed to archive session":"Failed to delete session");return}ce.success(J==="archive"?"Session archived":"Session deleted")},[we,p,Ie,Ge]),Se=fe(R=>R.isArchivePageOpen),Be=o.useMemo(()=>Se?{title:"Archive",subtitle:null}:null,[Se]),ot=o.useMemo(()=>Xs(rt||C?.path||""),[C?.path,rt]),L=o.useMemo(()=>C?{id:C.id,path:C.path}:null,[C]),oe=o.useRef(null);o.useEffect(()=>{!L||!ot||(oe.current={projectRef:L,directory:ot})},[ot,L]);const he=o.useMemo(()=>L&&ot?{projectRef:L,directory:ot}:oe.current,[ot,L]),Xe=o.useCallback(async R=>{},[]),ye=o.useCallback(()=>{if(typeof document>"u")return;const R=document.activeElement;if(!R)return;const I=R.tagName;(I==="INPUT"||I==="TEXTAREA"||I==="SELECT"||R.isContentEditable)&&R.blur()},[]),Qe=o.useCallback(()=>{if(v){ye(),l(!re);return}c()},[ye,v,re,l,c]),ut=o.useCallback(()=>{nn("desktop_open_draft_mini_chat_window",{directory:Xs(rt||C?.path||""),projectId:C?.id??null,apiBaseUrl:Mr(),clientToken:Rr()}).catch(R=>{console.warn("[header] failed to open draft mini chat window",R)})},[C?.id,C?.path,rt]),At=o.useCallback(()=>{if(y){ut();return}p&&nn("desktop_open_session_mini_chat_window",{sessionId:p,directory:Xs(rt||C?.path||""),apiBaseUrl:Mr(),clientToken:Rr()}).catch(R=>{console.warn("[header] failed to open session mini chat window",R)})},[C?.path,p,ut,y,rt]),Rt=tr,It=Rg,Gt=o.useMemo(()=>n?"sessions":x?r&&i?i:null:r?"git":u,[u,x,n,r,i]),_t=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&re&&l(!1)},[re,n,e,s,r,l]),Ct=o.useCallback(()=>{e?.()},[e]),Ft=o.useCallback(()=>{s?.()},[s]),U=o.useMemo(()=>E&&H&&!te?"5.5rem":ee?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!E||B?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[E,te,H,ee,B]);Ye.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",U)},[U]);const ne=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",le=d?"0px":E&&B?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":g?"2.75rem":"2.5rem";Ye.useEffect(()=>{if(!E||!H){_(!1);return}let R=!1;const I=async()=>{try{const Ee=await nn("desktop_is_window_fullscreen");R||_(Ee===!0)}catch{R||_(!1)}},J=()=>{I()};return I(),window.addEventListener("pichamber:window-resized",J),()=>{R=!0,window.removeEventListener("pichamber:window-resized",J)}},[E,H]);const ue=o.useMemo(()=>!E||!H||Y===null?"":Y>=26?"h-12":Y<=15?"h-14":"",[E,H,Y]),ge=o.useMemo(()=>{if(!(E&&!B))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))"}},[E,B]),it=o.useCallback(()=>{if(typeof document>"u")return;const R=M.current?.getBoundingClientRect().height;R&&document.documentElement.style.setProperty("--oc-header-height",`${R}px`)},[]);Ye.useEffect(()=>{if(typeof window>"u")return;it();const R=M.current;if(!R||typeof ResizeObserver>"u")return()=>{};let I=0;const J=()=>{I||(I=requestAnimationFrame(()=>{I=0,it()}))},Ee=new ResizeObserver(J);return Ee.observe(R),window.addEventListener("resize",J),window.addEventListener("orientationchange",J),()=>{I&&cancelAnimationFrame(I),Ee.disconnect(),window.removeEventListener("resize",J),window.removeEventListener("orientationchange",J)}},[it]),Ye.useEffect(()=>{it()},[it,v,ue]);const Dt=o.useCallback(async R=>{const I=R.target;I.closest(".app-region-no-drag")||I.closest("button, a, input, select, textarea")||R.button===0&&E&&await Tu()},[E]),yt=o.useMemo(()=>v?[{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"}]:[],[v]),Ht=o.useCallback(R=>to(sn(R,f)),[f]);Ye.useEffect(()=>{!v&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&b("chat")},[u,v,b]);const Xt=o.useMemo(()=>{const R=[];return E&&R.push({value:"instance",label:"Instance",icon:t.jsx(k,{name:"server",className:"h-3.5 w-3.5"})}),R},[E]);Ye.useEffect(()=>{const R=I=>{if(su(I)&&!I.shiftKey&&!I.altKey){const J=parseInt(I.key,10);J>=1&&J<=yt.length&&(I.preventDefault(),v&&(ye(),_t()),b(yt[J-1].id))}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[ye,_t,v,b,yt]),Ye.useEffect(()=>{const R=I=>{const J=sn("toggle_services_menu",f);if(Jo(I,J)){I.preventDefault(),Ue?Ae(!1):(Ae(!0),pe());return}const Ee=sn("cycle_services_tab",f);if(Jo(I,Ee)){if(I.preventDefault(),Xt.length===0)return;Ae(!0),pe();return}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[f,Ue,Xt,pe]);const Pt=R=>{const I=u===R.id,J=R.icon==="diff",Ee=J?null:R.icon,ft=R.id==="chat",xt=Kt=>J?t.jsx(Gi,{size:Kt}):Ee?t.jsx(k,{name:Ee,className:`h-${Kt/4} w-${Kt/4}`}):null,Ut=t.jsxs("button",{type:"button",onClick:()=>b(R.id),className:O("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",I?"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",ft&&!v&&"min-w-[100px] justify-center"),"aria-label":R.label,"aria-selected":I,role:"tab",children:[v?xt(20):t.jsxs(t.Fragment,{children:[xt(16),t.jsx("span",{className:"header-tab-label",children:R.label})]}),R.badge!==void 0&&R.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:R.badge})]});return t.jsx(o.Fragment,{children:Ut},R.id)},ns=t.jsxs(t.Fragment,{children:[t.jsx(mg,{directory:ot,className:"mr-1"}),E?t.jsx(Lg,{isDesktopApp:E,currentInstanceLabel:X,compactCurrentInstanceLabel:ve,currentInstanceIsLocal:We,isDesktopServicesOpen:Ue,setIsDesktopServicesOpen:Ae,refreshCurrentInstanceLabel:pe,shortcutLabel:Ht,remoteUpdateInfo:nt,remoteUpdateChecking:q,remoteUpdateError:be,onOpenRemoteUpdate:at}):null,t.jsx(Fg,{isMobile:v,githubAuthStatus:T,githubAccounts:Re,githubAvatarUrl:G,githubLogin:Te,isSwitchingGitHubAccount:He,handleGitHubAccountSwitch:Xe})]}),ls=Z&&(y||!!p),ms=()=>t.jsxs("div",{onMouseDown:Dt,className:O("app-region-drag relative flex h-12 select-none items-center pr-3",ue),style:ge,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:ne}}),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:le}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Be?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:Be.title}),Be.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:Be.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:Rt,"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:[ze?t.jsxs("form",{ref:Tt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:R=>{R.preventDefault(),vt()},children:[t.jsx("input",{value:pt,onChange:R=>Fe(R.target.value),autoFocus:!0,onKeyDown:R=>{R.stopPropagation(),R.key==="Escape"&&lt(!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:()=>lt(!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:y?"New session":w}),Ne?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:[N?t.jsx("span",{className:"truncate",children:N}):null,me?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:me})]}):null]}):null]}),t.jsx("div",{className:O("flex h-[18px] shrink-0 items-center justify-center",Ne?"self-start":"self-center"),children:p&&!y&&!ze?t.jsxs(Yt,{open:St,onOpenChange:Je,onOpenChangeComplete:R=>{!R&&ct.current&&(ct.current=!1,Bt())},children:[t.jsx(Vt,{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(qt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(wt,{onClick:()=>{ct.current=!0},children:[t.jsx(k,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(wt,{onClick:jt,children:[t.jsx(k,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Hs,{}),t.jsxs(wt,{onClick:()=>{kt()},children:[t.jsx(k,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Hs,{}),t.jsxs(wt,{onClick:()=>mt("archive"),children:[t.jsx(k,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(wt,{className:"text-destructive focus:text-destructive",onClick:()=>mt("delete"),children:[t.jsx(k,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),yt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:yt.map(R=>Pt(R))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[he?t.jsx(Wi,{projectRef:he.projectRef,directory:he.directory,className:"mr-1"}):null,t.jsx(Mg,{visible:ls,title:y?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:At,className:O(Rt,"mr-1"),Icon:"picture-in-picture-2"}),ns,t.jsx(ma,{visible:B&&z==="right",position:"right"})]})]})]}),Ws=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[g&&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:ne}}),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:le}})]}),!g&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:Ct,className:O(It,Gt==="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"})}):re?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:Qe,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&&re&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!re||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!x&&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:yt.map(R=>{const I=u===R.id,J=R.icon==="diff",Ee=J?null:R.icon;return t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{v&&(ye(),_t()),b(R.id)},"aria-label":R.label,"aria-selected":I,role:"tab",className:O(It,"relative rounded-lg",Gt===R.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[J?t.jsx(Gi,{className:"h-5 w-5"}):Ee?t.jsx(k,{name:Ee,className:"h-5 w-5"}):null,R.badge!==void 0&&R.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:R.badge}),R.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(st,{children:t.jsx("p",{children:R.label})})]},R.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[x&&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:A.map(R=>{const I=r&&i===R.id;return t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{v&&(ye(),_t()),D(!1),a?.(R.id)},"aria-label":R.label,"aria-selected":I,role:"tab",className:O(It,"relative rounded-lg",I&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(k,{name:R.icon,className:"h-5 w-5"})})}),t.jsx(st,{children:t.jsx("p",{children:R.label})})]},R.id)})}),t.jsx(Dh,{open:P,onOpenChange:D,currentSessionId:p,effectiveDirectory:rt||null,isNewSessionDraftOpen:y})]}),he&&t.jsx(Wi,{projectRef:he.projectRef,directory:he.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!x?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Ft,className:O(It,"relative",Gt==="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(st,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Ys=O("header-safe-area relative z-10 bg-background",v&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:M,className:Ys,style:{"--padding-scale":"1"},children:v?Ws():ms()}),t.jsx(is,{open:Ge!==null,onOpenChange:R=>{R||mt(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ys,{children:[t.jsx(hs,{children:Ge==="delete"?"Delete session?":"Archive session?"}),t.jsx(Es,{children:Ge==="delete"?`\\"${w}\\" will be permanently deleted.`:`\\"${w}\\" will be archived.`})]}),t.jsxs(Ts,{children:[t.jsx(qe,{variant:"outline",size:"sm",onClick:()=>mt(null),children:"Cancel"}),t.jsx(qe,{variant:"destructive",size:"sm",onClick:()=>{F()},children:Ge==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Ta,{open:je,onOpenChange:$e,info:nt,downloading:!1,downloaded:!1,progress:null,error:be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Yi="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",Bg="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",Lx=()=>{const e=fe(m=>m.isSidebarOpen),s=fe(m=>m.toggleSidebar),n=fe(m=>m.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=to(sn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=pa(),{enabled:d}=eo(),u=!e,b=l&&c==="left",f=l,y=u||b||f,p=b||f,h=o.useCallback(()=>{nn("desktop_show_app_menu").catch(m=>{console.warn("[titlebar] failed to open app menu",m)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const m=x=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(x)}px`)},S=x=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(x)}px`)};if(!p)return;const C=i.current,N=r.current;if(!C||!N){m(0),S(0);return}const v=()=>{const x=Math.max(C.getBoundingClientRect().width,C.scrollWidth);m(x),S(N.getBoundingClientRect().width)};if(v(),typeof ResizeObserver>"u")return;const g=new ResizeObserver(v);return g.observe(C),g.observe(N),()=>{g.disconnect()}},[p]),y?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:[b?t.jsx(ma,{visible:!0,position:"left"}):null,f?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:h,"aria-label":"Open PiChamber menu",className:O(Yi,"shrink-0"),children:t.jsx(k,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(st,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:O(d?Bg:Yi,"shrink-0"),children:t.jsx(k,{name:"layout-left",className:d?"h-5 w-5":"h-[18px] w-[18px]"})})}),t.jsx(st,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Pn=200,En="cubic-bezier(0.22, 1, 0.36, 1)",Ox=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 ${Pn}ms ${En}, width ${Pn}ms ${En}, min-width ${Pn}ms ${En}, max-width ${Pn}ms ${En}`}};export{Bs as $,bx as A,xx as B,gx as C,Ti as D,Ss as E,jx as F,lx as G,Fx as H,Df as I,uo as J,ox as K,If as L,Dh as M,fo as N,ix as O,Dx as P,Xf as Q,$n as R,kx as S,Px as T,Ta as U,Pf as V,hn as W,Sf as X,jf as Y,Ra as Z,pn as _,Zs as a,kf as a0,tx as a1,ux as a2,Cf as a3,Nf as a4,dx as a5,px as a6,hx as a7,Ef as a8,js as a9,cx as aa,fx as ab,mx as ac,ex as ad,sx as ae,nx as af,rx as ag,Yf as ah,ax as ai,oh as aj,ih as ak,Af as al,Zg as am,Cx as an,yx as ao,gm as b,Nx as c,Ln as d,fh as e,Tx as f,Ax as g,wx as h,ym as i,Sx as j,vx as k,Ox as l,Rx as m,Lx as n,Xg as o,Zf as p,eh as q,Ex as r,Ix as s,th as t,Mn as u,ci as v,sh as w,Qm as x,Mx as y,nh as z};