@pi-chamber/web 0.1.9 → 0.2.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 (79) hide show
  1. package/bin/cli.test.js +48 -0
  2. package/bin/lib/DOCUMENTATION.md +2 -2
  3. package/bin/lib/cli-args.js +38 -11
  4. package/bin/lib/cli-startup.js +60 -13
  5. package/bin/lib/commands-startup.js +20 -5
  6. package/bin/lib/commands-update.js +91 -34
  7. package/bin/lib/commands-update.test.js +57 -42
  8. package/dist/assets/CommitSection-LewzHfDH.js +1 -0
  9. package/dist/assets/DiagramEditor-BOIJVnh3.js +1 -0
  10. package/dist/assets/DiagramView-CdNHezna.js +1 -0
  11. package/dist/assets/{DiffView-k3lX2PiV.js → DiffView-Cmw-RHIH.js} +2 -2
  12. package/dist/assets/{FilesView-C39IOFfs.js → FilesView-BODbL0Xm.js} +6 -6
  13. package/dist/assets/{GitView-CkztSaT7.js → GitView-DqYF-n_h.js} +4 -4
  14. package/dist/assets/JsonTreeView-DzEjA1ht.js +1 -0
  15. package/dist/assets/{MarkdownRendererImpl-CF12jEtB.js → MarkdownRendererImpl-Bfq0bOSM.js} +2 -2
  16. package/dist/assets/PatchDiff-CtVByTC4.js +1 -0
  17. package/dist/assets/{PierreDiffViewer-DSQwk05R.js → PierreDiffViewer-Cwoewmiu.js} +2 -2
  18. package/dist/assets/{useAppFontEffects-DqOhrZWx.js → SessionSwitcherDropdown-DNjCJjzF.js} +97 -97
  19. package/dist/assets/{SettingsView-Bf4vWwVK.js → SettingsView-BtLvHlj4.js} +1 -1
  20. package/dist/assets/SettingsWindow-CPd7JmJs.js +1 -0
  21. package/dist/assets/{ToolOutputDialog-Brg2Humk.js → ToolOutputDialog-CFFC5eI-.js} +6 -6
  22. package/dist/assets/ToolPartDiffPreview-yFq1DKSA.js +8 -0
  23. package/dist/assets/{VirtualizedFileDiff-BELx71mz.js → VirtualizedFileDiff-CC5lTPJS.js} +1 -1
  24. package/dist/assets/collapsible-D_555Hw_.js +1 -0
  25. package/dist/assets/computeVirtualFileMetrics-BcVuV0Ic.js +3 -0
  26. package/dist/assets/contextFileOpenGuard-BygvjHuE.js +1 -0
  27. package/dist/assets/index-C9CLY-is.js +1 -0
  28. package/dist/assets/{index-Dnby-sDS.js → index-DQr8-8RF.js} +2 -2
  29. package/dist/assets/index-DYrJXRkU.css +1 -0
  30. package/dist/assets/isDiffPlainText-Bher0UxW.js +1 -0
  31. package/dist/assets/isFilePlainText-EIViqOlI.js +1 -0
  32. package/dist/assets/main-1bIgjP48.js +2 -0
  33. package/dist/assets/main-JDtt2bQS.js +133 -0
  34. package/dist/assets/{markdownCore-BK98alzY.js → markdownCore-Bm4FxtK1.js} +2 -2
  35. package/dist/assets/miniChat-B7kKqKHH.js +2 -0
  36. package/dist/assets/mobile-DZPRce5z.js +2 -0
  37. package/dist/assets/renderElectronMiniChatApp-Dq0GdThJ.js +1 -0
  38. package/dist/assets/renderMobileApp-DlKnjObC.js +23 -0
  39. package/dist/assets/{runtimeSurface-DMXukysz.js → runtimeSurface-B6sKTjo7.js} +1 -1
  40. package/dist/assets/{useInlineCommentController-ruw8wb2Y.js → useInlineCommentController-CSR_Ju0a.js} +2 -2
  41. package/dist/assets/usePanelSlide-BkonU4LS.js +47 -0
  42. package/dist/assets/{useWindowTitle-qt23iibv.js → useWindowTitle-rt_8xbd9.js} +3 -3
  43. package/dist/assets/{vendor-codemirror-language-data-DVYP3hf_.js → vendor-codemirror-language-data-Be-zDX0u.js} +2 -2
  44. package/dist/assets/{web-components-P2py0R8j.js → web-components-DgFD1Jms.js} +4 -4
  45. package/dist/index.html +4 -4
  46. package/dist/mini-chat.html +3 -3
  47. package/dist/mobile.html +3 -3
  48. package/package.json +1 -1
  49. package/server/lib/package-manager.js +44 -65
  50. package/server/lib/package-manager.test.js +27 -0
  51. package/server/lib/pi/routes.js +6 -0
  52. package/server/lib/pi/routes.test.js +32 -0
  53. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  54. package/server/lib/pi/session-daemon/session-daemon.js +11 -4
  55. package/server/lib/pi/session-daemon/session-daemon.test.js +24 -0
  56. package/dist/assets/CommitSection-DSFuOWuL.js +0 -1
  57. package/dist/assets/DiagramEditor-D6W6zeV7.js +0 -1
  58. package/dist/assets/DiagramView-r89Qi5ON.js +0 -1
  59. package/dist/assets/JsonTreeView-C6qt2uIj.js +0 -1
  60. package/dist/assets/PatchDiff-D6In_lUU.js +0 -1
  61. package/dist/assets/SessionSwitcherDropdown-CvE7hsxG.js +0 -1
  62. package/dist/assets/SettingsWindow-B8IV35H4.js +0 -1
  63. package/dist/assets/ToolPartDiffPreview-rlz2ipa2.js +0 -8
  64. package/dist/assets/collapsible-QoPrpZP_.js +0 -1
  65. package/dist/assets/computeVirtualFileMetrics-CInbUZiB.js +0 -3
  66. package/dist/assets/contextFileOpenGuard-BOtkNMZy.js +0 -1
  67. package/dist/assets/index-4sRd3SSM.js +0 -1
  68. package/dist/assets/index-NYG3k04a.css +0 -1
  69. package/dist/assets/isDiffPlainText-BquUayus.js +0 -1
  70. package/dist/assets/isFilePlainText-D4iUTBdr.js +0 -1
  71. package/dist/assets/main-Cp3YZZm1.js +0 -2
  72. package/dist/assets/main-CyshB9VI.js +0 -134
  73. package/dist/assets/miniChat-C_A4lnrT.js +0 -2
  74. package/dist/assets/mobile-2dXx6cUI.js +0 -2
  75. package/dist/assets/renderElectronMiniChatApp-HL15h5xo.js +0 -1
  76. package/dist/assets/renderMobileApp-w6YFCJhq.js +0 -23
  77. package/dist/assets/runtimeEndpointReset-DiVqZFZB.js +0 -46
  78. package/dist/assets/useOpenInAppsStore-DVr2oGEm.js +0 -1
  79. /package/dist/assets/{runtimeEndpointReset-BV3KOtdA.css → usePanelSlide-BV3KOtdA.css} +0 -0
@@ -1,46 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-4sRd3SSM.js","assets/useAppFontEffects-DqOhrZWx.js","assets/index-Dnby-sDS.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-NYG3k04a.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-DMXukysz.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-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.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-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DVYP3hf_.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.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-CInbUZiB.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-D4iUTBdr.js","assets/isDiffPlainText-BquUayus.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 Ms}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ue,j as t,R as i}from"./vendor-react-DYyjh7Q0.js";import{bw as ti,bx as Ts,by as cl,as as dl,o as ul,D as os,C as is,G as fs,I as k,aY as xs,bz as Yr,f as F,B as Me,aB as nr,T as et,y as tt,z as st,bA as si,bB as fl,bC as hl,bD as ml,bE as pl,m as De,bF as gl,bG as Jr,bH as xl,bI as bl,bJ as Zr,bK as yl,bL as vl,bM as wl,bN as Sl,aE as jl,bO as kl,t as oe,aw as as,ax as ls,ay as Xt,a1 as Ls,bP as Cl,bQ as Nl,bR as Il,bS as Dl,bT as Xr,h as qt,bU as Pl,bV as Tl,bW as El,bX as Ml,bY as Al,bZ as Rl,b_ as rr,b$ as ni,c0 as ri,c1 as Fl,c2 as Ll,c3 as Ol,c4 as Bl,c5 as _l,c6 as $l,bh as or,r as As,c7 as ys,c8 as oi,bj as vs,bm as zl,bn as Ul,bo as Kl,bp as Gl,bq as $n,br as Us,c9 as eo,az as Ft,b as kt,aD as Vs,ca as ii,E as ws,H as Bs,J as _s,cb as Hl,cc as Ds,cd as to,ce as so,cf as Wl,cg as ai,ch as ql,ci as li,e as jn,cj as Ql,K as ci,R as di,ck as Vl,cl as At,b8 as ui,c as ir,cm as Yl,cn as Jl,co as Gs,cp as gn,cq as fi,a3 as Hs,a4 as Ws,a2 as Zl,cr as Xl,cs as no,bi as hi,ct as ec,cu as mi,aQ as tc,aR as sc,cv as ro,cw as In,aW as nc,aM as rc,N as oc,aN as pi,cx as ic,cy as ac,p as lc,s as cc,cz as dc,cA as uc,q as fc,aO as oo,w as zn,S as io,aT as hc,cB as mc,cC as pc,v as gc,aA as gi,cD as xc,cE as bc,cF as yc,d as vc,cG as xn,cH as wc,a as Sc,aX as jc,bl as kc,cI as Cc,bk as Nc,cJ as Ic,cK as Dc,cL as Pc,cM as Tc,aj as Ec,cN as ao,cO as Mc,b9 as Ac,cP as Rc,cQ as Fc,cR as on,cS as lo,i as Lc,cT as Oc,cU as co,cV as uo,cW as Bc,aC as _c,a8 as $c,L as zc,cX as xi,u as Uc,cY as Kc,cZ as Gc}from"./useAppFontEffects-DqOhrZWx.js";import{V as fo,W as Hc,X as ho,Y as Wc,i as qc,Z as Qc,U as Vc,r as rs,u as de,y as Yc,b as Jc,x as wr,_ as Zc,$ as ss,a0 as bi,o as yi,l as us,a1 as Qe,a2 as Sr,a3 as jr,a4 as Xc,a5 as ed,N as td,a6 as sd,a7 as nd,a8 as rd,B as Zt,a9 as ar,a as Dn,aa as od,ab as id,ac as ad,ad as ld,A as cd,C as dd,G as ud,H as fd,e as hd,d as an,ae as md,af as pd,ag as Ks,ah as Un,ai as vi,M as gd,n as xd}from"./index-Dnby-sDS.js";import{C as wi,a as Si,M as lr,b as cr,c as dr,d as ji,S as ki,D as bd,e as yd,f as vd,g as wd,h as Sd,i as jd,j as kd,k as Cd}from"./vendor-base-ui-DwfTg5wD.js";import{c as hs,d as Ci,p as kr,u as mo,a as Nd}from"./vendor-zustand-CnsBKjP5.js";import{u as Id}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as Pn,d as qs,P as Cr,D as Tn,e as En,f as Ni,b as Dd,a as Pd,T as Td,M as Ed}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as Nr,v as Ii,u as Mn,a as Md,h as Ad}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as An}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as Rd}from"./permissionStore-BRcQ9Jgt.js";const Fd=3;let kn=0;const Di=[],Ld=()=>kn<Fd?(kn+=1,Promise.resolve()):new Promise(e=>{Di.push(e)}),Od=()=>{const e=Di.shift();if(e){e();return}kn=Math.max(0,kn-1)},Bd=async e=>{await Ld();try{return await e()}finally{Od()}},_d="chat";function Pi(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ts.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ts.SETTINGS,n),s}return e.tab!==_d&&s.set(Ts.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ts.FILE,e.diffFile),s}function $d(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function zd(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Pi(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ts.SESSION)&&s.set(Ts.SESSION,o);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")&&!ti()&&!(!s.force&&zd(e)))try{const n=Pi(e),r=$d(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ud=["typescript","javascript","tsx","jsx","json","markdown"],Ti={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let po=null;const Ei=()=>(po??=Promise.all([Ms(()=>import("./index-4sRd3SSM.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])),Ms(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ms(()=>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})),po),Qs={},go=new Set,fr=new Set;let bn={light:"pierre-light",dark:"pierre-dark"};const Kd=()=>{for(const e of fr)e()},Mi=(e,s)=>{s.setRenderOptions({theme:bn,lineDiffType:Ti[e].lineDiffType})},hr=e=>{typeof window>"u"||go.has(e)||(go.add(e),Ei().then(s=>{if(Qs[e])return;const n=Ti[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ud,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Qs[e]=r,Mi(e,r),Kd()}))},Gd=e=>(fr.add(e),()=>fr.delete(e)),Hd=e=>{if(!(bn.light===e.light&&bn.dark===e.dark)){bn=e;for(const s of Object.keys(Qs)){const n=Qs[s];n&&Mi(s,n)}}},ap=({children:e})=>{const s=cl(),n=fo(!1),r=fo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===o)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ue.useEffect(()=>{let d=!1;return Ei().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Hd({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ue.useEffect(()=>{if(typeof window>"u")return;const d=()=>{hr("unified"),hr("split")};if(typeof window.requestIdleCallback=="function"){const y=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(y)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},lp=(e="unified")=>{const s=Ue.useSyncExternalStore(Gd,()=>Qs[e],()=>{});return Ue.useEffect(()=>{hr(e)},[e]),s},xo="pichamber.update-install-id";function Wd(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const e=window.localStorage.getItem(xo)?.trim();if(e)return e;const s=crypto.randomUUID();return window.localStorage.setItem(xo,s),s}catch{return}}function qd(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=dl();return e}catch{return"unknown"}}function Qd(){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 Vd(){const e=Jc();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 Yd(e){const s=de.getState().reportUsage,n=new URLSearchParams({reportUsage:s?"true":"false"});if(n.set("deviceClass",qd()),n.set("arch",Qd()),n.set("platform",Vd()),s&&(e==="desktop"||e==="mobile")){const r=Wd();r&&n.set("installId",r)}return e==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",Yc()?"local":"remote"),n):e==="mobile"?(n.set("appType","mobile-capacitor"),n.set("instanceMode","remote"),n):(n.set("appType","web"),n.set("instanceMode","unknown"),n)}async function Kn(e,s){try{const n=Yd(e);s&&n.set("currentVersion",s);const r=await rs(`/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 o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Jd(){return qc()?"mobile":Qc()?"desktop":Vc()?"web":null}const bo={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},yn=hs()((e,s)=>({...bo,checkForUpdates:async()=>{const n=Jd();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.1.9",[l,c]=await Promise.allSettled([ho(),Kn("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await Kn("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await Kn("mobile","0.1.9"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}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 o=await ho();if(!o?.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,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await Wc(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Hc())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(bo)}})),yo="https://github.com/RyderAsKing/PiChamber/releases";function Zd(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 Xd(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function vo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function eu(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function tu(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((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const wo=2e3,su=600*1e3;async function nu(){try{const e=await rs("/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 ru(){try{return(await rs("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function ou(e,s=Math.ceil(su/wo),n=wo){for(let r=0;r<s;r++){try{const o=await rs("/api/pi/update-check?reportUsage=false",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await ru())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const iu=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[y,m]=Ue.useState(!1),[w,x]=Ue.useState("idle"),[v,g]=Ue.useState(null),j=n?.version?n.releaseUrl||`${yo}/tag/v${n.version}`:yo,C=n?.downloadUrl||j,N=a?.total?Math.round(a.downloaded/a.total*100):0,b=u==="web",h=u==="mobile",f=n?.updateCommand||"pichamber update";Ue.useEffect(()=>{e||(x("idle"),g(null))},[e]);const I=async()=>{(await nr(f)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},M=Ue.useCallback(async z=>{await ul(z)},[]),T=Ue.useCallback(async()=>{x("updating"),g(null);const z=await nu();if(!z.success){x("error"),g(z.error||"Update failed");return}z.autoRestart&&(x("restarting"),await new Promise(ne=>setTimeout(ne,2e3))),x("reconnecting"),await ou(n?.currentVersion)?window.location.reload():(x("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),O=Ue.useCallback(()=>{M(C)},[M,C]),P=w!=="idle"&&w!=="error",B=Ue.useMemo(()=>{if(!n?.body)return null;const z=n.body.trim();if(!z)return null;const U=tu(z);return U.length===0?{kind:"raw",title:"What's new",content:vo(z)}:{kind:"sections",title:"What's new",sections:[...U].sort((se,K)=>eu(se.version,K.version)).map(se=>({version:se.version,dateLabel:Zd(se.date),content:vo(Xd(se.raw)||z)}))}},[n?.body]);return t.jsx(os,{open:e,onOpenChange:P?void 0:s,children:t.jsxs(is,{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(fs,{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:w==="restarting"||w==="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:[b&&P&&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:[w==="updating"&&"Installing update...",w==="restarting"&&"Server restarting...",w==="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."})]}),B&&!P&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(xs,{className:"max-h-[400px] p-0",fillContainer:!1,children:B.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:z=>{const ne=z.target.closest("a");ne&&ne.href&&(z.preventDefault(),z.stopPropagation(),M(ne.href))},children:t.jsx(Yr,{content:B.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:B.sections.map(z=>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",z.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:z.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:U=>{const se=U.target.closest("a");se&&se.href&&(U.preventDefault(),U.stopPropagation(),M(se.href))},children:t.jsx(Yr,{content:z.content,disableLinkSafety:!0,enableFileReferences:!1})})]},z.version))})})}),b&&w==="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:f}),t.jsx("button",{onClick:I,className:F("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",y&&"text-[var(--status-success)]"),title:y?"Copied!":"Copy command",children:y?t.jsx(k,{name:"check",className:"h-4 w-4"}):t.jsx(k,{name:"clipboard",className:"h-4 w-4"})})]})]}),!b&&!h&&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||v)&&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||v})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!b&&!h&&!o&&!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"]}),!b&&!h&&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..."]}),!b&&!h&&o&&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"]}),h&&t.jsxs(Me,{onClick:O,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),b&&!P&&t.jsxs("button",{onClick:T,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"]}),b&&P&&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..."]})]})]})]})})},au=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=i.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":o,className:F("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:F("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),Ys=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(et,{open:r,onOpenChange:o,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(),o(c=>!c)},className:F("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(k,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(st,{sideOffset:8,className:F("max-w-sm",n),children:e})]})},cp="w-full min-w-40 max-w-48",lu="settings",cu="w-full min-w-40 max-w-48",dp="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",du="w-full max-w-[24rem]",up="min-w-0 flex-1",fp="flex w-full min-w-0 items-center gap-2",hp="typography-meta shrink-0 text-muted-foreground tabular-nums",Ai="space-y-3.5",uu="space-y-1.5",mp="typography-settings-page-title text-muted-foreground",fu="typography-settings-section-title text-foreground",pp="typography-settings-section-title text-foreground",Ri="typography-settings-group-title text-foreground",Ir="typography-settings-field-label text-foreground",hu="typography-settings-description text-muted-foreground",Js="typography-meta text-muted-foreground",gp="typography-meta font-medium text-foreground",xp="typography-settings-section-title text-foreground",mu=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const y=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:F("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[y?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:fu,children:e}):e,n,r!=null?t.jsx(Ys,{children:r}):null]}):null,s!=null?t.jsx("div",{className:hu,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:F(d),children:a})]})},bp=({children:e,className:s})=>t.jsx("div",{className:F("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),pu=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:F(Ri,s),children:e}),yp=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:F("space-y-2",o),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(pu,{children:e}),n!=null?t.jsx(Ys,{children:n}):null]}):null,s!=null?t.jsx("p",{className:Js,children:s}):null]}):null,t.jsx("div",{className:F(a),children:r})]}),Es=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:Js,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:F("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:Ir,children:e}),n!=null?t.jsx(Ys,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:F("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},vp=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:F("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:Ir,children:e}),n!=null?t.jsx(Ys,{children:n}):null]}),s!=null?t.jsx("p",{className:F(Js,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:F("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),wp=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:F("pt-4",s),children:e}),gu=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const y=()=>{o||s(!e)},m=r!=null;return t.jsxs("div",{"data-settings-item":l,className:F("group flex cursor-pointer gap-2 py-0.5",m?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:y,onKeyDown:w=>{(w.key===" "||w.key==="Enter")&&(w.preventDefault(),y())},children:[t.jsx(si,{checked:e,onChange:s,disabled:o,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:Ir,children:n}),d,u!=null?t.jsx(Ys,{children:u}):null]}),m?t.jsx("span",{className:Js,children:r}):null]})]})},Sp=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:F("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(au,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:F("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:Js,children:r}):null]})]}),jp=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:F(uu,n),children:s});function kp({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:F("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Me,{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 xu extends i.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(fl,{className:"w-full max-w-md",children:[t.jsx(hl,{className:"text-center",children:t.jsxs(ml,{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(pl,{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(Me,{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 bu(e){return t.jsx(xu,{...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 Cp=({active:e=!0,readOnly:s=!1})=>{const n=De(r=>r.currentSessionId);return t.jsx(bu,{sessionId:n||void 0,children:t.jsx(gl,{active:e,readOnly:s},n??"no-session")})};function yu({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 Dr=Ue.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:y,endSlot:m,...w},x)=>{const v=Ue.useRef(null),g=Ue.useRef(null),[j,C]=Ue.useState(null),N=c??j,b=Ue.useCallback(f=>{const I=v.current;if(!I)return;g.current={startY:f.clientY,startHeight:I.getBoundingClientRect().height};const M=f.currentTarget;M.setPointerCapture(f.pointerId);const T=P=>{const B=g.current;if(!B)return;const z=B.startHeight+(P.clientY-B.startY),U=Math.max(82,z);d?d(U):C(U)},O=()=>{g.current=null,M.removeEventListener("pointermove",T),M.removeEventListener("pointerup",O),M.removeEventListener("pointercancel",O)};M.addEventListener("pointermove",T),M.addEventListener("pointerup",O),M.addEventListener("pointercancel",O),f.preventDefault()},[d]),h=Ue.useCallback(f=>{if(f.target.closest('textarea, button, [role="separator"]'))return;const M=v.current?.querySelector("textarea");M&&document.activeElement!==M&&(f.preventDefault(),M.focus())},[]);return y?t.jsx(xs,{as:"textarea",ref:x,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:F("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...w}):t.jsx("div",{ref:v,onPointerDown:h,style:N!==null?{height:`${N}px`}:void 0,className:F("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:x,className:F("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...w}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,t.jsx(yu,{onResizeStart:b,ariaLabel:"Resize textarea"})]})]})})});Dr.displayName="Textarea";const So=(e,s)=>s.updatedAtMs-e.updatedAtMs,jo=hs((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([vl(),Zr()]),o={};for(const a of r.sort(So))o[a.id]=a;s().listenerReady||await wl(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:o,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 yl();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Zr(),r={};for(const o of n.sort(So))r[o.id]=o;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await bl({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,o=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(o)},createFromCommand:async(n,r,o)=>{const a=Sl(n,r);o&&o.trim()&&(a.nickname=o.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await Jr(n).catch(()=>{});const r=s().instances.filter(o=>o.id!==n);await s().setInstances(r),e(o=>{const a={...o.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await xl(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 Jr(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})})),Fi=[{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"}],Li=Object.fromEntries(Fi.map(e=>[e.key,e.Icon])),vu="pichamber:project-actions-updated",wu=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},Np=(e,s)=>`${wu(e)}::${s}`,Su=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ko=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},ju=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ko(s.localPort),r=ko(s.remotePort);if(!n||!r)return null;const o=Su(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} - ${o}:${n} -> ${a}:${r}`,url:`http://${o}:${n}`}},Oi=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const o=ju(n,r);o&&s.push(o)}return s},Ip=(e,s)=>{const n=(e||"").trim();return n&&Oi(s).find(a=>a.id===n)?.url||null},ku=du,Bi=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(mu,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),mr=e=>e.name.trim().length>0&&e.command.trim().length>0,Cu=e=>e.name.trim().length===0&&e.command.trim().length===0,Nu=e=>!mr(e)&&!Cu(e),Iu=(e,s)=>e.some(r=>s.has(r.id)&&!mr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(mr)},Du=450,Pu=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Tu=()=>({id:Pu(),name:"",command:"",icon:"play"}),Eu=({projectRef:e})=>{const s=i.useMemo(()=>wr(),[]),n=jo(f=>f.instances),r=jo(f=>f.load),[o,a]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[y,m]=i.useState(new Set),w=i.useRef(!1);i.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),i.useEffect(()=>{let f=!1;return c(!0),(async()=>{try{const I=await jl(e);if(f)return;a(I.actions),u(JSON.stringify({actions:I.actions})),m(new Set(I.actions.map(M=>M.id)))}catch{if(f)return;a([]),u(JSON.stringify({actions:[]})),m(new Set)}finally{f||c(!1)}})(),()=>{f=!0}},[e]);const x=i.useMemo(()=>s?Oi(n):[],[n,s]),v=i.useMemo(()=>Iu(o,y),[o,y]),g=i.useMemo(()=>JSON.stringify({actions:v.actions}),[v.actions]),j=d!==null&&v.canPersist&&g!==d,C=i.useCallback(async f=>await kl(e,{actions:f,primaryActionId:null})?(u(JSON.stringify({actions:f})),m(new Set(f.map(M=>M.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(vu,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!j||l||w.current)return;const f=window.setTimeout(()=>{w.current||(w.current=!0,(async()=>{try{await C(v.actions)}finally{w.current=!1}})())},Du);return()=>{window.clearTimeout(f)}},[j,l,C,v.actions]);const N=i.useCallback(()=>{const f=Tu();a(I=>[...I,f])},[]),b=i.useCallback(f=>{a(I=>I.filter(M=>M.id!==f))},[]),h=i.useCallback((f,I)=>{a(M=>M.map(T=>T.id===f?I(T):T))},[]);return t.jsx(Bi,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Me,{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..."}):o.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:F("space-y-6",ku),children:o.map((f,I)=>{const M=f.icon||"play",T=Li[M]||"play",O=f.name.trim()||`Action ${I+1}`,P=Nu(f);return t.jsxs("div",{className:Ai,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ri,children:O}),t.jsx(Me,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>b(f.id),"aria-label":`Delete ${O}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Es,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(as,{children:[t.jsx(ls,{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:T,className:"h-4 w-4"})})}),t.jsx(Xt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Fi.map(B=>{const z=B.Icon,U=(f.icon||"play")===B.key;return t.jsx("button",{type:"button",onClick:()=>h(f.id,ne=>({...ne,icon:B.key})),className:F("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",U&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${B.label}`,children:t.jsx(k,{name:z,className:"h-4 w-4"})},B.key)})})})]}),t.jsx(Ls,{value:f.name,onChange:B=>h(f.id,z=>({...z,name:B.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Es,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(Dr,{value:f.command,onChange:B=>h(f.id,z=>({...z,command:B.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),P?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(gu,{checked:f.autoOpenUrl===!0,onChange:B=>h(f.id,z=>({...z,...B?{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 ${O}`}),f.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Es,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Ls,{value:f.openUrl||"",onChange:B=>h(f.id,z=>({...z,openUrl:B.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Es,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:x.length>0?t.jsxs(Cl,{value:f.desktopOpenSshForward&&x.some(B=>B.id===f.desktopOpenSshForward)?f.desktopOpenSshForward:"__none__",onValueChange:B=>{h(f.id,z=>({...z,...B==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:B}}))},children:[t.jsx(Nl,{size:lu,className:"w-full",children:t.jsx(Il,{placeholder:"Use output/manual URL"})}),t.jsxs(Dl,{children:[t.jsx(Xr,{value:"__none__",children:"Use output/manual URL"}),x.map(B=>t.jsx(Xr,{value:B.id,children:B.label},B.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},f.id)})})})},Mu={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)"},Au=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=qt(P=>P.providers),d=qt(P=>P.modelsMetadata),u=de(P=>P.hiddenModels),y=de(P=>P.providerOrder),m=de(P=>P.setProviderOrder),w=de(P=>P.isFavoriteModel),x=de(P=>P.toggleFavoriteModel),v=de(P=>P.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:j}=Pl(),[C,N]=i.useState(!1),[b,h]=i.useState("");i.useEffect(()=>{C||h("")},[C]);const f=e?c.find(P=>P.id===e.providerId):void 0,I=e&&f?(Array.isArray(f.models)?f.models:[]).find(P=>P.id===e.modelId):void 0,M=e?Tl(I,e.modelId):s,T=i.useMemo(()=>e?u.filter(P=>!(P.providerID===e.providerId&&P.modelID===e.modelId)):u,[u,e]),O=i.useCallback(P=>{l({providerId:P.providerID,modelId:P.modelID}),N(!1)},[l]);return t.jsxs(as,{modal:!1,open:C,onOpenChange:P=>{r||N(P)},children:[t.jsx(ls,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:F(Ml({size:"default"}),cu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(El,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:F("truncate",e?"text-foreground":"text-muted-foreground"),children:M})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Xt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Al,{providers:c,favoriteModels:g,recentModels:j,modelsMetadata:d,searchQuery:b,onSearchQueryChange:h,onSelect:O,labels:{...Mu,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:T,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),N(!1)},disabled:r,autoFocus:!0,onEscape:()=>N(!1),isFavorite:P=>w(P.providerID,P.modelID),onToggleFavorite:P=>x(P.providerID,P.modelID),onReorderFavorite:(P,B)=>v(P.providerID,P.modelID,B.providerID,B.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:y,onReorderProvider:m,reorderProviderTitle:"Drag to reorder provider"})})]})},Gn="w-full max-w-none",Ru=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=qt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Bi,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ai,children:[t.jsx(Es,{label:"Name",settingsItem:"projects.name",controlClassName:Gn,children:t.jsx(Ls,{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(Es,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Gn,children:t.jsx(Au,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Gn,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Fu=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>Rl(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,y)=>{o(u&&y?`${u}/${y}`:void 0)},[]),d=i.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}},Lu=450,Ou=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.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{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},Lu);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},Bu=({project:e,onIdentitySave:s})=>{const n=Fu(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Ou(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Ru,{form:n}),t.jsx(Eu,{projectRef:r})]})};function _u({...e}){return t.jsx(wi,{...e})}function $u({...e}){return t.jsx(Si,{...e})}function zu({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(lr,{children:t.jsx(cr,{className:F("app-region-no-drag z-50",s),children:t.jsx(dr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:F(rr,e),...o,children:n})})})}function Co({className:e,...s}){return t.jsx(ji,{className:F(ni,e),...s})}function Uu({className:e,...s}){return t.jsx(ki,{className:F(ri,e),...s})}const gs=hs()(Ci(kr((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 $l();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 _l();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 Bl();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 o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=yi()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await rs("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.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():"",o=r.length>0?r:"";return await bi({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o: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 ss("saving"),await Ol(r),ss("saved"),await s().loadProfiles(),!0}catch(r){return ss("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(l=>l.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};return ss("saving"),await Ll(n,a),ss("saved"),await s().loadProfiles(),!0}catch(o){return ss("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{return ss("saving"),await Fl(n),ss("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ss("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Zc(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=gs);const Ku=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"content",kind:"split",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"content",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"content",kind:"split",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"Magic Prompts",group:"content",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request"]},{slug:"snippets",title:"Snippets",group:"content",kind:"split",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"]},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Gu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Hu(e){const s=e.trim().toLowerCase();return Ku.find(n=>n.slug===s)??null}function Wu(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=Gu[s];if(n)return n;const r=Hu(s);return r?r.slug:"home"}function Dp(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 ln=100;function Pp(){const e=de(T=>T.isArchivePageOpen),s=de(T=>T.setArchivePageOpen),n=de(T=>T.setActiveMainTab),r=De(T=>T.setCurrentSession),o=De(T=>T.unarchiveSession),a=us(T=>T.homeDirectory),l=or({archived:!0}),[c,d]=i.useState(""),[u,y]=i.useState(null),[m,w]=i.useState(ln),x=c.trim().toLowerCase(),v=i.useMemo(()=>e?[...l].sort((T,O)=>(O.time?.archived??0)-(T.time?.archived??0)):[],[l,e]),g=i.useMemo(()=>{const T=new Map;for(const O of v){const P=Qe(As(O))??"",B=T.get(P);if(B){B.sessions.push(O);continue}T.set(P,{directory:P,label:P?ys(P,a)||P:"other projects",sessions:[O]})}return[...T.values()].sort((O,P)=>P.sessions.length-O.sessions.length)},[a,v]),j=i.useMemo(()=>x?v.filter(T=>(T.title??"").toLowerCase().includes(x)):u===null?v:g.find(T=>T.directory===u)?.sessions??[],[g,x,u,v]),C=j.slice(0,m),N=j.length-C.length,b=l.length,h=i.useCallback(T=>{y(T),w(ln)},[]),f=i.useCallback(T=>{const O=Qe(As(T));r(T.id,O??void 0),n("chat"),s(!1)},[n,r,s]),I=i.useCallback(T=>{o(T.id).then(O=>{O?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const M=(T,O,P,B,z,U,ne)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:z,title:U,className:F("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",ne?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",B?"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:O}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:P})]}),ne?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>vs.requestDelete({sessions:ne,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 ${O}`,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]},T);return t.jsx(bd,{open:e,onOpenChange:s,children:t.jsxs(yd,{children:[t.jsx(vd,{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(wd,{className:"pointer-events-auto flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-border/70 bg-sidebar px-4",children:[t.jsxs(Sd,{className:"flex items-center gap-2 typography-ui-label font-medium text-foreground",children:[t.jsx(k,{name:"archive",className:"size-4 text-muted-foreground"}),"Archived sessions"]}),t.jsx("button",{type:"button",onClick:()=>s(!1),className:"inline-flex size-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Close archived sessions",children:t.jsx(k,{name:"close",className:"size-4"})})]}),t.jsx(jd,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[M("__all__","All directories",b,u===null,()=>h(null)),g.map(T=>M(T.directory||"__none__",T.label,T.sessions.length,u===T.directory,()=>h(T.directory),T.directory||void 0,T.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:T=>{d(T.target.value),w(ln)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:j.length===1?`${j.length} archived session`:`${j.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[C.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:x?"No matching archived sessions":"No archived sessions"})}):C.map(T=>{const O=Qe(As(T))??"",P=O?ys(O,a)||O: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:()=>f(T),role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),f(T))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:T.title||"Untitled Session"}),x&&P?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:O,children:P}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:oi(T.time?.archived??T.time?.updated??T.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),I(T)},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 ${T.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),vs.requestDelete({sessions:[T],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 ${T.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},T.id)}),N>0?t.jsx("button",{type:"button",onClick:()=>w(T=>T+ln),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 qu=()=>{const[e,s]=Ue.useState(!1),[n,r]=Ue.useState(!1);Ue.useEffect(()=>{s(wr()),r(Sr())},[]);const o=Ue.useCallback(async c=>e?await jr(c):{success:!0,path:c},[e]),a=Ue.useCallback(async c=>e?await Xc():{success:!0},[e]),l=Ue.useCallback(async c=>e?await ed():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}},Qu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Vu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=i.useState(!1),[y,m]=i.useState(""),[w,x]=i.useState(!1),[v,g]=i.useState(!1),[j,C]=i.useState(""),[N,b]=i.useState(!1),h=i.useRef(null),f=i.useCallback(K=>{K.stopPropagation()},[]),I=l.length>1,M=i.useMemo(()=>Qu(j),[j]),T=i.useMemo(()=>{const K=y.toLowerCase();return K?s.filter(G=>G.toLowerCase().includes(K)):s},[y,s]),O=i.useMemo(()=>{const K=y.toLowerCase();return K?n.filter(G=>G.toLowerCase().includes(K)):n},[y,n]),P=K=>{if(K===e){u(!1);return}o(K),u(!1),m("")},B=()=>{x(!0),setTimeout(()=>h.current?.focus(),50)},z=async()=>{if(!(!M||N)){if(I){g(!0);return}b(!0);try{await a(M,l[0]),C(""),x(!1),u(!1)}finally{b(!1)}}},U=async K=>{if(!(!M||N)){b(!0);try{await a(M,K),C(""),x(!1),g(!1),u(!1)}finally{b(!1)}}},ne=()=>{g(!1)},se=()=>{C(""),x(!1),g(!1)};return i.useEffect(()=>{d||(m(""),x(!1),g(!1),C(""))},[d]),t.jsxs(as,{open:d,onOpenChange:u,children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsxs(Me,{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(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(zl,{className:"h-full min-h-0",children:[t.jsx(Ul,{placeholder:"Search branches...",value:y,onValueChange:m,onKeyDown:f}),t.jsxs(Kl,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Gl,{children:"No branches found."}),t.jsx($n,{children:v?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:ne,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:M})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(K=>t.jsxs("button",{type:"button",onClick:()=>U(K),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,K.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:K.pushUrl})]},K.name))})]}):w?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:h,placeholder:"New branch name",value:j,onChange:K=>C(K.target.value),onClick:K=>K.stopPropagation(),onKeyDown:K=>{f(K),K.key==="Enter"?(K.preventDefault(),z()):K.key==="Escape"&&(K.preventDefault(),se())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:z,disabled:!M||N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:N?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:se,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(Us,{onSelect:B,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(eo,{}),t.jsxs($n,{heading:"Local branches",children:[T.map(K=>t.jsxs(Us,{onSelect:()=>P(K),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:K}),(r?.[K]?.ahead||r?.[K]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[K].ahead||0," ahead ·"," ",r[K].behind||0," behind"]})]}),e===K&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${K}`)),T.length===0&&t.jsx(Us,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(eo,{}),t.jsxs($n,{heading:"Remote branches",children:[O.map(K=>t.jsx(Us,{onSelect:()=>P(K),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:K})},`remote-${K}`)),O.length===0&&t.jsx(Us,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Yu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Ju=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,d]=i.useState(!1),u=i.useRef(null),y=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!e||!s||!a.trim())return;const v=Yu(a);if(v===e){o(!1);return}d(!0);try{await s(e,v),o(!1),l("")}finally{d(!1)}},w=()=>{o(!1),l("")},x=v=>{v.key==="Enter"?(v.preventDefault(),m()):v.key==="Escape"&&(v.preventDefault(),w())};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:v=>{v.preventDefault(),m()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:v=>l(v.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:x,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:w,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(Me,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:y,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},Zu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:y=!1})=>{const m=i.useRef(!1),w=!!l,x=s.find(f=>f.name===u)??s[0],v=d>0&&y,g=a||e!==null||w||!x||v,j=a||e!==null||w||s.length===0,C=c>0||d>0,N=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),b=v?"Commit or stash your changes before syncing":x?C?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",h=()=>{x&&r(x)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:v?0:void 0,children:t.jsxs("button",{type:"button",onClick:h,disabled:g,className:F("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:N})]})})}),t.jsx(st,{sideOffset:8,children:b})]}),t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:j,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Xt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(f=>t.jsx(Ft,{onSelect:I=>{if(m.current){I.preventDefault(),m.current=!1;return}n(f)},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 ${f.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:f.fetchUrl})]})}),o&&f.name!==u?t.jsx(Me,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||w,onPointerDown:I=>{m.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{m.current=!0,I.preventDefault(),I.stopPropagation(),o(f)},"aria-label":`Remove remote ${f.name}`,title:`Remove remote ${f.name}`,children:l===f.name?t.jsx(k,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(k,{name:"close",className:"size-3.5"})}):null]})},f.name))})]})]})},Xu={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ef={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 _i(e){return e&&ef[e]||"var(--primary)"}const No=({icon:e,className:s,colorToken:n})=>{const r=Xu[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:_i(n)}})},$i=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsxs(Me,{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:_i(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(No,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&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(Xt,{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(Ft,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(No,{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)})})]})},tf=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=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}),o?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})]})},Tp=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:y,onCreateBranch:m,onRenameBranch:w,activeIdentityProfile:x,availableIdentities:v,onSelectIdentity:g,isApplyingIdentity:j,isWorktreeMode:C,onOpenHistory:N,onOpenGraph:b,onOpenStashes:h,onOpenUpdateBranch:f,onOpenReintegrateCommits:I,pullRequest:M,prChecks:T,onOpenPullRequest:O})=>{if(!e)return null;const P=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:N||b||h||f?t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsx(Me,{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(Xt,{align:"end",children:[N?t.jsxs(Ft,{onSelect:N,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,b?t.jsxs(Ft,{onSelect:b,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,h?t.jsxs(Ft,{onSelect:h,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,f?t.jsxs(Ft,{onSelect:f,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?t.jsxs(Ft,{onSelect:I,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),B=T?T.state==="success"?"var(--status-success)":T.state==="failure"?"var(--status-error)":"var(--status-warning)":null,z=M?M.state==="merged"?"merged":M.state==="closed"?"closed":M.draft?"draft":T?.state==="failure"||M.mergeable===!1||M.mergeableState==="blocked"||M.mergeableState==="dirty"?"blocked":"open":null,U=M&&O?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs(Me,{variant:"ghost",size:"sm",onClick:O,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-${z})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${M.number}`}),B?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:B}}):null]})}),t.jsx(st,{sideOffset:8,children:"Open pull request"})]}):null,ne=t.jsx(Zu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),se=e.upstreamComparison?t.jsx(tf,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,K=t.jsx($i,{activeProfile:x,identities:v,onSelect:g,isApplying:j,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:C?t.jsx(Ju,{currentBranch:e.current,onRename:w}):t.jsx(Vu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:y,onCreate:m,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:K})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[U?t.jsx("div",{className:"shrink-0",children:U}):null,t.jsx("div",{className:"min-w-0 flex-1"}),se?t.jsx("div",{className:"min-w-0 shrink",children:se}):null,P,t.jsx("div",{className:"shrink-0",children:ne})]})]})},sf=e=>e==="/",Rs=e=>e.replace(/\\/g,"/"),Os=e=>{if(!e||sf(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),Cn=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},Pr=e=>e.lastIndexOf("/"),zi=e=>{if(Fs(e))return e;const s=Pr(e);return s<0?e:e.slice(0,s+1)},Ui=e=>{const s=Pr(e);return e.slice(s+1)},Ki=e=>{const s=Os(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=Pr(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Gi=e=>Fs(e)&&Ki(e)!==null,nf=e=>{if(!Gi(e))return null;const s=Os(e.trim());return Ui(s)||s},rf=(e,s)=>`${zi(e)}${s}/`,ps=e=>{if(!e)return null;const s=Os(Rs(e.trim()));return s?s.toLowerCase():null},Io=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},of=(e,s)=>{const n=Os(Rs(e.trim())),r=Os(Rs(s.trim()));if(!n)return"";if(!r)return Cn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Cn(n)},af=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Hn=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},lf=async()=>rd(),cf=({open:e,onOpenChange:s})=>{const n=us(D=>D.homeDirectory),r=kt(D=>D.projects),o=kt(D=>D.addProject),a=de(D=>D.setActiveMainTab),l=de(D=>D.setSessionSwitcherOpen),c=De(D=>D.openNewSessionDraft),d=gs(D=>D.profiles),u=gs(D=>D.globalIdentity),y=gs(D=>D.defaultGitIdentityId),m=gs(D=>D.loadProfiles),w=gs(D=>D.loadGlobalIdentity),x=gs(D=>D.loadDefaultGitIdentityId),{canRequestAccess:v,startAccessing:g}=qu(),{isMobile:j}=Vs(),C=i.useRef(null),N=i.useRef(new Map),[b,h]=i.useState(""),[f,I]=i.useState("~/"),[M,T]=i.useState([]),[O,P]=i.useState(!1),[B,z]=i.useState(!1),[U,ne]=i.useState(null),[se,K]=i.useState(0),[G,R]=i.useState(0),[A,V]=i.useState(!1),[le,$]=i.useState(!1),[ke,Ie]=i.useState(!1),[_e,Ge]=i.useState(""),[Fe,ve]=i.useState(null),[Te,me]=i.useState(!1),[He,we]=i.useState("right"),xe=i.useRef("~/"),Ce=b||n,Ve=i.useMemo(()=>new Set(r.map(D=>ps(D.path)).filter(D=>!!D)),[r]);i.useEffect(()=>{if(!e)return;I("~/"),T([]),R(0),V(!1),$(!1),Ie(!1),Ge(""),ve(null),me(!1),xe.current="~/",we("right"),requestAnimationFrame(()=>Hn(C.current));let D=!1;return(async()=>{const Ne=await lf();D||(h(Ne||n||""),requestAnimationFrame(()=>Hn(C.current)))})(),()=>{D=!0}},[n,e]),i.useEffect(()=>{e&&(m(),w(),x())},[x,m,w,e]);const Be=i.useMemo(()=>{const D=new Map;u&&D.set(u.id,u);for(const fe of d)D.set(fe.id,fe);return Array.from(D.values())},[d,u]);i.useEffect(()=>{if(!e||!ke||Fe!==null)return;const D=typeof y=="string"?y.trim():"";if(D&&Be.some(Ne=>Ne.id===D)){ve(D);return}const fe=Be.find(Ne=>Ne.authType==="ssh"||Ne.sshKey);fe&&ve(fe.id)},[Be,y,ke,e,Fe]);const W=i.useMemo(()=>Be.find(D=>D.id===Fe)??null,[Be,Fe]),H=i.useMemo(()=>zi(f),[f]),ie=i.useMemo(()=>Fs(f)?"":Ui(f),[f]),pe=i.useMemo(()=>Ce?Io(H,Ce):"",[H,Ce]);i.useEffect(()=>{const D=xe.current;D!==H&&(we(H.length>=D.length?"right":"left"),xe.current=H)},[H]),i.useEffect(()=>{if(!e||!pe){T([]),ne(null);return}let D=!1;return P(!0),z(!1),ne(null),td(pe).then(fe=>{if(D)return;z(!1),ne(null);const Ne=fe.filter(Le=>Le.isDirectory).map(Le=>({name:Le.name,path:Rs(Le.path)})).sort((Le,We)=>Le.name.localeCompare(We.name));T(Ne)}).catch(fe=>{if(!D){T([]);const Ne=sd(fe)?fe.reason:"unknown";ne(Ne),z(Ne==="not-found")}}).finally(()=>{D||P(!1)}),()=>{D=!0}},[pe,se,e]);const Se=i.useMemo(()=>{const D=ie.toLowerCase(),fe=Te||ie.startsWith(".");return M.filter(Ne=>Ne.name.toLowerCase().startsWith(D)&&(fe||!Ne.name.startsWith(".")))},[ie,M,Te]),Y=i.useMemo(()=>nf(f),[f]),be=i.useMemo(()=>Ki(f),[f]),ue=i.useMemo(()=>{const D=[],fe=ps(pe);Gi(f)&&Y&&be&&D.push({type:"parent",value:"browse:up",name:Y,path:be,alreadyAdded:!!(fe&&Ve.has(fe))});for(const Ne of Se){const Le=ps(Ne.path);D.push({type:"directory",value:`browse:${Ne.path}`,name:Ne.name,path:Ne.path,alreadyAdded:!!(Le&&Ve.has(Le))})}return D},[Ve,pe,Y,Se,be,f]);i.useEffect(()=>{R(0)},[f,ue.length]);const Ye=i.useMemo(()=>Ce?Os(Io(f,Ce)):"",[Ce,f]),at=ps(Ye),ze=!!(at&&Ve.has(at)),je=i.useMemo(()=>ie?Se.find(D=>D.name===ie)??null:null,[ie,Se]),Ae=!!(Ye&&!ze&&(U===null||U==="not-found")&&(Fs(f)&&B||!Fs(f)&&ie.trim().length>0&&je===null)),ot=!A&&!le&&!ze&&U!=="os-permission"&&U!=="invalid-response"&&U!=="unknown"&&!!Ye,ht=ot&&_e.trim().length>0,pt=ue[G]??null,ge=!!pt,Je=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Tt=ze?"Already added":ke?A?"Cloning...":"Clone & add":A?"Adding...":Ae?"Create & add":"Add folder",S=ke?ht:ot;i.useLayoutEffect(()=>{const D=C.current;D&&(D.scrollLeft=D.scrollWidth)},[f]),i.useLayoutEffect(()=>{e&&Hn(C.current)},[e]),i.useLayoutEffect(()=>{const D=ue[G];D&&N.current.get(D.value)?.scrollIntoView({block:"nearest"})},[G,ue]);const Z=i.useCallback(()=>{s(!1)},[s]),ae=i.useCallback((D,fe)=>{a("chat"),j&&l(!1),c({selectedProjectId:D,directoryOverride:fe}),Z()},[Z,j,c,a,l]),ye=i.useCallback(async D=>{if(!D||A)return;const fe=ps(D);if(fe&&Ve.has(fe))return;let Ne=D;V(!0);try{const Le=!ke&&Ae&&ps(D)===ps(Ye);if(ke){const Ct=_e.trim();if(!Ct){oe.error("Enter a repository URL before cloning.");return}const E=await rs("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:Ct,destinationPath:D,gitIdentityId:W?.id??null})});if(!E.ok)throw new Error("Failed to clone git repository");Ne=(await E.json()).path||D}else if(Le&&!(await rs("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:pe?{directory:pe}:void 0,body:JSON.stringify({path:D})})).ok)throw new Error("Failed to select directory");const We=o(Ne);if(!We){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}ae(We.id,We.path)}catch(Le){oe.error("Failed to select directory",{description:Le instanceof Error?Le.message:"Unknown error occurred."})}finally{V(!1)}},[o,Ve,pe,_e,ke,A,ae,W?.id,Ae,Ye]),Re=i.useCallback(D=>{I(Cn(D))},[]),Ke=i.useCallback(D=>{I(rf(f,D.name))},[f]),nt=i.useCallback(D=>{if(D){if(D.type==="parent"){Re(D.path);return}Ke(D)}},[Re,Ke]),ct=i.useCallback(async D=>{const fe=await g(D);if(!fe.success)return oe.error("Failed to open directory",{description:fe.error||"Desktop could not grant file access."}),!1;const Ne=Ce?of(D,Ce):Cn(Rs(D));return Re(Ne),!0},[Re,Ce,g]),Gt=i.useCallback(async()=>{if(!le){$(!0);try{if(Sr()){const fe=await jr(Ye);if(!fe.success||!fe.path){fe.error&&fe.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:fe.error});return}await ct(fe.path);return}const D=await nd(Ye);if(D.status==="cancelled")return;if(D.status!=="picked"){oe.error("Couldn't open a folder picker",{description:D.error});return}await ct(D.path)}catch(D){oe.error("Failed to select directory",{description:D instanceof Error?D.message:"Unknown error occurred."})}finally{$(!1)}}},[ct,le,Ye]),it=i.useCallback(D=>{if(D.key==="ArrowDown"){D.preventDefault(),R(fe=>Math.min(ue.length-1,fe+1));return}if(D.key==="ArrowUp"){D.preventDefault(),R(fe=>Math.max(0,fe-1));return}if(D.key==="Enter"){if(D.preventDefault(),af(D)){ye(Ye);return}ge&&nt(pt);return}D.key==="Backspace"&&f===""&&(D.preventDefault(),Z())},[nt,ye,Z,ge,pt,f,ue.length,Ye]),gt=t.jsxs("button",{type:"button",onClick:()=>me(D=>!D),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[Te?t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),yt=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(Ls,{ref:C,value:f,onChange:D=>I(Rs(D.target.value)),onKeyDown:it,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Me,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:A||le,onMouseDown:D=>D.preventDefault(),onClick:()=>{Gt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),le?"Opening...":"Browse"]})]})}),Ze=ue.some(D=>D.type==="parent"),Bt=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(Me,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":ke,disabled:A||le,onClick:()=>Ie(D=>!D),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),ke?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(Ls,{value:_e,onChange:D=>Ge(D.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($i,{activeProfile:W,identities:Be,onSelect:D=>ve(D.id),isApplying:A,iconOnly:!0})]})]}):null,ze?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:F("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",He==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:O?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):U&&U!=="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:U==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[U==="os-permission"&&v?t.jsx(Me,{size:"xs",onClick:()=>{Gt()},disabled:le,children:"Grant access"}):null,t.jsx(Me,{variant:"outline",size:"xs",onClick:()=>K(D=>D+1),children:"Try again"})]})]}):ue.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:ue.map((D,fe)=>{const Ne=fe===G,Le=D.type==="directory"&&Ze;return t.jsxs("button",{ref:We=>{We?N.current.set(D.value,We):N.current.delete(D.value)},type:"button","aria-label":D.type==="parent"?D.alreadyAdded?`Go back from ${D.name}, already added`:`Go back from ${D.name}`:D.alreadyAdded?`Open ${D.name}, already added`:`Open ${D.name}`,onMouseEnter:()=>R(fe),onMouseDown:We=>We.preventDefault(),onClick:()=>nt(D),className:F("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ne&&"bg-interactive-selection text-interactive-selection-foreground",!Ne&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:F("flex min-w-0 flex-1 items-center gap-2",Le&&"pl-4"),children:[D.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:D.name})]}),D.alreadyAdded?t.jsx("span",{className:F("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ne?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,D.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"})]},D.value)})})},H)]})}),_t=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[yt,Bt]}),Et=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:Je}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),xt=t.jsx(Me,{size:j?"xs":"default",onClick:()=>{ye(Ye)},disabled:!S,className:F(j&&"w-full flex-1"),children:Tt}),Mt=()=>t.jsxs(t.Fragment,{children:[j?null:Et,t.jsx("div",{className:F("flex w-full flex-row justify-end gap-2 sm:w-auto",j&&"justify-stretch"),children:xt})]});return j?t.jsx(ii,{open:e,onClose:Z,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:Mt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:gt}),_t]})}):t.jsx(os,{open:e,onOpenChange:s,children:t.jsxs(is,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(ws,{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(fs,{children:"Add folder"}),t.jsx(Bs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),gt]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:_t}),t.jsx(_s,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:Mt()})]})})},cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Ep=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(!1),[o,a]=i.useState(null),[l,c]=i.useState(!1),d=Hl,u=De(P=>P.deleteSessions),y=de(P=>P.showDeletionDialog),m=de(P=>P.setShowDeletionDialog),w=us(P=>P.isHomeReady),x=kt(P=>P.projects),{isMobile:v,isTablet:g,hasTouchInput:j}=Vs(),C=v||g||j;i.useEffect(()=>{n||!w||x.length>0||(r(!0),s(!0))},[n,w,x.length]);const N=i.useCallback(P=>{a({sessions:P.sessions,dateLabel:P.dateLabel})},[]),b=i.useCallback(()=>{a(null),c(!1)},[]),h=i.useCallback(async P=>{if(P.sessions.length===0)return;if(P.sessions.length===1){const ne=P.sessions[0];await d(ne.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const B=P.sessions.map(ne=>ne.id),{deletedIds:z,failedIds:U}=await u(B);if(z.length>0){const ne=U.length>0?U.length===1?`${U.length} session could not be deleted.`:`${U.length} sessions could not be deleted.`:P.dateLabel?`Removed all sessions from ${P.dateLabel}.`:void 0;oe.success(z.length===1?"Deleted {count} session":`Deleted ${z.length} sessions`,{description:cn(ne)})}U.length>0&&oe.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`,{description:cn("Please try again in a moment.")})},[d,u]);i.useEffect(()=>vs.onDeleteRequest(P=>{if(!y){h(P);return}N(P)}),[N,y,h]),i.useEffect(()=>vs.onDirectoryRequest(()=>{s(!0)}),[]);const f=i.useCallback(async()=>{if(o){c(!0);try{if(o.sessions.length===1){const P=o.sessions[0];if(!await d(P.id)){oe.error("Failed to delete session"),c(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const P=o.sessions.map(ne=>ne.id),B=await u(P),z=B.deletedIds,U=B.failedIds;if(z.length>0){const ne=U.length>0?U.length===1?`${U.length} session could not be deleted.`:`${U.length} sessions could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0;oe.success(z.length===1?"Deleted {count} session":`Deleted ${z.length} sessions`,{description:cn(ne),action:{label:"OK",onClick:()=>{}}})}if(U.length>0&&(oe.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`,{description:cn("Please try again in a moment.")}),z.length===0)){c(!1);return}}b()}finally{c(!1)}}},[o,d,u,b]),I=o?o.sessions.length===1?o.dateLabel?`This action permanently removes 1 session from ${o.dateLabel}.`:"This action permanently removes 1 session.":o.dateLabel?`This action permanently removes ${o.sessions.length} sessions from ${o.dateLabel}.`:`This action permanently removes ${o.sessions.length} sessions.`:"",M=o?t.jsxs("div",{className:"space-y-2",children:[o.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:[o.sessions.slice(0,5).map(P=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})},P.id)),o.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${o.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,T=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>m(!y),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":!y,children:[y?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(Me,{variant:"ghost",onClick:b,disabled:l,children:"Cancel"}),t.jsx(Me,{variant:"destructive",onClick:f,disabled:l,children:l?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),O=o?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[C?t.jsx(ii,{open:!!o,onClose:()=>{l||b()},title:O,footer:t.jsx("div",{className:"flex justify-end gap-2",children:T}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),M]})}):t.jsx(os,{open:!!o,onOpenChange:P=>{if(!P){if(l)return;b()}},children:t.jsxs(is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(ws,{children:[t.jsx(fs,{children:O}),I&&t.jsx(Bs,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:M}),t.jsx(_s,{className:"mt-2 gap-2 pt-1 pb-1",children:T})]})}),t.jsx(cf,{open:e,onOpenChange:s})]})};function Mp(){const e=i.useMemo(()=>ti(),[]),s=i.useRef(!1),n=i.useRef(!1),r=De(m=>m.setCurrentSession),o=de(m=>m.setActiveMainTab),a=de(m=>m.setSettingsDialogOpen),l=de(m=>m.setSettingsPage),c=de(m=>m.navigateToDiff),d=i.useCallback(async m=>{if(!n.current){n.current=!0;try{if(m.sessionId){const w=De.getState().currentSessionId,x=Ds().getState().selectedSessionId;if(m.sessionId!==w||m.sessionId!==x){const g=(e&&typeof window<"u"?new URLSearchParams(window.location.search).get("directory"):null)||De.getState().getDirectoryForSession(m.sessionId);r(m.sessionId,g)}}if(m.settingsPath){l(Wu(m.settingsPath)),a(!0);return}de.getState().isSettingsDialogOpen&&a(!1),m.tab&&o(m.tab),m.diffFile&&(m.tab==="diff"||!m.tab)&&c(m.diffFile)}finally{n.current=!1}}},[e,r,o,a,l,c]),u=i.useCallback(()=>{const m=De.getState(),w=Ds().getState(),x=de.getState();return{sessionId:m.currentSessionId??w.selectedSessionId,tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),y=i.useCallback((m={})=>{if(e||n.current)return;const w=u();ur(w,m)},[e,u]);i.useEffect(()=>{if(s.current||(s.current=!0,!to()))return;const m=so();(async()=>(await d(m),e||ur({...u(),sessionId:m.sessionId??De.getState().currentSessionId??Ds().getState().selectedSessionId,tab:m.tab??de.getState().activeMainTab,settingsPath:m.settingsPath??de.getState().settingsPage,diffFile:m.diffFile??de.getState().pendingDiffFile},{replace:!0,force:!0})))()},[d,u,e]),i.useEffect(()=>{if(e)return;let m=De.getState().currentSessionId??Ds().getState().selectedSessionId;const w=g=>{!g||g===m||n.current||(m=g,y({replace:!0}))},x=De.subscribe(g=>{w(g.currentSessionId)}),v=Ds().subscribe(()=>{w(Ds().getState().selectedSessionId)});return()=>{x(),v()}},[e,y]),i.useEffect(()=>{if(e)return;let m=de.getState().activeMainTab,w=de.getState().isSettingsDialogOpen,x=de.getState().settingsPage,v=de.getState().pendingDiffFile;return de.subscribe(j=>{if(n.current)return;const C=j.activeMainTab!==m,N=j.isSettingsDialogOpen!==w,b=j.settingsPage!==x,h=j.pendingDiffFile!==v&&j.activeMainTab==="diff";m=j.activeMainTab,w=j.isSettingsDialogOpen,x=j.settingsPage,v=j.pendingDiffFile,(C||N||b||h)&&y()})},[e,y]),i.useEffect(()=>{if(typeof window>"u"||e)return;const m=()=>{const w=so();if(to())d(w);else{const x=de.getState();x.isSettingsDialogOpen&&a(!1),x.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[d,e,o,a])}function Ap(){const e=yn(n=>n.checkForUpdates),s=i.useRef(e);i.useEffect(()=>{s.current=e},[e]),i.useEffect(()=>{let l=!1,c=null;const d=y=>{const m=Math.round(y*1e3);return Math.max(3e5,Math.min(864e5,m))},u=y=>{l||(c=window.setTimeout(async()=>{const m=await s.current(),w=typeof m=="number"&&Number.isFinite(m)?d(m):36e5;u(w)},y))};return u(3e3),()=>{l=!0,c!==null&&window.clearTimeout(c)}},[])}const Do=12,df=[{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"}],uf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=df,onComplete:a})=>{const l=Ue.useRef(!1);Ue.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ue.useMemo(()=>Array.from({length:Do},(d,u)=>{const y=Math.PI*2*u/Do;return{x:Math.cos(y),y:Math.sin(y),delay:u*18}}),[]);return e?t.jsx("div",{className:F("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.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((y,m)=>{const w=y.x*d.radius,x=y.y*d.radius,v={"--translate-x":`${w}px`,"--translate-y":`${x}px`,"--particle-delay":`${y.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:v},`${d.id}-${m}-${s}`)})},`${d.id}-${s}`)})}):null},ff=({durationMs:e=3400}={})=>{const[s,n]=Ue.useState({isActive:!1,cycle:0}),r=Ue.useRef(null),o=Ue.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ue.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ue.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Ue.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Hi=i.createContext(void 0),Rp=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=ff(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(Hi.Provider,{value:a,children:[e,t.jsx(uf,{isActive:s,burstKey:n})]})},hf={triggerFireworks:()=>{},dismissFireworks:()=>{}},Fp=()=>i.useContext(Hi)??hf,Po=600,mf=1,pf=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},gf=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:o})=>{const a=i.useRef(new Map),l=i.useRef([]),c=i.useRef(new Set),d=i.useRef(0),u=!1,y=i.useCallback(v=>`${v.directory}
3
- ${v.sessionId}`,[]),m=i.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(v=>window.clearTimeout(v)),a.current.clear()},[]),w=i.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<mf&&l.current.length>0;){const v=l.current.shift();if(!v)break;v.generation!==d.current||De.getState().currentSessionId===v.sessionId||Wl(v.sessionId,v.directory).renderable}},[e,u,o,y]),x=i.useCallback(v=>{const g=v?.id,j=pf(v);if(!e||u||!g||!j||g===s||typeof window>"u")return;const C={sessionId:g,directory:j,generation:d.current};y(C)},[s,e,u,w,y]);i.useEffect(()=>{m()},[m,s,e,u]),i.useEffect(()=>{if(!e||u||!s||n.length===0)return;const v=window.setTimeout(()=>{const g=n.findIndex(j=>j.id===s);g<0||(x(n[g-1]),x(n[g+1]))},Po);return()=>window.clearTimeout(v)},[s,e,u,x,n]),i.useEffect(()=>{if(!e||u||!s||r.length===0)return;const v=window.setTimeout(()=>{const g=r.findIndex(j=>j.id===s);g<0||(x(r[g-1]),x(r[g+1]))},Po);return()=>window.clearTimeout(v)},[s,e,u,r,x]),i.useEffect(()=>m,[m])},xf=e=>{const s=De(n=>n.currentSessionId);return gf({...e,currentSessionId:s}),null},bf=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:o,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:y}=e;i.useEffect(()=>{!n||o||!a||l||s.forEach(m=>{if(c.has(m.normalizedPath))return;const w=ai(m.normalizedPath),x=r.archivedSessionsByProject.get(m.id)??[],v=d[w]??[],g=new Map(v.map(j=>[j.name.toLowerCase(),j]));x.forEach(j=>{const C=ql(j,m.normalizedPath),N=C.toLowerCase();let b=g.get(N);b||(b=u(w,C),g.set(N,b)),b.sessionIds.includes(j.id)||y(w,b.id,j.id)})})},[s,n,r,o,a,l,c,d,u,y])},yf=e=>({getOrderedGroups:i.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];o.forEach(u=>{const y=a.get(u);y&&(l.push(y),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])}),vf=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,projectRepoStatus:o,projectRootBranches:a,lastRepoStatus:l,buildGroupedSessions:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:y,buildGroupSearchText:m,foldersMap:w}=e,x=i.useRef(new Map),v=i.useMemo(()=>{const I=x.current,M=new Map;let T=0,O=0;const P=(z,U)=>z.length===U.length&&z.every((ne,se)=>ne===U[se]),B=s.map(z=>{const U=n(z.id),ne=r(z.id),se=o.has(z.id)?!!o.get(z.id):l,K=a.get(z.id)??null,G=I.get(z.id);if(G&&G.project===z&&P(G.activeSessions,U)&&P(G.archivedSessions,ne)&&G.rootBranch===K&&G.isRepo===se&&G.buildGroupedSessions===c)return T+=1,M.set(z.id,G),G.section;O+=1;const R=li([...U,...ne]),A=c(R,z.normalizedPath,[],K,se),V={project:z,groups:A};return M.set(z.id,{project:z,activeSessions:U,archivedSessions:ne,rootBranch:K,isRepo:se,buildGroupedSessions:c,section:V}),V});return x.current=M,T>0&&Zt("ui.sidebar.project_section.reused",T),O>0&&Zt("ui.sidebar.project_section.rebuilt",O),B},[s,n,r,o,l,c,a]),g=i.useMemo(()=>v,[v]),j=i.useMemo(()=>{const I=new WeakMap;if(!d)return I;const M=T=>T.reduce((O,P)=>O+1+M(P.children),0);return g.forEach(T=>{T.groups.forEach(O=>{const P=y(O.sessions,u),B=M(P),z=m(O).includes(u),U=Qe(O.directory??null),se=(U?w[U]??[]:[]).filter(K=>K.name.toLowerCase().includes(u)).length;I.set(O,{filteredNodes:P,matchedSessionCount:B,folderNameMatchCount:se,groupMatches:z,hasMatch:z||B>0||se>0})})}),I},[d,g,y,u,m,w]),C=i.useMemo(()=>d?g.map(I=>({...I,groups:I.groups.filter(M=>j.get(M)?.hasMatch===!0)})).filter(I=>I.groups.length>0):g,[d,g,j]),N=d?C:g,b=i.useRef(new WeakMap),h=i.useMemo(()=>{const I=b.current;return N.map(M=>{const T=I.get(M);if(T&&T.query===u)return T.section;const O=M.groups.filter(K=>!K.isArchivedBucket),P=M.groups.filter(K=>K.isArchivedBucket),B=O.flatMap(K=>d?j.get(K)?.filteredNodes??[]:K.sessions),z=O.map(K=>({scopeKey:K.folderScopeKey??Qe(K.directory??null),directory:K.directory??null})).filter(K=>!!K.scopeKey),U=O.find(K=>K.isMain)??null,ne={id:"flat",label:U?.label??"",branch:U?.branch??null,description:U?.description??null,isMain:!0,isArchivedBucket:!1,directory:U?.directory??M.project.normalizedPath,folderScopeKey:U?.folderScopeKey??M.project.normalizedPath,folderScopes:z,sessions:B};if(d){const K=O.map(G=>j.get(G)).filter(G=>!!G);j.set(ne,{filteredNodes:B,matchedSessionCount:K.reduce((G,R)=>G+R.matchedSessionCount,0),folderNameMatchCount:K.reduce((G,R)=>G+R.folderNameMatchCount,0),groupMatches:K.some(G=>G.groupMatches),hasMatch:K.some(G=>G.hasMatch)})}const se={project:M.project,groups:[ne,...P]};return I.set(M,{query:u,section:se}),se})},[j,d,u,N]),f=i.useMemo(()=>d?N.reduce((I,M)=>I+M.groups.reduce((T,O)=>{const P=j.get(O);if(!P)return T;const B=P.folderNameMatchCount+(P.groupMatches?1:0);return T+P.matchedSessionCount+B},0),0):0,[d,N,j]);return{projectSections:v,visibleProjectSections:g,groupSearchDataByGroup:j,searchableProjectSections:C,sectionsForRender:N,flatSectionsForRender:h,searchMatchCount:f}},wf=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:y,setSessionSwitcherOpen:m}=e,w=i.useMemo(()=>{const v=new Map,g=new Map,j=(C,N,b,h)=>{v.has(C)||v.set(C,new Map);const f=v.get(C);h.forEach(I=>{const M=Qe(I.session.directory??b??N);f.set(I.session.id,{directory:M}),g.has(C)||g.set(C,{id:I.session.id,directory:M}),I.children.length>0&&j(C,N,M,I.children)})};return s.forEach(C=>{C.groups.forEach(N=>{j(C.project.id,C.project.normalizedPath,N.directory,N.sessions)})}),{metaByProject:v,firstSessionByProject:g}},[s]),x=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){x.current=n;return}if(x.current===n)return;const v=s.find(I=>I.project.id===n);if(!v)return;x.current=n;const g=w.metaByProject.get(n);if(a&&g&&g.has(a)){o(I=>{if(I.get(n)===a)return I;const M=new Map(I);return M.set(n,a),M});return}const j=a?Array.from(w.metaByProject.entries()).some(([I,M])=>I!==n&&M.has(a)):!1;if(a&&g&&!j)return;if(!g||g.size===0){y("chat"),d&&m(!1),u({selectedProjectId:v.project.id,directoryOverride:v.project.normalizedPath});return}const C=r.get(n),N=C&&g.has(C)?C:null,b=w.firstSessionByProject.get(n)?.id??null,h=N??b;if(!h||h===a)return;const f=g.get(h)?.directory??null;l(h,f,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,w,y,m,o]),i.useEffect(()=>{if(!n||!a)return;const v=w.metaByProject.get(n);!v||!v.has(a)||o(g=>{if(g.get(n)===a)return g;const j=new Map(g);return j.set(n,a),j})},[n,a,w,o])},Sf=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=De(c=>c.currentSessionId),o=De(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return wf({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},dn=e=>!!e.time?.archived,jf=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=Qe(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=i.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]),o=i.useCallback((a,l,c,d,u)=>{const y=Qe(l??null),m=li(a).sort((b,h)=>jn(b,h,e.pinnedSessionIds,e.sessionOrderRanks)),w=new Map(m.map(b=>[b.id,b])),x=new Map;m.forEach(b=>{const h=b.parentID;if(!h)return;const f=w.get(h);if(!f||dn(f)!==dn(b))return;const I=x.get(h)??[];I.push(b),x.set(h,I)}),x.forEach(b=>b.sort((h,f)=>jn(h,f,e.pinnedSessionIds,e.sessionOrderRanks)));const v=b=>{const h=x.get(b.id)??[];return{session:b,children:h.map(f=>v(f)),worktree:null}},g=m.filter(b=>{const h=b.parentID;if(!h)return!0;const f=w.get(h);return f?dn(f)!==dn(b):!0}),j=[],C=[];g.forEach(b=>{const h=v(b);b.time?.archived?C.push(h):j.push(h)});const N=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:y?Ql(y,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:y,folderScopeKey:y,sessions:j}];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:y?ai(y):null,sessions:C}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},kf=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{i.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]),i.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,o])},Cf=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((b,h,f)=>{ar("navigation.session_select"),de.getState().closeMainSurfaces();const I=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},M=f?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),b===De.getState().currentSessionId){e.allowReselect&&M&&e.onSessionSelected?.(b),I();return}ar("navigation.session_state_set"),e.setCurrentSession(b,h??null),M&&e.onSessionSelected?.(b),I()},[e]),a=i.useCallback((b,h)=>{e.setEditingId(b),e.setEditTitle(h)},[e]),l=i.useCallback(async b=>{if(!e.editingId)return;const h=(b??e.editTitle).trim();h&&await e.updateSessionTitle(e.editingId,h),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=i.useCallback(async(b,h)=>{try{return(await nr(b)).ok?(n(h),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=i.useCallback(async b=>{const h=await e.shareSession(b.id);if(!h?.share?.url){oe.error("Unable to share session");return}const f=await d(h.share.url,b.id);oe[f?"success":"warning"]("Session shared",{description:f?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),y=i.useCallback((b,h)=>{d(b,h).then(f=>{f||oe.error("Failed to copy URL")})},[d]),m=i.useCallback(b=>{nr(b).then(h=>{if(h.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),w=i.useCallback(async b=>{await e.unshareSession(b)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),x=i.useCallback(b=>{const h=[],f=I=>{(e.childrenMap.get(I)??[]).forEach(T=>{h.push(T),f(T.id)})};return f(b),h},[e.childrenMap]),v=i.useCallback((b,h)=>h?b:b.filter(f=>!f.time?.archived),[]),g=i.useCallback(async(b,h,f)=>{const I=h?.archivedBucket===!0||h?.hardDelete===!0,M=f?.descendantIds??v(x(b.id),I).map(B=>B.id);if(M.length===0){(I?await e.deleteSession(b.id):await e.archiveSession(b.id))?oe.success(I?"Session deleted":"Session archived"):oe.error(I?"Failed to delete session":"Failed to archive session");return}const T=[b.id,...M];if(I){const{deletedIds:B,failedIds:z}=await e.deleteSessions(T);if(z.length===0){const U=B.length;oe.success(U===1?`Deleted ${U} session`:`Deleted ${U} sessions`)}else oe.error("Failed to delete session");return}const{archivedIds:O,failedIds:P}=await e.archiveSessions(T);O.length>0&&oe.success(O.length===1?`Archived ${O.length} session`:`Archived ${O.length} sessions`),P.length>0&&oe.error(P.length===1?`Failed to archive ${P.length} session`:`Failed to archive ${P.length} sessions`)},[e,x,v]),j=i.useCallback((b,h)=>{const f=h?.archivedBucket===!0||h?.hardDelete===!0,I=v(x(b.id),f).map(M=>M.id);if(!e.showDeletionDialog||h?.skipConfirm===!0){g(b,h,{descendantIds:I});return}e.setDeleteSessionConfirm({session:b,descendantCount:I.length,descendantIds:I,archivedBucket:f})},[e,x,g,v]),C=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:b,archivedBucket:h,descendantIds:f}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await g(b,{archivedBucket:h},{descendantIds:f})},[e,g]),N=i.useCallback(async b=>{await e.unarchiveSession(b.id)?oe.success("Session restored"):oe.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:y,handleCopySessionId:m,handleUnshareSession:w,handleDeleteSession:j,handleRestoreSession:N,confirmDeleteSession:C}},Nf=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:a,setCollapsedProjects:l}=e,c=i.useRef(null),d=i.useRef(null),u=i.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:w}=kt.getState(),x=w.map(v=>({...v,sidebarCollapsed:m.has(v.id)}));bi({projects:x}).catch(()=>{})},[]),y=i.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return i.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),i.useEffect(()=>{try{const m=s.getItem(n.sessionExpanded);if(m){const x=JSON.parse(m);Array.isArray(x)&&a(new Set(x.filter(v=>typeof v=="string")))}const w=s.getItem(n.projectCollapse);if(w){const x=JSON.parse(w);Array.isArray(x)&&l(new Set(x.filter(v=>typeof v=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const m=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(m))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:y}},If=5*6e4,Df=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=ci(),c=di(m=>m.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(m=>{Bd(()=>c(m.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const m=new Map;s.forEach(w=>{m.set(w.id,r.get(w.normalizedPath)?.isGitRepo??null)}),o(m)},[n,s,r,o]);const d=i.useMemo(()=>s.map(m=>{const w=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${w}`}).join("|"),[s,r]),u=i.useRef(new Map),y=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let m=!1;const w=setTimeout(()=>{(async()=>{const v=new Set(s.map(b=>b.id));for(const b of u.current.keys())v.has(b)||(u.current.delete(b),y.current.delete(b));const g=Date.now();if(s.filter(b=>{const h=r.get(b.normalizedPath);if(h?.isGitRepo===!1)return u.current.delete(b.id),y.current.delete(b.id),!1;if(h?.isGitRepo!==!0||h.branch===null)return!1;const f=h.branch.trim(),I=`${b.normalizedPath}\0${f}`,M=u.current.get(b.id);if(M===I){const T=y.current.get(b.id);return T&&(T.at=g),!1}return!(M!==void 0&&g-(y.current.get(b.id)?.at??0)<If)}).length===0)return;const C=[];if(s.forEach(b=>{const h=r.get(b.normalizedPath)?.branch?.trim()??"",f=`${b.normalizedPath}\0${h}`;h&&C.push({id:b.id,inputKey:f,branch:h})}),m||C.length===0)return;const N=Date.now();a(b=>{const h=new Map(b);return C.forEach(({id:f,branch:I})=>{I&&h.set(f,I)}),h}),C.forEach(({id:b,inputKey:h,branch:f})=>{u.current.set(b,h),f&&y.current.set(b,{branch:f,at:N})})})()},150);return()=>{m=!0,clearTimeout(w)}},[n,s,d,r,a])},Pf=e=>{const{ownership:s}=e,n=i.useCallback(o=>s.sessionsByProject.get(o)??[],[s]),r=i.useCallback(o=>s.archivedSessionsByProject.get(o)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Tf=e=>{if(e.runtimeKey!==Dn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=od(e.sessionId,e.directory,e.runtimeKey);s&&id.getState().clearQueue(s),Vl.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),At.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),ui.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),ir.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Yl(e.runtimeKey,e.directory,e.sessionId);n&&Jl(n,!0)},Ef=e=>{const s=new Map;for(const n of e){const r=As(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Mf=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Af=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Dn(),l=Ef(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const d of Mf(c,l))Tf({runtimeKey:a,...d});o.current={runtimeKey:a,identities:l}},[s,n,r])},Rf=(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,To=(e,s,n)=>{Rf(e.get(s),n)&&e.set(s,n)},Ff=e=>{const s=e;return Qe(s.directory)??Qe(s.project?.worktree)},Lf=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)},Of=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const x of s){const v=Qe(x.normalizedPath);if(!v)continue;const g=a.get(v);(!g||x.id.localeCompare(g.id)<0)&&a.set(v,x),To(o,v,{projectId:x.id,projectRoot:v,scopeDirectory:v,kind:"project"})}if(n)for(const[x,v]of n){const g=Qe(x),j=g?a.get(g):void 0;if(!(!j||!g))for(const C of v||[]){const N=Qe(C?.path);N&&To(o,N,{projectId:j.id,projectRoot:g,scopeDirectory:N,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,y=new Map,m=x=>{if(!x)return null;if(l.has(x))return l.get(x)??null;const v=[];let g=x,j=null;for(;g;){if(l.has(g)){j=l.get(g)??null;break}if(v.push(g),j=o.get(g)??null,j)break;g=Lf(g)}for(const C of v)l.set(C,j);return j},w=(x,v,g)=>{for(const j of x){const C=m(Ff(j));if(!C)continue;c.set(j.id,C);const N=v.get(C.projectId);if(N?N.push(j):v.set(C.projectId,[j]),!g)continue;const b=g.get(C.scopeDirectory);b?b.add(j.id):g.set(C.scopeDirectory,new Set([j.id]))}};return w(e,d,y),w(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:y,directoryResolutions:l.size}},Bf=e=>{const{enabled:s=!0,isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=e,[a,l]=i.useState(new Set);return i.useEffect(()=>{if(!s||!n){l(y=>y.size===0?y:new Set);return}const d=Array.from(o.current.values()).find(y=>y!==null)?.closest(".oc-sidebar-scroller")??null;if(!d)return;const u=new IntersectionObserver(y=>{l(m=>{const w=new Set(m);let x=!1;for(const v of y){const g=v.target.dataset.projectId;if(!g)continue;const j=v.rootBounds?.top??d.getBoundingClientRect().top,C=!v.isIntersecting&&v.boundingClientRect.top<j;w.has(g)!==C&&(x=!0,C?w.add(g):w.delete(g))}return x?w:m})},{root:d,threshold:0});return o.current.forEach(y=>{y&&u.observe(y)}),()=>u.disconnect()},[s,n,o,r]),a},_f=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(os,{open:e,onOpenChange:s,children:t.jsx(is,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(xs,{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(Bu,{project:n,onIdentitySave:r}):null})})})});function Wi({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const $f=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:y,groupDirectory:m,projectId:w,mobileVariant:x=!1,alwaysShowActions:v=x,isRenaming:g=!1,renameDraft:j="",onRenameDraftChange:C,onRenameSave:N,onRenameCancel:b,droppableRef:h,isDropTarget:f=!1,onNewSession:I,depth:M=0,hideActions:T=!1,archivedBucket:O=!1})=>{const[P,B]=i.useState(!1),[z,U]=i.useState(""),ne=i.useRef(null),se=g||P,K=g?j:z,G=i.useCallback(()=>{U(e.name),B(!0)},[e.name]),R=i.useCallback(()=>{const $=K.trim();$&&$!==e.name&&c($),g&&N&&N(),B(!1),U("")},[K,e.name,g,c,N]),A=i.useCallback(()=>{g&&b&&b(),B(!1),U("")},[g,b]),V=i.useCallback($=>{g&&C?C($):U($)},[g,C]);i.useEffect(()=>{if(!g)return;const $=()=>{const _e=ne.current;_e&&(_e.focus(),_e.select())},ke=requestAnimationFrame($),Ie=window.setTimeout($,0);return()=>{cancelAnimationFrame(ke),window.clearTimeout(Ie)}},[g]);const le=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:h,className:F("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",f&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:se?void 0:$=>{$.currentTarget.blur(),l()},role:se?void 0:"button",tabIndex:se?void 0:0,onKeyDown:se?void 0:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:F("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",O?v?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":v?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(k,{name:le,className:F(gn,f?"text-primary":"text-muted-foreground")}),se?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onSubmit:$=>{$.preventDefault(),R()},children:[t.jsx("input",{ref:ne,value:K,onChange:$=>V($.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:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onKeyDown:$=>{if($.key==="Escape"){$.stopPropagation(),A();return}($.key===" "||$.key==="Enter")&&$.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),children:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),A()},onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.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:F(fi,f?"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(Wi,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(k,{name:"arrow-right-s",className:F(gn,"text-muted-foreground")}):t.jsx(k,{name:"arrow-down-s",className:F(gn,"text-muted-foreground")})]})]}),!se&&(!T||O)?t.jsx("div",{className:F("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",v?"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:[!O&&I?t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),I()},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,O?null:t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),G()},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:$=>{$.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":O?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(k,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map($=>t.jsx(i.Fragment,{children:u($,0,m??null,w??null,O,void 0,"project",y?.($))},$.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},zf=i.memo($f),Uf=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=Dd({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),d=i.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return t.jsx("div",{ref:l,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Kf=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Pd({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Gf=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=Pn(qs(Cr,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,d]=i.useState("Session"),[u,y]=i.useState(null),[m,w]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const x=v=>{l(null),y(null),w(null);const{active:g,over:j}=v;if(!j)return;const C=g.data.current,N=j.data.current;C?.type==="session"&&C.sessionId&&N?.type==="folder"&&N.folderId&&n(C.sessionId,N.folderId)};return t.jsxs(Tn,{sensors:o,collisionDetection:En,onDragStart:v=>{const g=v.active.data.current;if(g?.type==="session"&&g.sessionId){l(g.sessionId),d(g.sessionTitle??"Session");const j=v.active.rect.current.initial?.width,C=v.active.rect.current.initial?.height;y(typeof j=="number"?j:null),w(typeof C=="number"?C:null)}},onDragCancel:()=>{l(null),y(null),w(null)},onDragEnd:x,children:[r,t.jsx(Ni,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}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})]})},vn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),o=r.length;if(o===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+o);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e},bs=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:F(o?Zl:Xl,r),children:[t.jsx(k,{name:e,className:F(Hs(o),"text-muted-foreground")}),t.jsx("span",{className:F(Ws(o),"flex-1 text-muted-foreground"),children:s})]}),Eo=(e,s,n)=>{if(!s)return;const r=o=>{let a=o.session.id===s;for(const l of o.children)a=r(l)||a;return a&&n.add(o.session.id),a};for(const o of e)r(o)},ns=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(ns(n,s))return!0;return!1},Hf=(e,s,n)=>{const r=new Map,o=a=>{const l=As(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)o(c)};return o(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Wf=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let a=r.session.parentID??null;for(;a&&!o.has(a);){if(n.has(a)&&s.has(a))return!1;o.add(a),a=s.get(a)?.session?.parentID??null}return!0})},Mo=new WeakMap;let Ao=1;const qf=e=>{const s=Mo.get(e);if(s!==void 0)return s;const n=Ao;return Ao+=1,Mo.set(e,n),n},pr=e=>e.children.length===0?"":e.children.map(n=>{const r=qf(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${pr(n)}`}).join("|"),qi=(e,s,n,r,o,a)=>{const l=Dn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const y=d.session.directory??o,m=u.session.directory??a,w=no(l,y??"",d.session.id),x=no(l,m??"",u.session.id);return(w?n.has(w):!1)!==(x?r.has(x):!1)?!0:d.children.some((v,g)=>c(v,u.children[g]))};return c(e,s)},Nn=(e,s,n,r)=>{if(!s)return null;const o=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${o}:${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},Qi=(e,s)=>"",Qf=hs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),Vf=e=>null,Tr=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Vi=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=Tr(o,Vi(l,s,n,r)),o==="active")return o;return o},Ro=(e,s,n,r)=>{let o=null;for(const a of e)if(o=Tr(o,Vi(a,s,n,r)),o==="active")return o;return o},Yf=50,Jf=28,un=(e,s)=>s?e.sessions.some(n=>ns(n,s)):!1,Zf=(e,s,n)=>e.sessions.some(r=>qi(r,r,s,n,e.directory,e.directory)),Xf=(e,s,n)=>{const r=o=>{const a=o.session.id;return s.get(a)!==n.get(a)?!0:o.children.some(r)};return e.sessions.some(r)},Fo=(e,s,n)=>{const r=o=>s.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},eh=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},th=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",o=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(o)};return e.sessions.some(o)},sh=(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&&Zf(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&th(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&Xf(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(un(e.group,e.editingId)||un(s.group,s.editingId))||e.editTitle!==s.editTitle&&(un(e.group,e.editingId)||un(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Nn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Nn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Fo(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Fo(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&eh(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 nh(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:y,collapsedFolderIds:m,toggleFolderCollapse:w,renameFolder:x,deleteFolder:v,showDeletionDialog:g,setDeleteFolderConfirm:j,renderSessionNode:C,showMoreGroupSessions:N,resetGroupSessionLimit:b,mobileVariant:h,alwaysShowActions:f,activeProjectId:I,setActiveProjectIdOnly:M,setActiveMainTab:T,setSessionSwitcherOpen:O,openNewSessionDraft:P,addSessionToFolder:B,createFolderAndStartRename:z,renamingFolderId:U,renameFolderDraft:ne,setRenameFolderDraft:se,setRenamingFolderId:K,pinnedSessionIds:G,expandedParents:R,sessionOrderIndex:A,editingId:V,openSidebarMenuKey:le,activeActivitySessionIds:$,unreadActivitySessionIds:ke,notifyOnSubtasks:Ie,onToggleCollapsedGroup:_e,dragHandleProps:Ge,compactBodyPadding:Fe=!1,scrollContainerRef:ve}=e,Te=i.useCallback((L,q)=>{const ee=A.get(L.session.id),te=A.get(q.session.id);if(ee!==void 0||te!==void 0){if(ee===void 0)return 1;if(te===void 0)return-1;if(ee!==te)return ee-te}return jn(L.session,q.session,G,hi)},[G,A]),me=a?c.get(s):null,He=At(L=>L.foldersMap),we=a?!1:u.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const L=Qe(s.directory??null),q=s.branch?.trim();return L&&q?Qi():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const xe=mi(),Ce=i.useMemo(()=>{const L=s.folderScopes?.map(q=>Qe(q.directory))??[Qe(s.directory??null)];return[...new Set(L.filter(q=>!!q))]},[s.directory,s.folderScopes]);i.useSyncExternalStore(i.useCallback(L=>Ce.length>0?xe.subscribeBootstrap(L):()=>{},[Ce.length,xe]),i.useCallback(()=>Ce.map(L=>`${L}\0${xe.getBootstrapState(L)??""}\0${xe.getBootstrapFailure(L)??""}`).join(""),[Ce,xe]),i.useCallback(()=>"",[]));const Ve=Ce.some(L=>{const q=xe.getBootstrapState(L);return q==="queued"||q==="running"}),Be=Ce.find(L=>xe.getBootstrapState(L)==="failed")??null,W=Be?xe.getBootstrapFailure(Be):void 0,H=W==="os-permission"&&Sr(),[ie,pe]=i.useState(!1),Se=i.useCallback(()=>{Be&&xe.requestBootstrap({directory:Be,priority:we?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[xe,Be,s.isMain,we]),Y=i.useCallback(async()=>{if(!(!Be||!H||ie)){pe(!0);try{(await jr(Be)).success&&Se()}finally{pe(!1)}}},[H,Be,ie,Se]),be=y?10:5,ue=Math.max(be,d??be),Ye=a?me?.groupMatches===!0:!1,at=a,ze=i.useMemo(()=>[...at?me?.filteredNodes??[]:s.sessions].sort(Te),[Te,s.sessions,me?.filteredNodes,at]),je=s.folderScopeKey??Qe(s.directory??null),Ae=i.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:je?[{scopeKey:je,directory:s.directory??null}]:[],[je,s.directory,s.folderScopes]),ot=i.useMemo(()=>Ae.flatMap(({scopeKey:L,directory:q})=>(He[L]??[]).map(ee=>({folder:ee,scopeKey:L,scopeDirectory:q}))),[Ae,He]),ht=i.useMemo(()=>{const L=new Map,q=ee=>{ee.forEach(te=>{L.set(te.session.id,te),te.children.length>0&&q(te.children)})};return q(ze),L},[ze]),pt=i.useMemo(()=>ot.map(({folder:L,scopeKey:q,scopeDirectory:ee})=>{const te=Wf(L.sessionIds,ht).sort(Te);return{folder:L,scopeKey:q,scopeDirectory:ee,nodes:te}}),[ot,ht,Te]),ge=i.useMemo(()=>{const L=new Map(pt.map(re=>[re.folder.id,re])),q=new Map;for(const{folder:re}of pt){if(!re.parentId)continue;const rt=q.get(re.parentId);rt?rt.push(re.id):q.set(re.parentId,[re.id])}const ee=new Map,te=re=>{const rt=ee.get(re);if(rt!==void 0)return rt;const wt=L.get(re);if(!wt)return ee.set(re,!1),!1;const St=q.get(re)??[];if(s.isArchivedBucket&&wt.nodes.length===0){const jt=St.some(cs=>te(cs));return ee.set(re,jt),jt}if(!a||wt.folder.name.toLowerCase().includes(l)||wt.nodes.length>0)return ee.set(re,!0),!0;const es=St.some(jt=>te(jt));return ee.set(re,es),es};return pt.filter(({folder:re})=>te(re.id))},[pt,s.isArchivedBucket,a,l]),Je=i.useMemo(()=>new Set(ge.flatMap(L=>L.folder.sessionIds)),[ge]),Tt=i.useMemo(()=>ze.filter(L=>!Je.has(L.session.id)),[ze,Je]),S=i.useMemo(()=>ge.filter(({folder:L})=>!L.parentId),[ge]),Z=i.useMemo(()=>{const L=new Map;return ge.forEach(q=>{if(!q.folder.parentId)return;const ee=L.get(q.folder.parentId)??[];ee.push(q),L.set(q.folder.parentId,ee)}),L},[ge]),ae=i.useMemo(()=>{const L=new Map(ge.map(te=>[te.folder.id,te])),q=new Map,ee=(te,re)=>{const rt=q.get(te);if(rt!==void 0)return rt;if(re.has(te))return null;re.add(te);const wt=L.get(te);let St=wt?Ro(wt.nodes,$,ke,Ie):null;for(const Ut of Z.get(te)??[])if(St=Tr(St,ee(Ut.folder.id,re)),St==="active")break;return q.set(te,St),St};return ge.forEach(({folder:te})=>ee(te.id,new Set)),q},[$,ge,Z,Ie,ke]),ye="project",Re=i.useMemo(()=>{const L=new Set;return Eo(ze,V,L),ge.forEach(({nodes:q})=>{Eo(q,V,L)}),L},[ze,ge,V]),Ke=i.useMemo(()=>{if(!le)return null;const L=Nn(ze,le,ye,!!s.isArchivedBucket);if(L)return L;for(const{nodes:q}of ge){const ee=Nn(q,le,ye,!!s.isArchivedBucket);if(ee)return ee}return null},[le,ze,ge,s.isArchivedBucket]),nt=i.useCallback(L=>{const q=new WeakMap,ee=te=>{q.set(te,pr(te));for(const re of te.children)ee(re)};return L.forEach(ee),q},[]),ct=i.useMemo(()=>nt(ze),[nt,ze]),Gt=i.useMemo(()=>{const L=new WeakMap;return ge.forEach(({nodes:q})=>{q.forEach(ee=>L.set(ee,pr(ee)))}),L},[ge]),it=i.useCallback(L=>ct.get(L)??Gt.get(L)??"",[ct,Gt]),gt=i.useCallback(L=>({subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L)}),[Re,Ke,it]),yt=Tt.length,Ze=s.isArchivedBucket||a?Tt:Tt.slice(0,ue),Bt=yt-Ze.length,_t=!s.isArchivedBucket&&!a&&yt>be&&Bt===0,Et=s.isArchivedBucket===!0&&!a&&Ze.length>=Yf,xt=s.isArchivedBucket?"archived":"active",Mt=Et&&Ze.some(L=>{if(L.children.length===0)return!1;const q=`project:${xt}:${L.session.id}`;return R.has(q)}),D=i.useRef(null),[fe,Ne]=i.useState(null),[Le,We]=i.useState(0),[,Ct]=i.useState(0);i.useEffect(()=>{if(!Et)return;const L=D.current;if(!L||typeof ResizeObserver>"u")return;const q=new ResizeObserver(()=>Ct(ee=>ee+1));return q.observe(L),()=>q.disconnect()},[Et]),i.useLayoutEffect(()=>{if(!Et){fe!==null&&Ne(null),Le!==0&&We(0);return}const L=D.current;if(!L)return;let q=fe;const ee=ve?.current??null;if(ee&&ee.contains(L)){if(q=ee,q!==fe){Ne(q);return}}else if(!q||!q.contains(L)){let re=L.parentElement;for(;re;){const rt=window.getComputedStyle(re);if(rt.overflowY==="auto"||rt.overflowY==="scroll"){q=re;break}re=re.parentElement}if(q!==fe){Ne(q);return}}if(!q)return;const te=L.getBoundingClientRect().top-q.getBoundingClientRect().top+q.scrollTop;We(re=>Math.abs(re-te)<1?re:te)});const E=Et&&fe!==null,X=Id({count:Ze.length,enabled:E,getScrollElement:()=>fe,initialOffset:()=>fe?.scrollTop??0,estimateSize:()=>Jf,overscan:Mt?20:8,scrollMargin:Le,getItemKey:L=>Ze[L]?.session.id??L}),ce=i.useCallback(L=>{const q=[],ee=te=>{te.forEach(re=>{q.push(re.session),re.children.length>0&&ee(re.children)})};return ee(L),q},[]),$e=i.useMemo(()=>ce(ze),[ce,ze]),he=i.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const L=new Map,q=new Map;for(const{folder:te}of ge){if(!te.parentId)continue;const re=q.get(te.parentId)??[];re.push(te.id),q.set(te.parentId,re)}const ee=(te,re)=>{if(re.has(te))return[];re.add(te);const rt=ge.find(({folder:Ut})=>Ut.id===te),wt=rt?ce(rt.nodes):[],St=q.get(te)??[];for(const Ut of St)wt.push(...ee(Ut,re));return wt};for(const{folder:te}of ge)L.set(te.id,ee(te.id,new Set));return L},[ge,ce,s.isArchivedBucket]);if(a&&!Ye&&S.length===0&&Tt.length===0)return null;const Ee=!s.isMain&&!!s.branch,lt=s.branch&&ec(s.branch,s.label)?{label:s.branch}:null,vt=we?Ro(ze,$,ke,Ie):null,$t=vt?t.jsx(Wi,{state:vt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Lt=(L,q)=>{const{folder:ee,scopeKey:te,scopeDirectory:re,nodes:rt}=L,wt=he.get(ee.id)??[],St=a?!1:m.has(ee.id);return t.jsx(Kf,{folderId:ee.id,children:(Ut,es)=>t.jsx(zf,{folder:ee,displayName:q,sessions:rt,isCollapsed:St,collapsedActivityState:St?ae.get(ee.id)??null:null,onToggle:()=>w(ee.id),onRename:jt=>{x(te,ee.id,jt)},onDelete:()=>{if(s.isArchivedBucket){vs.requestDelete({sessions:wt,mode:"session"});return}if(!g){v(te,ee.id);return}const jt=ge.filter(({folder:Ss})=>Ss.parentId===ee.id).length,cs=rt.length;j({scopeKey:te,folderId:ee.id,folderName:ee.name,subFolderCount:jt,sessionCount:cs})},renderSessionNode:C,getRenderExtras:it?jt=>({subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(jt),childRenderExtrasFor:gt}):void 0,groupDirectory:re??s.directory,projectId:r,mobileVariant:h,alwaysShowActions:f,isRenaming:U===ee.id,renameDraft:U===ee.id?ne:void 0,onRenameDraftChange:jt=>se(jt),onRenameSave:()=>{const jt=ne.trim();jt&&x(te,ee.id,jt),K(null),se("")},onRenameCancel:()=>{K(null),se("")},droppableRef:Ut,isDropTarget:es,depth:0,onNewSession:()=>{r&&r!==I&&M(r),T("chat"),h&&O(!1),P({selectedProjectId:r,directoryOverride:re??s.directory,targetFolderId:ee.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},ee.id)},Ht=()=>{const L=new Map;for(const te of ge){const re=te.folder.parentId;if(!re)continue;const rt=L.get(re);rt?rt.push(te):L.set(re,[te])}const q=[],ee=(te,re)=>{const rt=re?`${re} / ${te.folder.name}`:te.folder.name;q.push(Lt(te,rt)),!(!a&&m.has(te.folder.id))&&(L.get(te.folder.id)??[]).forEach(St=>ee(St,rt))};return S.forEach(te=>ee(te,"")),q},zt=f?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",mt=Be?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[W==="os-permission"?"Folder access is required.":"Could not refresh sessions.",H?t.jsx(Me,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ie,onClick:()=>{Y()},children:"Grant access"}):null,t.jsx(Me,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:Se,children:"Try again"})]}):null,Ot=t.jsxs(Gf,{scopeKey:Ae[0]?.scopeKey??je,hasFolders:ge.length>0,onSessionDroppedOnFolder:(L,q)=>{const ee=ge.find(({folder:re})=>re.id===q);if(!ee)return;const te=At.getState();for(const{scopeKey:re}of Ae)re!==ee.scopeKey&&te.getSessionFolderId(re,L)&&te.removeSessionFromFolder(re,L);B(ee.scopeKey,q,L)},children:[Ht(),Et?t.jsx("div",{ref:D,children:E?t.jsx("div",{style:{height:X.getTotalSize(),position:"relative"},children:X.getVirtualItems().map(L=>{const q=Ze[L.index];return q?t.jsx("div",{"data-index":L.index,ref:X.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${L.start-Le}px)`},children:C(q,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(q),childRenderExtrasFor:gt})},q.session.id):null})}):Ze.map(L=>t.jsx(i.Fragment,{children:C(L,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L),childRenderExtrasFor:gt})},L.session.id))}):Ze.map(L=>t.jsx(i.Fragment,{children:C(L,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L),childRenderExtrasFor:gt})},L.session.id)),yt===0&&ge.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."}):Ve?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…"]})}):mt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:mt}):t.jsx(bs,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,yt>0&&mt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:mt}):null,Bt>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>N(n,Ze.length),children:Bt===1?"Show 1 more session":`Show ${Bt} more sessions`}):null,_t?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>b(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Ot})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:F("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>_e(n),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),_e(n))},"aria-label":we?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!we,children:[t.jsx("div",{ref:Ge?.setActivatorNodeRef,className:F("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",zt),...Ge?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:s.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"archive",className:F("size-4 shrink-0 text-muted-foreground",f?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",f?"inline-flex":"hidden group-hover/gh:inline-flex"),children:we?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:vn(s.label,l)}),$t]}):!s.isMain||s.worktree?t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"git-branch",className:F("size-4 shrink-0","text-muted-foreground",f?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",f?"inline-flex":"hidden group-hover/gh:inline-flex"),children:we?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:vn(s.label,l)}),$t,null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:vn(s.label,l)}),$t]})}),Ee&&lt?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:lt.label})]}):null]})}),s.isArchivedBucket&&$e.length>0?t.jsx("div",{className:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",f?"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:L=>{L.stopPropagation(),vs.requestDelete({sessions:$e,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:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",f?"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:L=>{L.stopPropagation(),r&&r!==I&&M(r),T("chat"),h&&O(!1),P({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]}),we?null:t.jsx("div",{className:"oc-group-body",children:Ot})]})}const rh=i.memo(nh,sh);function oh(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:y,setIsSessionSearchOpen:m,sessionSearchInputRef:w,sessionSearchQuery:x,setSessionSearchQuery:v,hasSessionSearchQuery:g,searchMatchCount:j,selectionModeEnabled:C,onToggleSelectionMode:N,mobileVariant:b=!1}=e;if(s)return null;const h=F(u,"text-muted-foreground hover:text-foreground",!b&&"hover:bg-transparent");return t.jsx("div",{className:F("select-none flex-shrink-0",b?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:F("flex flex-col",b?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:F("flex items-center justify-between",b?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:F("flex min-w-0 items-center",b?"gap-0.5 overflow-x-auto":"gap-1.5"),children:[o?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:h,"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,a?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:h,"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:h,"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,t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:h,"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"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:h,"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:F("flex shrink-0 items-center",b?"gap-0.5":"gap-1.5"),children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>m(f=>!f),className:h,"aria-label":"Search sessions","aria-expanded":y,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:F(h,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"})})]})]})]}),y?t.jsxs("div",{className:F(b?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:g?t.jsx("span",{children:j===1?`${j} match`:`${j} 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:w,value:x,onChange:f=>v(f.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:f=>{f.key==="Escape"&&(f.stopPropagation(),g?v(""):m(!1))}}),x.length>0?t.jsx("button",{type:"button",onClick:()=>v(""),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 ih(e){const s=de(o=>o.toggleSidebar),n=de(o=>o.shortcutOverrides),r=tc(sc("toggle_sidebar",n));return t.jsx("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",style:{paddingLeft:`max(${ro}, var(--oc-titlebar-left-inset, ${ro}), var(--oc-titlebar-overlay-width, 0px))`},children:t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:F("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),children:[t.jsx(k,{name:"chat-new",className:F(gn,"text-current")}),t.jsx("span",{className:fi,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 ah=500,lh=({project:e,label:s,isSelected:n,hasActive:r,canDrag:o,onSelect:a,onOpenProjectEditDialog:l,onRemoveProject:c,mobileVariant:d=!1})=>{const{attributes:u,listeners:y,setNodeRef:m,transform:w,transition:x,isDragging:v}=Mn({id:e.id,disabled:!o}),[g,j]=i.useState(!1),C=i.useRef(null),N=i.useCallback(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null)},[]);i.useEffect(()=>()=>N(),[N]);const b=i.useCallback(()=>{N(),C.current=window.setTimeout(()=>{C.current=null,j(!0)},ah)},[N]);return t.jsx("div",{ref:m,style:{transform:An.Translate.toString(w),transition:x},className:F(v&&"opacity-60"),children:t.jsxs(_u,{open:g,onOpenChange:j,children:[t.jsxs($u,{render:t.jsx("button",{type:"button",onClick:()=>{g||a()},onTouchStart:b,onTouchMove:N,onTouchEnd:N,onTouchCancel:N,style:{touchAction:"manipulation"},className:F("relative flex w-full items-center justify-between rounded-xl px-3 py-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",d&&"py-1.5",n?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:F("inline-flex shrink-0 items-center justify-center",o&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":o?`Reorder ${s}`:void 0,...o?{...u,...y}:{},children:t.jsx(k,{name:"folder",className:F(Hs(d),"text-muted-foreground")})}),t.jsx("span",{className:Ws(d),children:s})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsxs(zu,{className:"min-w-[160px]",children:[t.jsxs(Co,{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(Uu,{}),t.jsxs(Co,{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"})]})]})]})})},ch=({projects:e,selectedProjectId:s,onSelectProject:n,onOpenDirectoryDialog:r,onOpenProjectEditDialog:o,onRemoveProject:a,hasActiveSessionByProject:l,homeDirectory:c,className:d,mobileVariant:u=!1})=>{const y=s===null,m=kt(g=>g.reorderProjects),w=e.length>1,x=Pn(qs(Ed,{activationConstraint:{distance:8}}),qs(Td,{activationConstraint:{delay:200,tolerance:6}})),v=i.useCallback(g=>{const{active:j,over:C}=g;if(!C||j.id===C.id)return;const N=kt.getState().projects,b=N.findIndex(f=>f.id===j.id),h=N.findIndex(f=>f.id===C.id);b<0||h<0||m(b,h)},[m]);return t.jsxs("div",{className:F("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",d),children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:F("group relative flex w-full items-center justify-between rounded-xl px-3 py-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",y?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),"aria-pressed":y,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(k,{name:"folder",className:Hs(u)}),t.jsx("span",{className:Ws(u),children:"All Folders"})]})}),t.jsx(Tn,{sensors:x,collisionDetection:En,onDragEnd:v,children:t.jsx(Nr,{items:e.map(g=>g.id),strategy:Ii,children:e.map(g=>{const j=s===g.id,C=In(g.label?.trim()||ys(g.normalizedPath,c)||g.normalizedPath);return t.jsx(lh,{project:g,label:C,isSelected:j,hasActive:l?.(g.id),canDrag:w,onSelect:()=>n(j?null:g.id),onOpenProjectEditDialog:o,onRemoveProject:a,mobileVariant:u},g.id)})})}),t.jsxs("button",{type:"button",onClick:r,className:F("flex w-full items-center gap-1.5 rounded-xl px-3 py-2 typography-ui-label text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"),children:[t.jsx(k,{name:"add",className:Hs(u)}),t.jsx("span",{className:Ws(u),children:"Add folder"})]})]})},Wn="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 dh({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:a=!0}){return!o&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?t.jsxs(t.Fragment,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:Wn,"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:Wn,"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:Wn,"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(Me,{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 uh=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Lo=hs()(kr(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:uh})),fh=({projectLabel:e,isCollapsed:s,alwaysShowActions:n=!1,mobileVariant:r=!1})=>{const o=s!==void 0,a=o?n?"hidden":"group-hover/project:hidden group-focus-within/project:hidden":void 0,l=Hs(r),c=Ws(r);return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:F("inline-flex shrink-0 items-center justify-center",l),children:[o?t.jsx("span",{className:F("items-center justify-center text-muted-foreground",l,n?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:t.jsx(k,{name:s?"arrow-right-s":"arrow-down-s",className:l})}):null,t.jsx(k,{name:"folder",className:F(l,"text-muted-foreground/80",a)})]}),t.jsx("span",{className:F(c,"text-foreground"),children:e})]})},hh=({id:e,disabled:s=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e,disabled:s}),u=i.useMemo(()=>({listeners:r,setActivatorNodeRef:a}),[r,a]);return t.jsx("div",{ref:o,style:{transform:An.Transform.toString(l),transition:c},className:F("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};i.memo(hh);const mh=48,ph=32,gh=24,Oo=(e,s)=>In(e.label?.trim()||ys(e.normalizedPath,s)||e.normalizedPath);function xh(e){Zt("ui.sidebar_projects_list.render");const s=e.isDesktopShellRuntime&&e.stickyZoneHeaders,n=i.useRef(new Map),r=i.useRef(e.getOrderedGroups);r.current!==e.getOrderedGroups&&(r.current=e.getOrderedGroups,n.current.clear());const o=(N,b)=>{const h=n.current,f=h.get(N);if(f&&f.groups===b)return f.ordered;const I=e.getOrderedGroups(N,b);if(h.set(N,{groups:b,ordered:I}),h.size>256){const M=h.keys().next().value;M!==void 0&&h.delete(M)}return I},a=i.useRef(null),l=i.useRef(0),c=i.useCallback(N=>{const h=N.scrollTop>1?Math.min(ph+N.scrollTop,mh):0;l.current=h,N.style.setProperty("--scroll-shadow-top-size",`${h}px`),N.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(h-8,0),gh)}px`)},[]),d=i.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;i.useLayoutEffect(()=>{s&&u&&a.current&&c(a.current)},[s,u,c]);let y=null;for(const N of e.projectSections)e.stuckProjectHeaders.has(N.project.id)&&(y=N.project);const m=y??(e.hasSharedSessions?null:e.sectionsForRender[0]?.project??null),w=m?Oo(m,e.homeDirectory):null,x=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const N=[];for(const b of e.sectionsForRender){const h=Oo(b.project,e.homeDirectory);for(const f of b.groups)if(!f.isArchivedBucket)for(const I of f.sessions){const M=!!e.pinnedSessionIds?.has(I.session.id),T=I.session.time?.updated||I.session.time?.created||0;N.push({node:I,project:b.project,projectLabel:h,isPinned:M,timestamp:T})}}return N.sort((b,h)=>b.isPinned!==h.isPinned?b.isPinned?-1:1:h.timestamp-b.timestamp),N},[e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[v,g]=i.useState(30);i.useEffect(()=>{g(30)},[e.hasSessionSearchQuery]);const j=x.slice(0,v),C=x.length-j.length;return e.sharedSessionsOnly?t.jsx(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})}):e.projectSections.length===0?t.jsx(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0?t.jsx(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsxs("div",{className:"oc-sticky-fade-root relative flex min-h-0 flex-1",onPointerDownCapture:s?d:void 0,onClickCapture:s?d:void 0,onContextMenuCapture:s?d:void 0,children:[t.jsx(xs,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!s,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("oc-sidebar-scroller oc-sticky-fade-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-20"),style:s?{"--scroll-shadow-top-size":"0px"}:void 0,onScroll:s?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(I=>I.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!N)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=N.groups.find(I=>I.isMain&&I.sessions.length>0)??N.groups.find(I=>I.sessions.length>0)??N.groups.find(I=>I.isMain)??N.groups[0];if(!b)return t.jsx(bs,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:N.project.id,directoryOverride:N.project.normalizedPath}),children:"New session"});const h=N.groups.find(I=>I.isArchivedBucket);return[b,...h&&h.id!==b.id?[h]:[]].map(I=>{const M=`${N.project.id}:${I.id}`,T=I.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(I,M,N.project.id,T,null,!0,a)},M)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:x.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[j.map(({node:N,project:b,projectLabel:h})=>{const f=N.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(N,0,f,b.id,!1,{projectLabel:h,showFolderLabel:!0},"project")},N.session.id)}),C>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>g(N=>N+30),children:C===1?"Show 1 more session":`Show ${C} more sessions`}):null,v>30&&x.length>30?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>g(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(N=>{const b=N.project.id,h=o(b,N.groups),f=h.find(M=>M.isMain)??null,I=f?h.filter(M=>M.id!==f.id):h;return t.jsxs("div",{children:[f?e.renderGroupSessions(f,`${b}:${f.id}`,b,!0,null,void 0,a):null,I.map(M=>{const T=`${b}:${M.id}`;return t.jsx(i.Fragment,{children:e.renderGroupSessions(M,T,b,!1,null,void 0,a)},M.id)})]},b)})})]})}),s&&m&&w?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(fh,{id:m.id,projectLabel:w,mobileVariant:e.mobileVariant})}):null]})}const bh=i.memo(xh);function yh(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(),o=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${l}`}function vh(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 wh(e){const s=e.info.role==="user"?"User":"Assistant",n=yh(e.info.time?.created),r=vh(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
4
-
5
- *${o}*`:`**${s}**`}function Sh(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Yi(e){const s=wh(e),n=Sh(e.parts).trim();return n?`${s}
6
-
7
- ${n}`:""}function Ji(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
8
-
9
- ---
10
-
11
- `,a=e.records.map(Yi).filter(Boolean).join(`
12
-
13
- ---
14
-
15
- `),l=[o+a];for(const c of e.children)l.push(Ji(c,s+1));return l.join(`
16
-
17
- ---
18
-
19
- `)}function jh(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
20
-
21
- *Exported on ${o}*
22
-
23
- ---
24
-
25
- `,l=e.map(Yi).filter(Boolean).join(`
26
-
27
- ---
28
-
29
- `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Ji(u,1)).join(`
30
-
31
- ---
32
-
33
- `);c+=`
34
-
35
- ---
36
-
37
- `+d}return c}function kh(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function Ch(e,s){const n=await ad(s,e);return n||null}async function Nh(e){const s=yi()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await ld(e)?!0:cd(e)}function Ih(){return nc()}function Dh(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const Ph=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const a=s.get(o);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},Rt=hs()((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,o)=>{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 y=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const w of y)l.delete(w);d===n&&(d=null)}else{for(const w of y)l.add(w);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,o,a,l)=>{const c=s();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),y=o.indexOf(r);if(u<0||y<0)return;const[m,w]=u<=y?[u,y]:[y,u],x=o.slice(m,w+1),v=Ph(x,l),j=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const C of v)j.add(C);e({selectedIds:j,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 o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}}));let gr=!1;const xr=new Set;let Bo=!1;function Th(){for(const e of xr)e()}function Er(e){gr!==e&&(gr=e,Th())}function Eh(e){e.key==="Shift"&&Er(!0)}function Mh(e){e.key==="Shift"&&Er(!1)}function Ah(){Er(!1)}function Rh(){Bo||typeof window>"u"||(Bo=!0,window.addEventListener("keydown",Eh),window.addEventListener("keyup",Mh),window.addEventListener("blur",Ah))}function Fh(e){return Rh(),xr.add(e),()=>{xr.delete(e)}}function Lh(){return gr}function Oh(){return!1}function Bh(){return Ue.useSyncExternalStore(Fh,Lh,Oh)}const qn=new WeakMap,_h=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;qn.get(n)?.();const r=s.getBoundingClientRect().top;let o=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,qn.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,Zt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),qn.set(n,c),l=window.requestAnimationFrame(d)},$h=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Bh(),y=u?n:s,m=w=>{if(u||w.shiftKey){d(w);return}c(w)};return t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":y,onPointerDown:a,onMouseDown:l,onClick:m,onKeyDown:w=>w.stopPropagation(),children:t.jsx(k,{name:u?"delete-bin":"archive",className:o})})}),t.jsx(st,{side:"left",sideOffset:8,children:y})]})});function zh(e){Zt("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:y,editingId:m,setEditingId:w,editTitle:x,setEditTitle:v,handleSaveEdit:g,handleCancelEdit:j,toggleParent:C,handleSessionSelect:N,handleSessionDoubleClick:b,togglePinnedSession:h,handleShareSession:f,copiedSessionId:I,handleCopyShareUrl:M,handleCopySessionId:T,handleUnshareSession:O,openSidebarMenuKey:P,setOpenSidebarMenuKey:B,renamingFolderId:z,getFoldersForScope:U,getSessionFolderId:ne,removeSessionFromFolder:se,addSessionToFolder:K,createFolderAndStartRename:G,openContextPanelTab:R,handleDeleteSession:A,handleRestoreSession:V,mobileVariant:le,alwaysShowActions:$,renderSessionNode:ke,secondaryMeta:Ie,renderContext:_e="project",subtreeContainsEditing:Ge,menuOpenSessionId:Fe,childRenderExtrasFor:ve}=e,Te=i.useMemo(()=>dd(),[]),me=!a&&!le,He=i.useRef(!1),[we,xe]=i.useState(!1),Ce=i.useRef(m);Ce.current=m;const Ve=i.useRef(null),Be=i.useRef(g);Be.current=g;const[W,H]=i.useState(x),ie=i.useRef(W);ie.current=W;const pe=i.useRef(null),Se=i.useRef(null),Y=s.session,be=Y,ue=Qe(Y.directory??null)??Qe(r??null),Ye=De(_=>_.currentSessionId===Y.id),at=rc(ue),ze=oc(ue),je=kt(i.useCallback(_=>{if(Ie?.projectLabel||!o)return null;const Pe=_.projects.find(Xe=>Xe.id===o);return Pe?Pe.label?.trim()||ys(Qe(Pe.path)??Pe.path,null)||Pe.path:null},[o,Ie?.projectLabel])),Ae=Ie?.projectLabel??(je?In(je):null),ot=Ie?.branchLabel??s.worktree?.branch??(at&&at!=="HEAD"?at:null),ht=ot,pt=ze===!0||!!(ot||s.worktree),ge=s.children.length,Je=be.agent;i.useMemo(()=>{const _=s.worktree?.branch?.trim()||ot?.trim(),Pe=Qe(s.worktree?.path??ue);return _&&Pe?Qi():null},[s.worktree,ot,ue]);const Tt=Vf();i.useMemo(()=>null,[Tt]);const S=o??ue??null,Z=hc(),ae=pi(),ye=Rt(_=>_.enabled),Re=Rt(i.useCallback(_=>_.selectedIds.has(Y.id),[Y.id])),Ke=Rt(_=>_.toggleSelected),nt=Rt(_=>_.setRange),ct=i.useCallback(_=>{const Pe=[],Xe=dt=>{dt.children.forEach(Nt=>{Pe.push(Nt.session.id),Xe(Nt)})};return Xe(_),Pe},[]);i.useCallback(_=>{const Pe=[],Xe=dt=>{dt.children.forEach(Nt=>{Pe.push(Nt.session),Xe(Nt)})};return Xe(_),Pe},[]);const[Gt,it]=i.useState(!1),[gt,yt]=i.useState(!0),Ze=`${_e}:${a?"archived":"active"}:${Y.id}`,Bt=ic(i.useCallback(_=>!!_.sessionMemoryState.get(ac(Y.id))?.isZombie,[Y.id])),Et=lc(Y.id)?.type??"idle",xt=Et==="busy"||Et==="retry",Mt=cc(Y.id,xt),D=dc(Y.id),fe=be.title||"Untitled Session",Ne=s.children.length>0,Le=uc(l,ue,Y.id),We=Ze,Ct=d?!0:c.has(We);i.useMemo(()=>Hf(s,Ct,ue),[Ct,s,ue]);const E=pc(),X=!!be.parentID,$e=fc(Y.id)>0&&(!X||y),he=be.time?.updated||be.time?.created||Date.now(),Ee=oi(he),lt=gc(he),[vt,$t]=i.useState(!1),Lt=i.useMemo(()=>ct(s).length,[ct,s]),Ht=i.useCallback(async _=>{const Pe=[];let Xe=0;for(const dt of _)try{if(!ue)throw new Error("Session directory is required for export");await ae.loadCompleteHistory?.(dt.session.id,ue);const Nt=oo(Z.getState(),dt.session.id).list,ut=dt.session.title||"Untitled Sub-agent",Yt=dt.session.agent,Kt=await Ht(dt.children);Xe+=Kt.skipped,Pe.push({title:ut,agent:Yt,records:Nt,children:Kt.children})}catch{Xe+=ct(dt).length+1}return{children:Pe,skipped:Xe}},[ct,Z,ue,ae]),zt=i.useCallback(_=>{_<=0||oe.warning(_===1?`Exported session, but skipped ${_} sub-agent task that could not be loaded.`:`Exported session, but skipped ${_} sub-agent tasks that could not be loaded.`)},[]),mt=i.useCallback(async _=>{if(!ue){oe.error("Nothing to export");return}try{await ae.loadCompleteHistory?.(Y.id,ue)}catch{oe.error("Failed to load the complete session history");return}const Pe=oo(Z.getState(),Y.id).list;if(Pe.length===0){oe.error("Nothing to export");return}let Xe,dt=0;if(_&&s.children.length>0){const Kt=await Ht(s.children);Xe=Kt.children,dt=Kt.skipped}const Nt=jh(Pe,be.title??null,Xe),ut=Dh(be.title??null),Yt=await Ch(Nt,ut);if(Yt){oe.success("Session exported",{action:{label:Ih(),onClick:()=>{Nh(Yt).then(Kt=>{Kt||oe.error("Failed to reveal path")})}}}),zt(dt);return}kh(Nt,ut),oe.success("Session exported"),zt(dt)},[Ht,Z,s.children,be.title,Y.id,ue,zt,ae]),Ot=i.useCallback(async()=>{if(s.children.length>0){yt(!0),it(!0);return}await mt(!1)},[mt,s.children.length]),L=i.useCallback(()=>{ue&&ud("desktop_open_session_mini_chat_window",{sessionId:Y.id,directory:ue,apiBaseUrl:hd(),clientToken:fd()}).catch(_=>{console.warn("[session-sidebar] failed to open mini chat window",_)})},[Y.id,ue]);i.useEffect(()=>{if(m!==Y.id)return;const _=Pe=>{const dt=Pe.target?.closest?.(`[data-session-rename-form="${CSS.escape(Y.id)}"]`);Se.current&&!dt&&Be.current(ie.current)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[m,Y.id]),i.useLayoutEffect(()=>{if(m!==Y.id){pe.current===Y.id&&(pe.current=null);return}pe.current!==Y.id&&(pe.current=Y.id,H(x))},[m,x,Y.id]);const q=D.length,ee=!xt&&$e&&!Ye,te=xt&&Mt,re=Le,rt=t.jsx(k,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),wt=re?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:rt}):null,St=Ne?t.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),C(We)},onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),_.stopPropagation(),C(We))},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":Ct?"Collapse subsessions":"Expand subsessions",children:Ct?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,Ut=Bt?t.jsx(k,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,es=_=>{if(!_&&Ve.current){const{id:Pe,title:Xe}=Ve.current;Ve.current=null,w(Pe),v(Xe)}},jt=_=>{$t(_)},cs=_=>{_.preventDefault(),_.stopPropagation()},Ss=_=>{_.preventDefault(),_.stopPropagation()},js=_=>{_.preventDefault(),_.stopPropagation(),B(null),A(Y,{archivedBucket:a})},Rn=_=>{_.preventDefault(),_.stopPropagation(),B(null),A(Y,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Zs=_=>{if(He.current){He.current=!1;return}if(ye){if(_?.preventDefault(),_?.stopPropagation(),_?.shiftKey){const Xe=(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),dt=Rt.getState().anchorId,Nt=new Map;Nt.set(Y.id,ct(s)),nt(dt,Y.id,Xe,S,Nt);return}Ke(Y.id,S,ct(s));return}_?.currentTarget&&_h(_.currentTarget),N(Y.id,ue)},Fn=_=>{_.defaultPrevented||_.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Zs(_)},Xs=_=>{(_.button===2||_.button===0&&_.ctrlKey&&!ye)&&(He.current=!0)},ts=_=>{le&&_.pointerType==="touch"&&xe(!0)},ks=_=>{le&&_.pointerType==="touch"&&xe(!1)},$s=({Item:_,Separator:Pe,Sub:Xe,SubTrigger:dt,SubContent:Nt})=>t.jsxs(t.Fragment,{children:[t.jsxs(_,{onClick:()=>{Ve.current={id:Y.id,title:fe}},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(_,{onClick:()=>T(Y.id),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(_,{onClick:()=>ue&&h({directory:ue,sessionId:Y.id}),className:"[&>svg]:mr-1",children:[Le?t.jsx(k,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(k,{name:"pushpin",className:"mr-1 h-4 w-4"}),Le?"Unpin session":"Pin session"]}),be.share?t.jsxs(t.Fragment,{children:[t.jsx(_,{onClick:()=>{be.share?.url&&M(be.share.url,Y.id)},className:"[&>svg]:mr-1",children:I===Y.id?t.jsxs(t.Fragment,{children:[t.jsx(k,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):t.jsxs(t.Fragment,{children:[t.jsx(k,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy link"]})}),t.jsxs(_,{onClick:()=>O(Y.id),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),"Unshare"]})]}):t.jsxs(_,{onClick:()=>f(be),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"share-2",className:"mr-1 h-4 w-4"}),"Share"]}),t.jsxs(_,{onClick:()=>{Ot()},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),ue&&!a?(()=>{const ut=[],Yt=It=>{const Dt=Qe(It??null);Dt&&!ut.includes(Dt)&&ut.push(Dt)};if(o){const It=kt.getState().projects.find(Ns=>Ns.id===o),Dt=Qe(It?.path??null);Yt(Dt)}Yt(ue);const Kt=ut.flatMap(It=>U(It).map(Dt=>({scope:It,folder:Dt}))),Qt=Kt.find(({scope:It,folder:Dt})=>ne(It,Y.id)===Dt.id)??null,Cs=ut[0]??ue;return t.jsxs(t.Fragment,{children:[t.jsx(Pe,{}),t.jsxs(Xe,{children:[t.jsxs(dt,{className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"folder",className:"h-4 w-4"}),"Move to folder"]}),t.jsxs(Nt,{className:"min-w-[180px]",children:[Kt.length===0?t.jsx(_,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):Kt.map(({scope:It,folder:Dt})=>{const Ns=Qt?.folder.id===Dt.id;return t.jsxs(_,{onClick:()=>{if(Ns){se(It,Y.id);return}Qt&&Qt.scope!==It&&se(Qt.scope,Y.id),K(It,Dt.id,Y.id)},children:[t.jsx("span",{className:"flex-1 truncate",children:Dt.name}),Ns?t.jsx(k,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Dt.id)}),t.jsx(Pe,{}),t.jsxs(_,{onClick:()=>{const It=G(Cs);It&&(Qt&&Qt.scope!==Cs&&se(Qt.scope,Y.id),K(Cs,It.id,Y.id))},children:[t.jsx(k,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),Qt?t.jsxs(_,{onClick:()=>{se(Qt.scope,Y.id)},className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]})]})})():null,t.jsxs(_,{disabled:!ue,onClick:()=>{ue&&R(ue,{mode:"chat",dedupeKey:`session:${Y.id}`,label:fe,sessionTitleFallback:fe})},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"chat-4",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Side Panel"}),t.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]}),Te?t.jsxs(_,{disabled:!ue,onClick:L,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(Pe,{}),a?null:t.jsxs(_,{className:"[&>svg]:mr-1",onClick:()=>A(Y,{archivedBucket:a}),children:[t.jsx(k,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(_,{className:"[&>svg]:mr-1",onClick:()=>V(Y),children:[t.jsx(k,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(_,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>A(Y,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(k,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]});Xt,$s({Item:Ft,Separator:gi,Sub:xc,SubTrigger:bc,SubContent:yc});const en=t.jsx(lr,{children:t.jsx(cr,{className:"app-region-no-drag z-50",children:t.jsx(dr,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(z||Ce.current),style:{color:"var(--surface-elevated-foreground)"},className:F(rr,"min-w-[180px]"),children:$s({Item:({className:_,...Pe})=>t.jsx(ji,{className:F(ni,_),...Pe}),Separator:({className:_,...Pe})=>t.jsx(ki,{className:F(ri,_),...Pe}),Sub:kd,SubTrigger:({className:_,children:Pe,...Xe})=>t.jsxs(Cd,{className:F(mc,_),...Xe,children:[Pe,t.jsx(k,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:_,children:Pe,...Xe})=>t.jsx(lr,{children:t.jsx(cr,{className:"app-region-no-drag z-50",children:t.jsx(dr,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:F(rr,_),...Xe,children:Pe})})})})})})});return t.jsxs(i.Fragment,{children:[t.jsx(Uf,{sessionId:Y.id,sessionDirectory:ue??null,sessionTitle:fe,children:t.jsxs(wi,{open:vt,onOpenChange:jt,onOpenChangeComplete:es,children:[t.jsxs(Si,{render:t.jsx("div",{"data-session-row":Y.id,"data-session-scope":S??"","data-session-archived":a?"1":"0",onClick:Fn,style:n>0?{marginLeft:`${n*14}px`}:void 0,className:F("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",n>0?"bg-secondary/30 hover:bg-interactive-hover":"hover:bg-interactive-hover",Ye&&!Re&&"bg-interactive-selection",Re&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[St,wt,m===Y.id?t.jsxs("form",{ref:Se,"data-session-rename-form":Y.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation(),onSubmit:_=>{_.preventDefault(),g(W)},children:[t.jsx("input",{value:W,onChange:_=>H(_.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:_=>{_.stopPropagation(),_.key==="Escape"&&j()}}),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:j,"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(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs("button",{type:"button",onPointerDown:ts,onPointerUp:ks,onPointerCancel:ks,onMouseDown:Xs,onClick:_=>Zs(_),onDoubleClick:_=>{_.stopPropagation(),b(Y.id,fe)},className:F("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",we&&"bg-interactive-hover/70"),children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:F("block min-w-0 flex-1 truncate font-normal typography-ui-label",$e?"text-foreground":"text-foreground/90"),children:vn(fe,u)})}),Ie?.showFolderLabel&&Ae||ht||pt||Tt||ge>0||Je&&Je!=="default"||te||q>0||E>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:[Ie?.showFolderLabel&&Ae?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",title:`Folder: ${Ae}`,children:Ae}):null,ht?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",title:`Branch: ${ht}`,children:[t.jsx(k,{name:"git-branch",className:F("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:ht})]}):pt?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:"Git repository",children:[t.jsx(k,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,ge>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:`${ge} ${ge===1?"subtask":"subtasks"}`,children:[t.jsx(k,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:ge})]}):null,Je&&Je!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",title:`Agent: ${Je}`,children:Je}):null,te?t.jsx(zn,{sessionId:Y.id,running:xt,className:"text-muted-foreground/70"}):null,q>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0",title:"Permission required","aria-label":"Permission required",children:[t.jsx(k,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:q})]}):null,null]}):null]})}),t.jsx(st,{side:"right",sideOffset:56,className:"max-w-xs text-left",children:t.jsxs("div",{className:"flex min-w-44 flex-col gap-1.5 text-left text-xs",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"min-w-0 truncate font-normal text-foreground",children:fe}),xt?t.jsx(zn,{sessionId:Y.id,running:!0,className:"flex-shrink-0 text-primary font-medium"}):ee?t.jsx(io,{label:"Session complete"}):t.jsx("span",{className:"flex-shrink-0 text-muted-foreground",title:Ee,children:lt})]}),xt?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-primary",children:[t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"h-3 w-3 shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate font-medium",children:["Running for ",t.jsx(zn,{sessionId:Y.id,running:!0})]})]}):null,Ae?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"folder",className:"h-3 w-3 flex-shrink-0"}),t.jsx("span",{className:"min-w-0 truncate",children:Ae})]}):null,ht?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"h-3 w-3 flex-shrink-0",style:void 0}),t.jsx("span",{className:"min-w-0 truncate",children:ht})]}):pt?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"git-repository",className:"h-3 w-3 flex-shrink-0"}),t.jsx("span",{className:"min-w-0 truncate",children:"Git Repository"})]}):null,null,ge>0?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"node-tree",className:"h-3 w-3 flex-shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate text-[11px]",children:[ge," ",ge===1?"subtask":"subtasks"]})]}):null,Je&&Je!=="default"?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-3 w-3 flex-shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate text-[11px]",children:["Agent: ",Je]})]}):null]})})]})]}),Le?t.jsx(k,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,t.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[t.jsx("div",{className:F("flex items-center justify-end",me&&($||vt)?"opacity-0":me?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:xt?t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):ee?t.jsx(io,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",title:Ee,children:lt})}),me?t.jsx("div",{className:F("absolute inset-0 flex items-center justify-end",$||vt?"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($h,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:cs,onMouseDown:Ss,onArchive:js,onDelete:Rn})}):null]}),Ut&&!le?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:Ut}):null]}),en]})}),Ne&&Ct?s.children.map(_=>{const Pe=ve?ve(_):{subtreeContainsEditing:Ge,menuOpenSessionId:Fe,nodeStructureKey:""};return t.jsx(i.Fragment,{children:ke(_,n+1,ue??r,o,a,void 0,_e,Pe)},_.session.id)}):null,t.jsx(os,{open:Gt,onOpenChange:it,children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ws,{children:[t.jsx(fs,{children:"Export Markdown"}),t.jsx(Bs,{children:Lt===1?`This session has ${Lt} sub-agent task. Include it in the export?`:`This session has ${Lt} 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:gt,onChange:_=>yt(_.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(_s,{children:[t.jsx(Me,{type:"button",onClick:()=>it(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Me,{type:"button",onClick:()=>{it(!1),mt(gt)},size:"sm",children:"Export"})]})]})})]},Y.id)}const _o=e=>Qe(e.session.directory??null),Uh=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Kh=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},fn=e=>e.menuOpenSessionId??Kh(e),hn=(e,s,n)=>s?n.has(e.node.session.id)?!0:ns(e.node,s):!1,br=(e,s,n,r,o)=>{if(e.session.id!==s.session.id)return!0;const a=o(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(br(e.children[l],s.children[l],n,r,o))return!0;return!1},Gh=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return br(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||br(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},Hh=(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||_o(e.node)!==_o(s.node)||!Uh(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&qi(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Gh(e,s)||e.editingId!==s.editingId&&(hn(e,e.editingId,e.subtreeContainsEditing)||hn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(hn(e,e.editingId,e.subtreeContainsEditing)||hn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(ns(e.node,e.copiedSessionId)||ns(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=fn(e),r=fn(s);if(ns(e.node,n)||ns(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=fn(e),r=fn(s);if(ns(e.node,n)||ns(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},Wh=i.memo(zh,Hh),$o={selected:0,"active-project":1,expanded:2,visible:3,background:4};function qh(e){const s=new Map,n=(r,o,a)=>{const l=Qe(r??null);if(!l)return;const c=s.get(l);c&&$o[c.priority]<=$o[o]||s.set(l,{directory:l,priority:o,reason:a})};for(const r of e.projectSections){const o=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":o&&(a="expanded"),n(r.project.normalizedPath,a,o?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=o&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":o&&(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 Qh(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l="Untitled Session";return t.jsx(os,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ws,{children:[t.jsx(fs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Bs,{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(_s,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>o(!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 Vh(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,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(os,{open:!!s,onOpenChange:y=>{y||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ws,{children:[t.jsx(fs,{children:d}),t.jsx(Bs,{children:u})]}),t.jsxs(_s,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>o(!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 Yh(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(os,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ws,{children:[t.jsx(fs,{children:"Delete folder?"}),t.jsx(Bs,{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(_s,{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 Jh=({selectedCount:e,scopeKey:s,scopeFolders:n,archivedBucket:r,onMoveToFolder:o,onCreateFolderAndMove:a,onRemoveFromFolder:l,canRemoveFromFolder:c,onRestore:d,onDelete:u,onDone:y})=>{const m=!!s&&!r,w=r?"Delete":"Archive",x="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:[m?t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",className:x,"aria-label":"Move to folder",children:t.jsx(k,{name:"folder",className:"h-4 w-4"})})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Move to folder"})})]}),t.jsxs(Xt,{align:"end",className:"min-w-[180px]",children:[n.length===0?t.jsx(Ft,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):n.map(g=>t.jsx(Ft,{onClick:()=>o(g.id),children:t.jsx("span",{className:"flex-1 truncate",children:g.name})},g.id)),t.jsx(gi,{}),t.jsxs(Ft,{onClick:a,children:[t.jsx(k,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),c?t.jsxs(Ft,{onClick:l,className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]}):null,r?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:d,className:x,"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:u,className:F("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":w,children:t.jsx(k,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:w})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:y,className:x,"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"})})]})]})]})},Zh=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:y,setBulkDeleteConfirm:m}=e,w=Rt(G=>G.enabled),x=Rt(G=>G.selectedIds.size),v=x>0,g=Rt(G=>G.selectedIds),j=Rt(G=>G.scopeKey),C=i.useCallback(()=>{Rt.getState().toggleMode()},[]),N=i.useCallback(()=>{Rt.getState().disable()},[]),b=i.useMemo(()=>{if(!v||typeof document>"u")return!1;let G=!1,R=!1;for(const A of g){const V=document.querySelectorAll(`[data-session-row="${CSS.escape(A)}"]`);for(const le of V)le.getAttribute("data-session-archived")==="1"?R=!0:G=!0}return R&&!G},[v,g]),h=i.useMemo(()=>{if(j)return j;if(!v||typeof document>"u")return null;for(const G of g){const A=document.querySelector(`[data-session-row="${CSS.escape(G)}"]`)?.getAttribute("data-session-scope");if(A&&A.length>0)return A}return null},[v,g,j]),f=i.useMemo(()=>{if(!h)return[];const G=o.get(h);return G&&G.length>0?G.map(R=>R.scopeKey):[h]},[h,o]),I=i.useMemo(()=>f.flatMap(G=>r[G]??[]),[r,f]),M=i.useCallback(G=>{for(const R of f)if((r[R]??[]).some(A=>A.id===G))return R;return null},[r,f]),T=i.useMemo(()=>{if(!v)return!1;for(const G of f)for(const R of r[G]??[])for(const A of R.sessionIds)if(g.has(A))return!0;return!1},[r,f,v,g]),O=i.useCallback((G,R)=>{const A=Array.from(g);for(const V of f)V!==G&&l(V,A);a(G,R,A)},[a,l,g,f]),P=i.useCallback(G=>{if(!v)return;const R=M(G);R&&O(R,G)},[v,O,M]),B=i.useCallback(()=>{const G=f[0];if(!G||!v)return;const R=c(G);R&&O(G,R.id)},[c,v,O,f]),z=i.useCallback(()=>{if(!v)return;const G=Array.from(g);for(const R of f)l(R,G)},[l,g,f,v]),U=i.useCallback(async()=>{const G=Array.from(g);if(G.length!==0){if(b){const{deletedIds:R,failedIds:A}=await y(G);R.length>0&&oe.success(R.length===1?`Deleted ${R.length} session`:`Deleted ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to delete ${A.length} session`:`Failed to delete ${A.length} sessions`)}else{const{archivedIds:R,failedIds:A}=await d(G);R.length>0&&oe.success(R.length===1?`Archived ${R.length} session`:`Archived ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to archive ${A.length} session`:`Failed to archive ${A.length} sessions`)}Rt.getState().clear()}},[d,b,y,g]),ne=i.useCallback(()=>{if(!v)return;const G=g.size;if(!n){U();return}m({sessionCount:G,archivedBucket:b})},[b,U,g,n,m,v]),se=i.useCallback(async()=>{if(!v||!b)return;const G=Array.from(g),{restoredIds:R,failedIds:A}=await u(G);R.length>0&&oe.success(R.length===1?`Restored ${R.length} session`:`Restored ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to restore ${A.length} session`:`Failed to restore ${A.length} sessions`),Rt.getState().clear()},[b,v,g,u]),K=i.useCallback(async()=>{m(null),await U()},[U]);return i.useEffect(()=>{if(!w)return;const G=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),R=A=>{if(s)return;const V=A.target;if(V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable))return;const le=G?A.metaKey:A.ctrlKey;if(A.key==="Escape"){A.preventDefault(),Rt.getState().disable();return}if(le&&A.key==="Backspace"){A.preventDefault(),ne();return}if(le&&(A.key==="a"||A.key==="A")){const $=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if($.length===0)return;A.preventDefault();const Ie=Rt.getState().scopeKey??$[0]?.getAttribute("data-session-scope")??null,_e=Fe=>Ie?Fe.getAttribute("data-session-scope")===Ie:!0,Ge=$.filter(_e).map(Fe=>Fe.getAttribute("data-session-row")).filter(Fe=>typeof Fe=="string"&&Fe.length>0);if(Ge.length===0)return;Rt.getState().replaceAll(Ge,Ie||null)}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[ne,s,w]),{selectionModeEnabled:w,hasSelection:v,selectedIdsSize:x,bulkScopeIsArchived:b,derivedSelectionScope:h,bulkScopeFolders:I,bulkCanRemoveFromFolder:T,handleToggleSelectionMode:C,handleExitSelectionMode:N,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:B,handleBulkRemoveFromFolder:z,handleBulkDelete:ne,handleBulkRestore:se,confirmBulkDelete:K}},zo="oc.sessions.projectCollapse",Uo="oc.sessions.groupOrder",Ko="oc.sessions.groupCollapse",Go="oc.sessions.activeSessionByProject",Ho="oc.sessions.expandedParents.v3",Xh=(e,s,n)=>{if(e.time?.archived)return!0;const r=ao(As(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const o of s)if(ao(o)===r)return!0;return!1},em=new Set,Qn=[],Wt=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},tm=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l})=>{const c=De(d=>d.currentSessionDirectory);return i.useEffect(()=>{s.setBootstrapDemand(e,qh({projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,o,l,c,e,n]),i.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},sm=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=Qe(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return xn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=Qe(o.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(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},nm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{ar("react.session_sidebar_render"),Zt("ui.session_sidebar.render"),Zt(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Zt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=i.useState(!1),[u,y]=i.useState(""),m=i.useRef(null),w=i.useRef(null),[x,v]=i.useState(null),[g,j]=i.useState(""),[C,N]=i.useState(null),[b,h]=i.useState(new Set),f=i.useMemo(()=>an(),[]),[I,M]=i.useState(new Set),[T,O]=i.useState(null),[P,B]=i.useState(new Map),[z,U]=i.useState(new Map),[ne,se]=i.useState(!1),[K,G]=i.useState(null),[R,A]=i.useState(null),[V,le]=i.useState(""),[$,ke]=i.useState(null),[Ie,_e]=i.useState(null),[Ge,Fe]=i.useState(null),ve=ir(p=>p.ids),Te=vc(i.useCallback(p=>e?p.rankById:hi,[e])),me=xn(p=>e?wc(p.catalog):"",void 0,"catalog"),He=i.useMemo(()=>me?me.split("|"):Qn,[me]),we=i.useMemo(()=>new Set(He),[He]),xe=Sc(mo(p=>e?Object.entries(p.index.session.unseenCount).filter(([,J])=>J>0).map(([J])=>J).sort():Qn)),Ce=i.useMemo(()=>new Set(xe),[xe]),Ve=ir(p=>p.toggle),[Be,W]=i.useState(()=>{try{const p=an().getItem(Ko);if(!p)return new Set;const J=JSON.parse(p);return new Set(Array.isArray(J)?J.filter(Q=>typeof Q=="string"):[])}catch{return new Set}}),[H,ie]=i.useState(()=>{try{const p=an().getItem(Uo);if(!p)return new Map;const J=JSON.parse(p),Q=new Map;return Object.entries(J).forEach(([Oe,ft])=>{Array.isArray(ft)&&Q.set(Oe,ft.filter(Jt=>typeof Jt=="string"))}),Q}catch{return new Map}}),pe=i.useMemo(()=>{try{const p=an().getItem(Go);if(!p)return new Map;const J=JSON.parse(p),Q=new Map;return Object.entries(J).forEach(([Oe,ft])=>{typeof ft=="string"&&ft.length>0&&Q.set(Oe,ft)}),Q}catch{return new Map}},[]),Se=i.useCallback(p=>{try{f.setItem(Go,JSON.stringify(Object.fromEntries(p.entries())))}catch{}},[f]),[Y,be]=i.useState(new Map),ue=i.useRef(new Map),Ye=i.useRef(0),at=us(p=>p.homeDirectory),ze=us(p=>p.currentDirectory),je=kt(p=>p.projects),Ae=kt(p=>p.activeProjectId),ot=kt(p=>p.removeProject),ht=kt(p=>p.setActiveProjectIdOnly),pt=kt(p=>p.updateProjectMeta),ge=kt(p=>p.reorderProjects),Je=de(p=>p.setActiveMainTab),Tt=de(p=>p.openContextPanelTab),S=de(p=>p.setSettingsDialogOpen),Z=de(p=>p.setSettingsPage),ae=de(p=>p.toggleHelpDialog),ye=de(p=>p.setSessionSwitcherOpen),Re=de(p=>p.setArchivePageOpen),Ke=de(p=>p.notifyOnSubtasks),nt=de(p=>p.showDeletionDialog),ct=de(p=>p.setShowDeletionDialog),Gt=jc(u,120),it=i.useMemo(()=>Gt.trim().toLowerCase(),[Gt]),gt=it.length>0,yt=At(p=>p.collapsedFolderIds),Ze=At(p=>p.foldersMap),Bt=At(p=>p.getFoldersForScope),_t=At(p=>p.createFolder),Et=At(p=>p.renameFolder),xt=At(p=>p.deleteFolder),Mt=At(p=>p.addSessionToFolder),D=At(p=>p.addSessionsToFolder),fe=At(p=>p.removeSessionFromFolder),Ne=At(p=>p.removeSessionsFromFolders),Le=At(p=>p.toggleFolderCollapse),We=At(p=>p.getSessionFolderId);kf({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:w,sessionSearchContainerRef:m});const Ct=kc(e),E=pi(),X=mi(),ce=xn(p=>p.connection,void 0,"chrome"),$e=xn(p=>{for(const J of p.catalog.listStatusByDirectory.values())if(J==="ready")return!0;return!1},void 0,"catalog"),he=or({archived:!1}),Ee=or({archived:!0}),lt=`session-sidebar:${i.useId()}`,vt=De(p=>p.setCurrentSession),$t=De(p=>p.updateSessionTitle),Lt=De(p=>p.shareSession),Ht=De(p=>p.unshareSession),zt=De(p=>p.availableWorktreesByProject)??new Map,mt=De(p=>p.openNewSessionDraft),Ot=i.useCallback(p=>{de.getState().closeMainSurfaces(),mt(p),r?.()},[r,mt]),L=yn(mo(p=>({checkForUpdates:p.checkForUpdates,available:p.available,runtimeType:p.runtimeType,info:p.info,downloading:p.downloading,downloaded:p.downloaded,progress:p.progress,error:p.error,downloadUpdate:p.downloadUpdate,restartToUpdate:p.restartToUpdate}))),q=i.useMemo(()=>Cc(je,zt,{includeWorktrees:!0}),[zt,je]),ee=i.useMemo(()=>he.filter(p=>Xh(p,q,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[he,q]),te=i.useMemo(()=>[...ee,...Ee],[Ee,ee]),re=Dn(),rt=i.useMemo(()=>`${re}|${je.map(p=>`${p.id}:${Qe(p.path)??""}`).join("|")}`,[je,re]),[wt,St]=i.useState(null),Ut=wt!==rt,[es,jt]=i.useState(new Set),cs=i.useMemo(()=>wr(),[]),{isTablet:Ss}=Vs(),js=s||Ss,{buildGroupSearchText:Rn,filterSessionNodesForSearch:Zs,buildGroupedSessions:Fn}=jf({homeDirectory:at,pinnedSessionIds:ve,sessionOrderRanks:Te}),{scheduleCollapsedProjectsPersist:Xs}=Nf({safeStorage:f,keys:{sessionExpanded:Ho,projectCollapse:zo,groupOrder:Uo,groupCollapse:Ko},groupOrderByProject:H,collapsedGroups:Be,setExpandedParents:h,setCollapsedProjects:M}),ts=i.useMemo(()=>Nc(ee,ve,Te),[ve,Te,ee]),ks=i.useMemo(()=>ts.map(p=>p.id).join("|"),[ts]),$s=i.useRef(null),en=i.useMemo(()=>{const p=$s.current;if(p&&p.signature===ks)return p.map;const J=new Map(ts.map((Q,Oe)=>[Q.id,Oe]));return $s.current={signature:ks,map:J},J},[ts,ks]),_=i.useMemo(()=>{const p=new Map;return ts.forEach(J=>{const Q=J.parentID;if(!Q)return;const Oe=p.get(Q)??[];Oe.push(J),p.set(Q,Oe)}),p.forEach(J=>J.sort((Q,Oe)=>jn(Q,Oe,ve,Te))),p},[ts,ve,Te]),Pe=i.useMemo(()=>t.jsx(bs,{icon:"chat-new",mobileVariant:s,onClick:()=>Ot(),children:"New session"}),[s,Ot]),Xe=i.useMemo(()=>je.find(p=>p.id===C)??null,[je,C]),dt=i.useCallback(p=>{C&&pt(C,{label:p.label,defaultModel:p.defaultModel??null})},[C,pt]),Nt=i.useCallback(()=>{const p=yn.getState();if(p.available&&p.info){se(!0);return}L.checkForUpdates().then(()=>{const{available:J,error:Q}=yn.getState();if(Q){oe.error("Failed to check for updates",{description:Q});return}if(!J){oe.success("You are on the latest version");return}se(!0)})},[L]),ut=Ic(),Yt=i.useCallback(()=>{if(s&&ye(!1),r?.(),ut?.openSettings){ut.openSettings();return}S(!0)},[ut,s,r,ye,S]),Kt=L.available&&(L.runtimeType==="desktop"||L.runtimeType==="web"),Qt=De(p=>p.deleteSession),Cs=De(p=>p.deleteSessions),It=De(p=>p.archiveSession),Dt=De(p=>p.archiveSessions),Ns=De(p=>p.unarchiveSession),ta=De(p=>p.unarchiveSessions),{copiedSessionId:sa,handleSessionSelect:na,handleSessionDoubleClick:ra,handleSaveEdit:oa,handleCancelEdit:ia,handleShareSession:aa,handleCopyShareUrl:la,handleCopySessionId:ca,handleUnshareSession:da,handleDeleteSession:ua,handleRestoreSession:fa,confirmDeleteSession:ha}=Cf({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:y,setIsSessionSearchOpen:d,setActiveMainTab:Je,setSessionSwitcherOpen:ye,setCurrentSession:vt,updateSessionTitle:$t,shareSession:Lt,unshareSession:Ht,deleteSession:Qt,deleteSessions:Cs,archiveSession:It,archiveSessions:Dt,unarchiveSession:Ns,childrenMap:_,showDeletionDialog:nt,setDeleteSessionConfirm:ke,deleteSessionConfirm:$,setEditingId:v,setEditTitle:j,editingId:x,editTitle:g}),ma=i.useCallback(()=>{if(!Ie)return;const{scopeKey:p,folderId:J}=Ie;_e(null),xt(p,J)},[Ie,xt]),Mr=i.useCallback(()=>{vs.requestDirectoryDialog()},[]),pa=i.useCallback(p=>{h(J=>{const Q=Dc(J,p);try{f.setItem(Ho,JSON.stringify(Array.from(Q)))}catch{}return Q})},[f]),Ar=i.useCallback((p,J)=>{if(!p)return null;J&&yt.has(J)&&Le(J);const Q=_t(p,"New folder",J);return A(Q.id),le(Q.name),Q},[yt,Le,_t]),Rr=Wt(na),ga=Wt(ra),xa=Wt(oa),ba=Wt(ia),ya=Wt(aa),va=Wt(la),wa=Wt(ca),Sa=Wt(da),ja=Wt(ua),ka=Wt(fa),Ln=Wt(Ar),Fr=i.useCallback((p,J)=>{U(Q=>{const Oe=new Map(Q);return Oe.set(p,J+7),Oe})},[]),tn=i.useCallback(p=>{U(J=>{if(!J.has(p))return J;const Q=new Map(J);return Q.delete(p),Q})},[]),Lr=i.useCallback(p=>{U(J=>{let Q=!1;const Oe=new Map(J),ft=`${p}:`;for(const Jt of Oe.keys())Jt.startsWith(ft)&&(Oe.delete(Jt),Q=!0);return Q?Oe:J})},[]),Ca=i.useCallback(p=>{Ye.current=Date.now()+150,Lr(p),M(J=>{const Q=new Set(J);Q.has(p)?Q.delete(p):Q.add(p);try{f.setItem(zo,JSON.stringify(Array.from(Q)))}catch{}return Xs(Q),Q})},[Lr,f,Xs]),ds=i.useMemo(()=>je.map(p=>({...p,normalizedPath:Qe(p.path)})).filter(p=>!!p.normalizedPath),[je]),Na=i.useMemo(()=>ds.map(p=>p.normalizedPath),[ds]),Or=Pc(e?Na:Qn);Df({enabled:e,normalizedProjects:ds,gitRepoStatus:Or,setProjectRepoStatus:B,setProjectRootBranches:be});const Ia=De(p=>p.isLoading),Br=i.useMemo(()=>Of(ee,ds,zt,Ee),[Ee,zt,ds,ee]);Af({enabled:e,hasAuthoritativeGlobalSessions:$e,sessions:te});const{getSessionsForProject:Da,getArchivedSessionsForProject:Pa}=Pf({ownership:Br});bf({enabled:e,normalizedProjects:ds,ownership:Br,isSessionsLoading:Ia,hasAuthoritativeGlobalSessions:$e,isWorktreeTopologyLoading:Ut,unresolvedWorktreeProjectPaths:es,foldersMap:Ze,createFolder:_t,addSessionToFolder:Mt});const _r=i.useRef(!1);Ae&&P.has(Ae)&&(_r.current=!!P.get(Ae));const Ta=Lo(p=>p.showArchivedSessions),$r=Lo(p=>p.stickyZoneHeaders),On=kt(p=>p.manualProjectOrder),zr=i.useRef(new Set),sn=Tc(zr.current,b,"project");zr.current=sn;const Bn={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Ss,catalogSessions:he,archivedSessions:Ee,projects:je,activeProjectId:Ae,manualProjectOrder:On,currentDirectory:ze,availableWorktreesByProject:zt,pinnedSessionIds:ve,sessionOrderRanks:Te,foldersMap:Ze,collapsedFolderIds:yt,gitBranches:Ct,gitRepoStatus:Or,updateStore:L,showArchivedSessions:Ta,projectRepoStatus:P,projectRootBranches:Y,resolvedWorktreeTopologyKey:wt,unresolvedWorktreeProjectPaths:es,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:x,editTitle:g,editingProjectDialogId:C,expandedParents:b,collapsedProjects:I,visibleSessionCountByGroup:z,updateDialogOpen:ne,openSidebarMenuKey:K,renamingFolderId:R,renameFolderDraft:V,deleteSessionConfirm:$,deleteFolderConfirm:Ie,bulkDeleteConfirm:Ge,collapsedGroups:Be},Ur=i.useRef(null),Kr=Ur.current;if(Kr){let p=!1;for(const J of Object.keys(Bn))Object.is(Kr[J],Bn[J])||(Zt(`ui.session_sidebar.source.${J}`),p=!0);p||Zt("ui.session_sidebar.source.parent_or_context")}Ur.current=Bn;const Ea=i.useMemo(()=>{const p=new Map(On.map((J,Q)=>[J,Q]));return[...ds].sort((J,Q)=>(p.get(J.id)??1/0)-(p.get(Q.id)??1/0))},[On,ds]),{projectSections:bt,groupSearchDataByGroup:Gr,flatSectionsForRender:nn,searchMatchCount:Ma}=vf({normalizedProjects:Ea,getSessionsForProject:Da,getArchivedSessionsForProject:Pa,projectRepoStatus:P,projectRootBranches:Y,lastRepoStatus:_r.current,buildGroupedSessions:Fn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,filterSessionNodesForSearch:Zs,buildGroupSearchText:Rn,foldersMap:Ze}),Aa=i.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:Ra}=yf(H),Hr=i.useRef(!1);i.useEffect(()=>{if(Hr.current||bt.length===0)return;const p=bt.flatMap(J=>J.groups.filter(Q=>Q.isArchivedBucket).map(Q=>`${J.project.id}:${Q.id}`));p.length>0&&W(J=>new Set([...J,...p])),Hr.current=!0},[bt]),i.useMemo(()=>{const p=new Map,J=new Map;return bt.forEach(Q=>{const Oe=In(Q.project.label?.trim()||ys(Q.project.normalizedPath,at)||Q.project.normalizedPath);Q.groups.forEach(ft=>{const Jt=ft.branch&&ft.branch!=="HEAD"&&ft.branch!==Oe?ft.branch:null,zs={projectLabel:Oe,branchLabel:Jt},ms=al=>{al.forEach(Is=>{const Vr=Q.project.normalizedPath.length,ll=J.get(Is.session.id)??-1;Vr<ll||(p.set(Is.session.id,{node:Is,projectId:Q.project.id,groupDirectory:ft.directory,secondaryMeta:zs}),J.set(Is.session.id,Vr),Is.children.length>0&&ms(Is.children))})};ms(ft.sessions)})}),p},[bt,at]);const _n=i.useMemo(()=>nn.map(p=>p.groups.some(J=>J.isArchivedBucket)?{...p,groups:p.groups.filter(J=>!J.isArchivedBucket)}:p),[nn]),Fa=i.useMemo(()=>T?_n.filter(p=>p.project.id===T):_n,[_n,T]),La=i.useMemo(()=>{let p=0;for(const J of bt)for(const Q of J.groups)Q.isArchivedBucket||(p+=Q.sessions.length);return p},[bt]),Oa=i.useMemo(()=>{const p=new Map;for(const J of bt){let Q=0;for(const Oe of J.groups)Oe.isArchivedBucket||(Q+=Oe.sessions.length);p.set(J.project.id,Q)}return p},[bt]),Ba=i.useCallback(p=>{const J=bt.find(Q=>Q.project.id===p);return J?J.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Oe=>we.has(Oe.session.id))):!1},[we,bt]),_a=i.useCallback(p=>{const J=bt.find(Q=>Q.project.id===p);return J?J.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Oe=>Ce.has(Oe.session.id))):!1},[bt,Ce]),$a=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",za=s?"size-4":"h-4.5 w-4.5",Ua=Bf({enabled:e&&$r,isDesktopShellRuntime:cs,projectSections:bt,projectHeaderSentinelRefs:ue}),rn=Wt((p,J=0,Q,Oe,ft=!1,Jt,zs="project",ms)=>t.jsx(Wh,{node:p,depth:J,groupDirectory:Q,projectId:Oe,archivedBucket:ft,pinnedSessionIds:ve,expandedParents:sn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,notifyOnSubtasks:Ke,editingId:x,setEditingId:v,editTitle:g,setEditTitle:j,handleSaveEdit:xa,handleCancelEdit:ba,toggleParent:pa,handleSessionSelect:Rr,handleSessionDoubleClick:ga,togglePinnedSession:Ve,handleShareSession:ya,copiedSessionId:sa,handleCopyShareUrl:va,handleCopySessionId:wa,handleUnshareSession:Sa,openSidebarMenuKey:K,setOpenSidebarMenuKey:G,renamingFolderId:R,getFoldersForScope:Bt,getSessionFolderId:We,removeSessionFromFolder:fe,addSessionToFolder:Mt,createFolderAndStartRename:Ln,openContextPanelTab:Tt,handleDeleteSession:ja,handleRestoreSession:ka,mobileVariant:s,alwaysShowActions:js,renderSessionNode:rn,secondaryMeta:Jt,renderContext:zs,subtreeContainsEditing:ms?.subtreeContainsEditing??em,menuOpenSessionId:ms?.menuOpenSessionId??null,nodeStructureKey:ms?.nodeStructureKey??"",childRenderExtrasFor:ms?.childRenderExtrasFor})),Ka=i.useMemo(()=>{const p=new Map;return nn.forEach(J=>{const Q=J.groups.find(Oe=>!Oe.isArchivedBucket);Q?.folderScopes&&Q.folderScopes.length>0&&p.set(J.project.id,Q.folderScopes)}),p},[nn]),Ga=i.useCallback((p,J)=>{const Q=[];return J.forEach(Oe=>{Oe.isArchivedBucket||(Q.push(Oe.directory),Oe.folderScopes?.forEach(ft=>Q.push(ft.directory)))}),t.jsx(sm,{directories:Q})},[]),Wr=i.useCallback(p=>{tn(p),W(J=>{const Q=new Set(J);return Q.has(p)?Q.delete(p):Q.add(p),Q})},[tn]),Ha=i.useCallback((p,J,Q,Oe,ft,Jt,zs)=>t.jsx(rh,{group:p,groupKey:J,projectId:Q,hideGroupLabel:Oe,dragHandleProps:ft,compactBodyPadding:Jt,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,groupSearchDataByGroup:Gr,visibleSessionCount:z.get(J),collapsedGroups:Be,hideDirectoryControls:a,collapsedFolderIds:yt,toggleFolderCollapse:Le,renameFolder:Et,deleteFolder:xt,showDeletionDialog:nt,setDeleteFolderConfirm:_e,renderSessionNode:rn,showMoreGroupSessions:Fr,resetGroupSessionLimit:tn,mobileVariant:s,alwaysShowActions:js,activeProjectId:Ae,setActiveProjectIdOnly:ht,setActiveMainTab:Je,setSessionSwitcherOpen:ye,openNewSessionDraft:Ot,addSessionToFolder:Mt,createFolderAndStartRename:Ln,renamingFolderId:R,renameFolderDraft:V,setRenameFolderDraft:le,setRenamingFolderId:A,pinnedSessionIds:ve,expandedParents:sn,sessionOrderIndex:en,editingId:x,editTitle:g,openSidebarMenuKey:K,activeActivitySessionIds:we,unreadActivitySessionIds:Ce,notifyOnSubtasks:Ke,onToggleCollapsedGroup:Wr,scrollContainerRef:zs}),[gt,it,Gr,z,Be,a,yt,Le,Et,xt,nt,rn,Fr,tn,s,js,Ae,ht,Je,ye,Ot,Mt,Ln,R,V,ve,sn,en,x,g,K,we,Ce,Ke,Wr]),qr=!!(R||x||C),{selectionModeEnabled:Qr,hasSelection:Wa,selectedIdsSize:qa,bulkScopeIsArchived:Qa,derivedSelectionScope:Va,bulkScopeFolders:Ya,bulkCanRemoveFromFolder:Ja,handleToggleSelectionMode:Za,handleExitSelectionMode:Xa,handleBulkMoveToFolder:el,handleBulkCreateFolderAndMove:tl,handleBulkRemoveFromFolder:sl,handleBulkDelete:nl,handleBulkRestore:rl,confirmBulkDelete:ol}=Zh({isInlineEditing:qr,showDeletionDialog:nt,foldersMap:Ze,folderScopesByProject:Ka,addSessionsToFolder:D,removeSessionsFromFolders:Ne,createFolderAndStartRename:Ar,archiveSessions:Dt,unarchiveSessions:ta,deleteSessions:Cs,setBulkDeleteConfirm:Fe}),il=i.useCallback(()=>{de.getState().closeMainSurfaces(),Je("chat"),s&&ye(!1),mt(),r?.()},[s,r,mt,Je,ye]);return t.jsx(Ec,{delay:0,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:m,className:F("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(tm,{owner:lt,childStores:X,projectSections:bt,activeProjectId:Ae,collapsedProjects:I,collapsedGroups:Be,currentDirectory:ze}),t.jsx(Sf,{projectSections:bt,activeProjectId:Ae,initialActiveSessionByProject:pe,persistActiveSessionByProject:Se,handleSessionSelect:Rr,mobileVariant:s,openNewSessionDraft:mt,setActiveMainTab:Je,setSessionSwitcherOpen:ye}),t.jsx(xf,{enabled:e,sortedSessions:ts,prefetchSession:async p=>{await E.syncSession(p)}}),!a&&!s?t.jsx(ih,{onNewSession:il,showSidebarToggle:!0}):null,t.jsx(oh,{hideDirectoryControls:a,handleOpenDirectoryDialog:Mr,onOpenArchive:()=>{s&&ye(!1),Re(!0)},onOpenSettings:s?Yt:void 0,onOpenInstances:s?ut?.openInstances:void 0,instanceLabel:s?ut?.instanceLabel:void 0,onOpenUpdate:s?ut?.openUpdate:void 0,headerActionIconClass:za,headerActionButtonClass:$a,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:w,sessionSearchQuery:u,setSessionSearchQuery:y,hasSessionSearchQuery:gt,searchMatchCount:Ma,selectionModeEnabled:Qr,onToggleSelectionMode:Za,mobileVariant:s}),ce==="error"||ce==="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&&bt.length>0?t.jsx(ch,{projects:bt.map(p=>p.project),selectedProjectId:T,onSelectProject:p=>{O(p),p&&ht(p)},onOpenDirectoryDialog:Mr,onOpenProjectEditDialog:N,onRemoveProject:ot,totalSessionCount:La,getSessionCountForProject:p=>Oa.get(p)??0,hasActiveSessionByProject:Ba,hasUnseenByProject:_a,homeDirectory:at,mobileVariant:s}):null,e||s?t.jsx(bh,{sectionsForRender:Fa,projectSections:bt,activeProjectId:Ae,showOnlyMainWorkspace:l,hasSessionSearchQuery:gt,emptyState:Pe,searchEmptyState:Aa,isAllFoldersView:T===null,pinnedSessionIds:ve,renderSessionNode:rn,renderGroupSessions:Ha,homeDirectory:at,collapsedProjects:I,hideDirectoryControls:a,projectRepoStatus:P,isDesktopShellRuntime:cs,stickyZoneHeaders:$r,stuckProjectHeaders:Ua,mobileVariant:s,alwaysShowActions:js,toggleProject:Ca,setActiveProjectIdOnly:ht,setActiveMainTab:Je,setSessionSwitcherOpen:ye,openNewSessionDraft:Ot,openProjectEditDialog:N,removeProject:ot,projectHeaderSentinelRefs:ue,reorderProjects:ge,getOrderedGroups:Ra,setGroupOrderByProject:ie,renderProjectStatusIndicator:Ga,openSidebarMenuKey:K,setOpenSidebarMenuKey:G,isInlineEditing:qr}):null,Qr&&Wa?t.jsx(Jh,{selectedCount:qa,scopeKey:Va,scopeFolders:Ya,archivedBucket:Qa,onMoveToFolder:el,onCreateFolderAndMove:tl,onRemoveFromFolder:sl,canRemoveFromFolder:Ja,onRestore:rl,onDelete:nl,onDone:Xa}):null,s?null:t.jsx(dh,{onOpenSettings:Yt,onOpenShortcuts:ae,onOpenAbout:()=>{Z("about"),S(!0)},onOpenUpdate:Nt,showRuntimeButtons:!0,showUpdateButton:Kt}),t.jsx(iu,{open:ne,onOpenChange:se,info:L.info,downloading:L.downloading,downloaded:L.downloaded,progress:L.progress,error:L.error,onDownload:L.downloadUpdate,onRestart:L.restartToUpdate,runtimeType:L.runtimeType}),t.jsx(_f,{open:!!Xe,onOpenChange:p=>{p||N(null)},project:Xe,onSave:dt}),t.jsx(Qh,{value:$,setValue:ke,showDeletionDialog:nt,setShowDeletionDialog:ct,onConfirm:ha}),t.jsx(Yh,{value:Ie,setValue:_e,onConfirm:ma}),t.jsx(Vh,{value:Ge,setValue:Fe,showDeletionDialog:nt,setShowDeletionDialog:ct,onConfirm:ol})]})})},Lp=i.memo(nm),rm=({value:e,options:s,disabled:n,onChange:r})=>{const o=e||"Default",a=t.jsxs("div",{className:F("flex h-6 w-fit items-center gap-1.5 rounded-lg border border-border/20 bg-interactive-selection/20 px-2",n?"cursor-not-allowed opacity-60":"cursor-pointer hover:bg-interactive-hover/30"),children:[t.jsx("span",{className:"typography-micro whitespace-nowrap font-medium capitalize",children:o}),t.jsx(k,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:a}),t.jsxs(Xt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(Ft,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:F("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(Ft,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:F("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Wo=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function om(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:o=!1,onConfirm:a}=e,l=qt(h=>h.loadProviders),c=qt(h=>h.loadAgents),d=qt(h=>h.providers),u=qt(h=>h.currentProviderId),y=qt(h=>h.currentModelId),m=qt(h=>h.currentVariant||""),w=qt(h=>h.currentAgentName||""),[x,v]=i.useState(()=>Wo({providerID:u,modelID:y,variant:m,agent:w}));i.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),i.useEffect(()=>{s&&v(Wo({providerID:u,modelID:y,variant:m,agent:w}))},[s,u,y,m,w]),i.useEffect(()=>{if(!s||d.length===0)return;const h=d.find(T=>T.id===x.providerID)??d[0],f=Array.isArray(h?.models)?h.models:[],I=f.some(T=>T.id===x.modelID),M=f[0]?.id??"";h?.id===x.providerID&&I||v(T=>({...T,providerID:typeof h?.id=="string"?h.id:"",modelID:typeof M=="string"?I?T.modelID:M:"",variant:""}))},[s,d,x.providerID,x.modelID]),i.useCallback(h=>Mc(h.mode),[]);const g=i.useMemo(()=>{const f=d.find(I=>I.id===x.providerID)?.models?.find(I=>I.id===x.modelID);return f?.variants?Object.keys(f.variants):[]},[d,x.providerID,x.modelID]),j=g.length>0;i.useEffect(()=>{j||!x.variant||v(h=>({...h,variant:""}))},[j,x.variant]);const C=x.providerID.trim().length>0&&x.modelID.trim().length>0,N=i.useCallback(()=>{!C||o||a(x)},[C,o,a,x]);return i.useEffect(()=>{if(!s)return;const h=f=>{(f.metaKey||f.ctrlKey)&&f.key==="Enter"&&(f.preventDefault(),N())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[s,N]),t.jsx(os,{open:s,onOpenChange:h=>{o||n(h)},children:t.jsxs(is,{className:"max-w-md overflow-visible",children:[t.jsx(ws,{children:t.jsx(fs,{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(rm,{value:x.variant,options:g,disabled:!j,onChange:h=>v(f=>({...f,variant:h}))})]})}),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(Me,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:o,children:"Cancel"}),t.jsx(Me,{size:"sm",onClick:N,disabled:!C||o,children:o?"Sending":"Send"})]})})]})})}const yr=5,Zi=15,mn=new Map,wn=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},im=(e,s)=>{const n=wn(s);return Math.max(n*yr,Math.min(n*Zi,n*e))},am=async(e,s)=>{const n=await Bc(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},lm=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,qo=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],Qo=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},cm=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:o,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e});return t.jsx("li",{ref:o,style:{transform:An.Transform.toString(l),transition:c},className:F(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},dm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[o,a]=i.useState(!1),[l,c]=i.useState(""),[d,u]=i.useState([]),[y,m]=i.useState(""),[w,x]=i.useState(null),[v,g]=i.useState(()=>new Set),[j,C]=i.useState([]),[N,b]=i.useState(null),[h,f]=i.useState(!1),[I,M]=i.useState(0),T=i.useRef(!1),O=i.useRef(""),P=i.useRef(null),B=de(S=>S.todoPanelHeight),z=de(S=>S.setTodoPanelHeight),U=de(S=>S.notesPanelHeight),ne=de(S=>S.setNotesPanelHeight),[se,K]=i.useState(!1),G=i.useRef(0),R=i.useRef(B),A=De(S=>S.currentSessionId),V=De(S=>S.createSession),le=De(S=>S.initializeNewPiChamberSession),$=De(S=>S.sendMessage),ke=De(S=>S.setCurrentSession),Ie=Ac(S=>S.setPendingInputText),_e=us(S=>S.currentDirectory),Ge=de(S=>S.openContextPanelTab),Fe=de(S=>S.setActiveMainTab),ve=de(S=>S.setSessionSwitcherOpen),Te=de(S=>S.padding),me=i.useCallback(async(S,Z)=>{if(!e)return!1;const ae=e.id,Re=(mn.get(ae)??Promise.resolve()).catch(()=>{}).then(()=>Rc(e,{notes:S,todos:Z}));mn.set(ae,Re);try{const Ke=await Re;return Ke||oe.error("Failed to save project notes"),Ke}finally{mn.get(ae)===Re&&mn.delete(ae)}},[e]);i.useEffect(()=>{if(!e){c(""),u([]),C([]),m(""),g(new Set);return}let S=!1;return a(!0),(async()=>{try{const Z=await Fc(e),ae=await Promise.all(Z.plans.map(ye=>am(ye,"Plan")));if(S)return;c(Z.notes),u(qo(Z.todos)),C(ae),O.current=Z.notes,T.current=!0,m(""),g(new Set)}catch{S||(oe.error("Failed to load project notes"),c(""),u([]),C([]),O.current="",T.current=!0)}finally{S||a(!1)}})(),()=>{S=!0}},[I,e]),i.useEffect(()=>{if(!e)return;const S=Z=>{const ae=Z.detail;ae?.projectId&&ae.projectId!==e.id||M(ye=>ye+1)};return window.addEventListener("pichamber:project-plan-saved",S),window.addEventListener("pichamber:project-notes-updated",S),()=>{window.removeEventListener("pichamber:project-plan-saved",S),window.removeEventListener("pichamber:project-notes-updated",S)}},[e]),i.useEffect(()=>{if(d.length<7)return;const S=im(d.length,Te),Z=wn(Te)*yr;B!==S&&(B<Z||B>S)&&z(S)},[d.length,Te,B,z]),i.useEffect(()=>{if(!se)return;const S=ae=>{const ye=ae.clientY-G.current,Re=Math.min(wn(Te)*Zi,Math.max(wn(Te)*yr,R.current+ye));z(Re)},Z=()=>{K(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",Z,{once:!0}),window.addEventListener("pointercancel",Z,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",Z),window.removeEventListener("pointercancel",Z)}},[se,Te,z]);const He=i.useCallback(S=>{K(!0),G.current=S.clientY,R.current=B,S.preventDefault()},[B]),we=i.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),xe=i.useCallback(()=>{we(),O.current=l,me(l,d)},[we,l,me,d]);i.useEffect(()=>{if(!(!e||!T.current)&&l!==O.current)return P.current=window.setTimeout(()=>{P.current=null,O.current=l,me(l,d)},400),()=>{we()}},[we,l,me,e,d]),i.useEffect(()=>()=>we(),[we]);const Ce=i.useCallback(()=>{const S=y.trim();if(!S)return;const Z=Qo(d,{id:lm(),text:S.slice(0,on),completed:!1,createdAt:Date.now()});u(Z),m(""),me(l,Z)},[y,l,me,d]),Ve=i.useCallback(S=>{g(Z=>{const ae=new Set(Z);return ae.has(S)?ae.delete(S):ae.add(S),ae})},[]),Be=i.useCallback((S,Z)=>{const ae=d.find(nt=>nt.id===S);if(!ae||ae.completed===Z)return;const ye=d.filter(nt=>nt.id!==S),Re={...ae,completed:Z},Ke=Z?[...ye,Re]:Qo(ye,Re);u(Ke),me(l,Ke)},[l,me,d]),W=i.useCallback(S=>{const Z=d.filter(ae=>ae.id!==S);u(Z),me(l,Z)},[l,me,d]),H=i.useCallback(()=>{const S=d.filter(Z=>!Z.completed);S.length!==d.length&&(u(S),me(l,S))},[l,me,d]),ie=i.useCallback(S=>{const{active:Z,over:ae}=S;if(!ae||Z.id===ae.id)return;const ye=d.findIndex(nt=>nt.id===Z.id),Re=d.findIndex(nt=>nt.id===ae.id);if(ye===-1||Re===-1)return;const Ke=qo(Md(d,ye,Re));u(Ke),me(l,Ke)},[l,me,d]),pe=Pn(qs(Cr,{activationConstraint:{distance:8}})),Se=y.slice(0,on),Y=d.reduce((S,Z)=>S+(Z.completed?1:0),0),be=i.useCallback(()=>{Fe("chat"),ve(!1)},[Fe,ve]),ue=i.useCallback((S,Z)=>{!e||w!==null||b({todoId:S,todoText:Z})},[e,w]),Ye=i.useCallback(S=>{if(!A){oe.error("No active session selected");return}be();const Z=`\`\`\`md
38
- ${S}
39
- \`\`\``;Ie(Z,"append"),oe.success("Todo sent to current session"),n?.()},[A,n,be,Ie]),at=i.useCallback(async S=>{if(!e||!N)return;const Z=await lo("plan.todo.visible",{todo_text:N.todoText}),ye=[{synthetic:!0,text:await lo("plan.todo.instructions",{todo_text:N.todoText})}];f(!0),x(N.todoId);try{be();const Re=await V(void 0,e.path,null);if(!Re?.id){oe.error("Failed to create session");return}const Ke=Re.id,nt=Re.directory??e.path;le(Re.id,qt.getState().agents??[]);const ct=Lc.getState();ct.saveSessionModelSelection(Ke,S.providerID,S.modelID),S.agent.trim()&&(ct.saveSessionAgentSelection(Ke,S.agent),ct.saveAgentModelForSession(Ke,S.agent,S.providerID,S.modelID),ct.saveAgentModelVariantForSession(Ke,S.agent,S.providerID,S.modelID,S.variant||void 0)),ke(Ke,nt),await $(Z,S.providerID,S.modelID,S.agent.trim()||void 0,void 0,void 0,ye,S.variant||void 0),oe.success("Todo sent to new session"),b(null),n?.()}catch{oe.error("Failed to send note")}finally{f(!1),x(null)}},[V,le,n,N,e,be,$,ke]),ze=i.useRef(null),[je,Ae]=i.useState(!1),[ot,ht]=i.useState(null),pt=i.useCallback(async S=>{if(!(!e||ot)){ht(S);try{if(!await Oc(e,S)){oe.error("Failed to delete plan");return}C(ae=>ae.filter(ye=>ye.id!==S)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{ht(null)}}},[ot,e]),ge=i.useCallback(async()=>{if(!e||je)return;const S=await md({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(S.success&&S.path){Ae(!0);try{const Z=new URLSearchParams({path:S.path,allowOutsideWorkspace:"true"});S.outsideFileGrant&&Z.set("outsideFileGrant",S.outsideFileGrant);const ae=await rs(`/api/fs/read?${Z.toString()}`,{cache:"no-store"});if(!ae.ok){oe.error("Failed to read plan file");return}const ye=await ae.text();if(!ye.trim()){oe.error("Plan file is empty");return}const Re=S.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await co(e,ye,Re)){oe.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),oe.success("Plan imported")}catch(Z){const ae=Z instanceof Error?Z.message:void 0;oe.error("Failed to read plan file",ae?{description:ae}:void 0)}finally{Ae(!1)}}else S.error==="Native file picker not available"&&ze.current?.click()},[je,e]),Je=i.useCallback(async S=>{if(!(!e||!S)){Ae(!0);try{const Z=await S.text();if(!Z.trim()){oe.error("Plan file is empty");return}const ae=S.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await co(e,Z,ae)){oe.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),oe.success("Plan imported")}catch(Z){const ae=Z instanceof Error?Z.message:void 0;oe.error("Failed to read plan file",ae?{description:ae}:void 0)}finally{Ae(!1)}}},[e]),Tt=i.useCallback(S=>{const Z=e?.path?.trim(),ae=_e?.trim()||Z;ae&&Ge(ae,{mode:"file",targetPath:S.path,dedupeKey:S.path,label:S.title})},[_e,Ge,e]);return e?t.jsxs("div",{className:F("w-full min-w-0 space-y-3 p-3",r),children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:e.path,children:`Quick notes - ${s?.trim()||e.path.split("/").filter(Boolean).pop()||e.path}`}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",uo]})]}),t.jsx(Dr,{value:l,onChange:S=>c(S.target.value.slice(0,uo)),onBlur:xe,placeholder:"Capture context, reminders, or links",resizedHeight:U,onResizeHeightChange:ne,useScrollShadow:!0,scrollShadowSize:56,disabled:o})]}),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:H,disabled:o||Y===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:[Se.length,"/",on]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{value:Se,onChange:S=>m(S.target.value.slice(0,on)),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),Ce())},placeholder:"Add a todo",disabled:o,className:"h-8"}),t.jsx("button",{type:"button",onClick:Ce,disabled:o||Se.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",title:"Add todo",children:t.jsx(k,{name:"add",className:"h-4 w-4"})})]}),t.jsx("div",{className:F("overflow-y-auto rounded-lg border border-border/60 bg-background/40",se&&"transition-none"),style:d.length<7?void 0:{height:`${B}px`,maxHeight:`${B}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(Tn,{sensors:pe,collisionDetection:En,onDragEnd:ie,children:t.jsx(Nr,{items:d.map(S=>S.id),strategy:Ii,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(S=>{const Z=v.has(S.id);return t.jsx(cm,{id:S.id,children:ae=>t.jsxs("div",{className:F("flex gap-1.5 px-2.5 py-1.5",Z?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:ae.setActivatorNodeRef,...ae.attributes,...ae.listeners,onClick:ye=>{ye.preventDefault(),ye.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 \\"${S.text}\\"`,title:`Reorder \\"${S.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(si,{checked:S.completed,onChange:ye=>Be(S.id,ye),ariaLabel:`Mark \\"${S.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>Ve(S.id),className:F("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",Z?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",S.completed&&"text-muted-foreground line-through"),title:Z?void 0:S.text,"aria-label":Z?`Collapse todo \\"${S.text}\\"`:`Expand todo \\"${S.text}\\"`,children:S.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>W(S.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 \\"${S.text}\\"`,title:`Delete \\"${S.text}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",disabled:w===S.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 \\"${S.text}\\"`,title:`Send \\"${S.text}\\"`,children:t.jsx(k,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-56",children:[t.jsx(Ft,{onClick:()=>Ye(S.text),children:"Send to current session"}),t.jsx(Ft,{onClick:()=>ue(S.id,S.text),children:"Send to new session"})]})]})]})]})},S.id)})})})})}),d.length>=7&&t.jsx("div",{className:F("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",se&&"bg-[var(--interactive-border)]"),onPointerDown:He,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:j.length===1?`${j.length} file`:`${j.length} files`})]}),t.jsx("input",{ref:ze,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:S=>{const Z=S.target.files?.[0]??null;Je(Z),S.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:ge,disabled:!e||je,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:j.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:j.map(S=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>Tt(S),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:S.title}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(S.createdAt).toLocaleDateString("en-US")})]}),t.jsx("button",{type:"button",onClick:()=>{pt(S.id)},disabled:ot===S.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 \\"${S.title}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},S.id))})})]}),t.jsx(om,{open:N!==null,onOpenChange:S=>{!S&&!h&&b(null)},projectDirectory:e?.path??null,submitting:h,onConfirm:at})]}):t.jsx("div",{className:F("w-full min-w-0 p-3",r),children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},Op=({onActionComplete:e})=>{const s=kt(c=>c.activeProjectId),n=kt(c=>c.projects),r=us(c=>c.homeDirectory),o=i.useMemo(()=>s?n.find(c=>c.id===s)??n[0]??null:n[0]??null,[s,n]),a=i.useMemo(()=>o?{id:o.id,path:o.path}:null,[o]),l=i.useMemo(()=>o?o.label?.trim()||ys(o.path,r)||o.path:null,[o,r]);return t.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:t.jsx(dm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Sn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),vr=512*1024,um=new TextEncoder,fm=new TextDecoder,Vn=e=>{const s=um.encode(e);if(s.byteLength<=vr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-vr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:fm.decode(r),byteLength:r.byteLength}},Ps=(e,s)=>`${e}\0${s}`,Yn=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},hm="terminal-store";let Vo=!1,Yo=0;const pn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Yo+=1,`tab-${Date.now().toString(36)}-${Yo.toString(36)}`),Jn=e=>typeof e=="object"&&e!==null,mm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function Pt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const pm=/^Terminal(?: (\d+))?$/,gm=e=>{let s=0;for(const n of e){const r=pm.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(s=Math.max(s,o))}return s===0?"Terminal":`Terminal ${s+1}`},Zn=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Xn=e=>({tabs:[e],activeTabId:e.id}),Vt=(e,s)=>e.tabs.findIndex(n=>n.id===s);let er=null,tr=null;const xm=e=>{if(tr&&er?.sessions===e.sessions&&er.nextTabId===e.nextTabId)return tr;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return er={sessions:e.sessions,nextTabId:e.nextTabId},tr=s,s},bm=()=>{const e=Nd(()=>pd());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))}},qe=hs()(Ci(kr((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Pt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=pn(),c=Zn(l,"Terminal");return a.set(r,Xn(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Pt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=Pt(n),o=s().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Ps(Pt(n),r))??Sn,createTab:n=>{const r=Pt(n);if(!r)return"tab-invalid";const o=pn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=gm(c?.tabs??[]),y=Zn(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,y]}):l.set(r,Xn(y)),{sessions:l,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Pt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Vt(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=Pt(n),l=o.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const y=Vt(u,r);if(y<0||u.tabs[y]?.label===l)return c;const m=[...u.tabs];return m[y]={...m[y],label:l},d.set(a,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Pt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Vt(d,r);if(u<0)return l;const y=o?.trim()||null;if(d.tabs[u]?.iconKey===y)return l;const m=[...d.tabs];return m[u]={...m[u],iconKey:y},c.set(a,{...d,tabs:m}),{sessions:c}})},closeTab:(n,r)=>{const o=Pt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Vt(c,r);if(d<0)return a;const u=c.tabs.filter(g=>g.id!==r),y=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,g])=>!(g.directory===o&&g.tabId===r))),m=Object.keys(y).length!==Object.keys(a.projectActionRuns).length,w=Ps(o,r),x=a.buffers.has(w)?Yn(a.buffers,g=>g===w):null;if(u.length===0){const g=pn(),j=Zn(g,"Terminal");return l.set(o,Xn(j)),{sessions:l,nextTabId:a.nextTabId+1,...x?{buffers:x}:{},...m?{projectActionRuns:y}:{}}}let v=c.activeTabId;return c.activeTabId===r&&(v=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:v}),{sessions:l,...x?{buffers:x}:{},...m?{projectActionRuns:y}:{}}})},setTabSessionId:(n,r,o)=>{const a=Pt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Vt(d,r);if(u<0)return l;const y=d.tabs[u],m=o!==null&&y.terminalSessionId!==o,w=o?"running":y.terminalSessionId?"exited":y.lifecycle,x={...y,terminalSessionId:o,lifecycle:w,isConnecting:!1},v=Ps(a,r),g=m&&l.buffers.has(v)?Yn(l.buffers,C=>C===v):null,j=[...d.tabs];return j[u]=x,c.set(a,{...d,tabs:j}),{sessions:c,...g?{buffers:g}:{}}})},setTabLifecycle:(n,r,o)=>{const a=Pt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Vt(d,r);if(u<0)return l;const y=[...d.tabs];return y[u]={...y[u],lifecycle:o,isConnecting:!1},c.set(a,{...d,tabs:y}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=Pt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Vt(d,r);if(u<0)return l;const y=[...d.tabs];return y[u]={...y[u],isConnecting:o},c.set(a,{...d,tabs:y}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=Pt(n);e(c=>{const d=c.sessions.get(l);if(!d||Vt(d,r)<0)return c;const u=Ps(l,r),y=c.buffers.get(u)??Sn;if(y.lastSequence>a)return c;const m=Vn(o);if(y.lastSequence===a&&y.byteLength===m.byteLength&&y.chunks.map(v=>v.data).join("")===m.text)return c;const w=c.nextChunkId,x=new Map(c.buffers);return x.set(u,{chunks:m.text?[{id:w,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:a}),{buffers:x,nextChunkId:m.text?w+1:w}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=Pt(n);e(d=>{const u=d.sessions.get(c);if(!u||Vt(u,r)<0)return d;const y=Ps(c,r),m=d.buffers.get(y)??Sn;if(a!==void 0&&a<=m.lastSequence)return d;const w=d.nextChunkId,x=Vn(o),v=l!==void 0&&l!==o?Vn(l).text:void 0,g={id:w,data:x.text,...v!==void 0?{replayData:v}:{},byteLength:x.byteLength},j=[...m.chunks,g];let C=m.byteLength+g.byteLength;for(;C>vr&&j.length>1;){const b=j.shift();if(!b)break;C-=b.byteLength}const N=new Map(d.buffers);return N.set(y,{chunks:j,byteLength:C,lastSequence:a??m.lastSequence}),{buffers:N,nextChunkId:w+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=Pt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const y=Vt(u,r);if(y<0)return c;const m=u.tabs[y],w=a.autoOpened??m.previewAutoOpened,x=a.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===w&&m.previewUrlLocked===x)return c;const v=[...u.tabs];return v[y]={...m,previewUrl:o,previewAutoOpened:w,previewUrlLocked:x},d.set(l,{...u,tabs:v}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Pt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Vt(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const y=[...c.tabs];return y[d]={...u,previewAutoOpened:!0},l.set(o,{...c,tabs:y}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=Pt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Ps(r,""),c=Yn(o.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(o.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:hm,storage:bm(),partialize:xm,merge:(e,s)=>{if(!Jn(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!Jn(u))continue;const y=Array.isArray(u.tabs)?u.tabs:[],m=[],w=new Map;for(const j of y){if(!Jn(j))continue;const C=typeof j.id=="string"?j.id:null;if(!C)continue;const N=mm(C);N!==null&&(o=Math.max(o,N));const b=N===null?C:pn();w.set(C,b),m.push({id:b,label:typeof j.label=="string"?j.label:"Terminal",iconKey:typeof j.iconKey=="string"?j.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof j.createdAt=="number"?j.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const x=typeof u.activeTabId=="string"?u.activeTabId:null,v=x?w.get(x)??x:null,g=v?m.some(j=>j.id===v):!1;r.set(d,{tabs:m,activeTabId:g?v:m[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!Vo){Vo=!0;const e=qe.persist,s=()=>{qe.getState().hasHydrated||qe.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function ym(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 vm(e,s,n,r,o=!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:o}}const sr=["\x1B[0m","\x1B[m"],wm=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 o=r.slice(1,4).map(Number);return o.some(a=>a<0||a>255)?null:o},Jo=e=>{const s=wm(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},Sm=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let o=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(y=>y.length>u.length&&y.startsWith(u))&&(o=d)}const l=o>0?r.slice(-o):"";let c=o>0?r.slice(0,-o):r;for(const d of sr)c=c.replaceAll(d,n);return{data:c,carry:l}},jm=(e,s,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(o-1,l))}},km=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,a=n;for(;o>0&&r(e[o-1]);)o-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:o,endColumn:a}};let Cm=null;const Nm=()=>Cm??=Ms(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,8])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Im=2e3,Dm=()=>{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,Im))]).then(()=>{})},Pm=(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 o=r.measureText("M"),a=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.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))}},Xi=i.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:y=!0},m)=>{const w=i.useRef(null),x=i.useRef(null),v=i.useRef(null),g=i.useRef(n),j=i.useRef(r),C=i.useRef(null),N=i.useRef(null),b=i.useRef(null),h=i.useRef(""),f=i.useRef(""),I=i.useRef(Jo(o.background)),M=i.useRef(!1),T=i.useRef(0),O=i.useRef(y),P=i.useRef(!1),[B,z]=i.useState(0),[U,ne]=i.useState(0);g.current=n,j.current=r,O.current=y,I.current=Jo(o.background),i.useLayoutEffect(()=>{const R=w.current;if(!R)return;const A=Pm(R,a,l);N.current=A,A&&j.current(A.cols,A.rows)},[a,l]);const se=i.useCallback(()=>{const R=w.current,A=x.current;if(!R||!A||!v.current||!O.current)return;const V=R.getBoundingClientRect();if(!(V.width<24||V.height<24))try{v.current.fit();const le={cols:A.cols,rows:A.rows};(!C.current||C.current.cols!==le.cols||C.current.rows!==le.rows)&&(C.current=le,j.current(le.cols,le.rows)),P.current||(P.current=!0,z($=>$+1))}catch{}},[]),K=i.useCallback(()=>{if(M.current||!h.current||!x.current)return;const R=x.current,A=h.current;h.current="";const V=Sm(A,f.current,I.current);if(f.current=V.carry,!V.data){h.current&&K();return}M.current=!0;const le=T.current;R.write(V.data,()=>{x.current!==R||T.current!==le||(M.current=!1,h.current&&K())})},[]),G=i.useCallback(()=>{b.current=null,h.current="",f.current="",M.current=!1,T.current+=1;const R=x.current;if(!R){ne(A=>A+1);return}try{R.reset();const A=I.current;A&&R.write(`${A}\x1B[2J\x1B[H`)}catch{ne(A=>A+1)}},[]);return i.useEffect(()=>{const R=w.current;if(!R)return;let A=!1,V=null,le=null,$=null,ke=null,Ie=[];const _e=()=>{V&&O.current&&(V.options.cursorBlink=!0)},Ge=Te=>{Te.relatedTarget instanceof Node&&R.contains(Te.relatedTarget)||V&&(V.options.cursorBlink=!1)},Fe=()=>{V&&O.current&&R.contains(document.activeElement)&&(V.options.cursorBlink=!0)},ve=()=>{V&&(V.options.cursorBlink=!1)};return R.addEventListener("focusin",_e),R.addEventListener("focusout",Ge),window.addEventListener("focus",Fe),window.addEventListener("blur",ve),Promise.all([Nm(),Dm()]).then(([{module:Te,ghostty:me}])=>{if(A)return;V=new Te.Terminal({...vm(a,l,o,me,!1),...N.current??{}});const He=new Te.FitAddon;V.loadAddon(He),V.open(R),x.current=V,v.current=He,Ie=[V.onData(xe=>g.current(xe))],le=new ResizeObserver(()=>{$&&clearTimeout($),$=setTimeout(se,80)}),le.observe(R),se();const we=I.current;we&&V.write(`${we}\x1B[2J\x1B[H`),ke=requestAnimationFrame(se)}),()=>{A=!0;const Te=document.activeElement;Te instanceof HTMLElement&&R.contains(Te)&&(Te.blur(),window.Capacitor?.getPlatform?.()==="android"&&Ms(async()=>{const{Keyboard:He}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:He}},__vite__mapDeps([113,114])).then(({Keyboard:He})=>He.hide()).catch(()=>{})),le?.disconnect(),$&&clearTimeout($),ke!==null&&cancelAnimationFrame(ke),R.removeEventListener("focusin",_e),R.removeEventListener("focusout",Ge),window.removeEventListener("focus",Fe),window.removeEventListener("blur",ve),Ie.forEach(me=>me.dispose()),V?.dispose(),x.current=null,v.current=null,C.current=null,b.current=null,h.current="",f.current="",M.current=!1,T.current+=1,P.current=!1}},[se,a,l,U,o]),i.useEffect(()=>{const R=x.current,A=w.current;!R||!A||(R.options.cursorBlink=y&&document.hasFocus()&&A.contains(document.activeElement))},[y,B]),i.useEffect(()=>{if(!x.current)return;if(s.length===0){b.current!==null&&G();return}const A=b.current;let V=-1;if(A!==null){for(let ke=s.length-1;ke>=0;ke-=1){const Ie=s[ke].id;if(Ie===A){V=ke;break}if(Ie<A)break}if(V<0){G();return}}const le=V<0,$=V>=0?s.slice(V+1):s;h.current+=$.map(ke=>le?ke.replayData??ke.data:ke.data).join(""),b.current=s.at(-1)?.id??null,K()},[s,K,B,G]),i.useEffect(()=>{if(!u||!y)return;const R=requestAnimationFrame(()=>x.current?.focus());return()=>cancelAnimationFrame(R)},[u,y,B,e]),i.useEffect(()=>{const R=w.current;if(!d||!R)return;const A=V=>{const le=V;if(!le.isComposing)switch(le.inputType){case"insertText":le.data&&g.current(le.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return R.addEventListener("beforeinput",A),()=>R.removeEventListener("beforeinput",A)},[d,B]),i.useEffect(()=>{const R=w.current,A=x.current;if(!d||!R||!A)return;let V=null,le=null,$="idle",ke=0,Ie=0,_e=0,Ge=0,Fe=null;const ve=Math.max(12,l+2),Te=()=>{window.Capacitor?.getPlatform?.()==="android"&&Ms(async()=>{const{Keyboard:ie}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ie}},__vite__mapDeps([113,114])).then(({Keyboard:ie})=>ie.show()).catch(()=>{})},me=()=>{le&&(clearTimeout(le),le=null)},He=(H,ie)=>{const pe=R.querySelector("canvas");return pe?jm(H,ie,pe.getBoundingClientRect(),A.cols,A.rows):null},we=(H,ie)=>{const pe=R.querySelector("canvas");if(!pe)return;const Se=pe.getBoundingClientRect(),Y=Se.left+(ie.column+.5)/A.cols*Se.width,be=Se.top+(ie.row+.5)/A.rows*Se.height;pe.dispatchEvent(new MouseEvent(H,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Y,clientY:be}))},xe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},Ce=H=>{H.pointerType!=="touch"||V!==null||(V=H.pointerId,$="pending",ke=H.clientX,Ie=H.clientY,_e=H.clientY,Ge=0,Fe=null,R.setPointerCapture(H.pointerId),le=setTimeout(()=>{if(le=null,V!==H.pointerId||$!=="pending")return;const ie=He(ke,Ie);if(!ie)return;const pe=A.buffer.active,Se=Math.max(0,pe.length-A.rows-pe.viewportY+ie.row),Y=pe.getLine(Se),be=Array.from({length:A.cols},(at,ze)=>Y?.getCell(ze)?.getChars()??""),ue=km(be,ie.column),Ye={column:ue.startColumn,row:ie.row};Fe={column:ue.endColumn,row:ie.row},$="selecting",we("mousedown",Ye),we("mousemove",Fe)},350))},Ve=H=>{if(V!==H.pointerId)return;if($==="selecting"){const Se=He(H.clientX,H.clientY);Se&&(!Fe||Se.column!==Fe.column||Se.row!==Fe.row)&&(Fe=Se,we("mousemove",Se)),H.cancelable&&H.preventDefault();return}if($==="pending"){if(Math.hypot(H.clientX-ke,H.clientY-Ie)<8)return;me(),$="scrolling"}if($!=="scrolling")return;const ie=_e-H.clientY;_e=H.clientY,Ge+=ie;const pe=Math.trunc(Ge/ve);pe&&(A.scrollLines(pe),Ge-=pe*ve),H.cancelable&&H.preventDefault()},Be=H=>{if(V!==H.pointerId)return;const ie=$==="pending",pe=$==="selecting";me(),R.hasPointerCapture(H.pointerId)&&R.releasePointerCapture(H.pointerId),V=null,$="idle",pe&&xe(),ie&&(A.focus(),Te())},W=H=>{if(V!==H.pointerId)return;const ie=$==="selecting";me(),R.hasPointerCapture(H.pointerId)&&R.releasePointerCapture(H.pointerId),V=null,$="idle",ie&&xe()};return R.addEventListener("pointerdown",Ce),R.addEventListener("pointermove",Ve,{passive:!1}),R.addEventListener("pointerup",Be),R.addEventListener("pointercancel",W),()=>{me(),R.removeEventListener("pointerdown",Ce),R.removeEventListener("pointermove",Ve),R.removeEventListener("pointerup",Be),R.removeEventListener("pointercancel",W)}},[d,l,B]),i.useImperativeHandle(m,()=>({focus:()=>x.current?.focus(),fit:se,getSelection:()=>{const R=x.current,A=R?.getSelectionPosition(),V=R?.getSelection()??"";return!A||!V.trim()?null:{text:V,startLine:A.start.y+1,endLine:A.end.y+1}}}),[se]),t.jsx("div",{ref:w,"data-terminal-owner":"main",className:F("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});Xi.displayName="TerminalViewport";const Tm=280,Zo=4,Em=({transform:e})=>({...e,y:0}),Mm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:o,setNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:An.Transform.toString(l),transition:c},className:F("h-full rounded-md",n,d&&"opacity-50"),...r,...o,children:s})},Am=({id:e,children:s,className:n})=>t.jsx("div",{className:F("h-full",n),"data-sortable-tab-id":e,children:s}),Rm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:o,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:y,activePillLowercase:m=!0,nonCompositedIndicator:w=!1,className:x})=>{const v=de(W=>W.isMobile),{isTablet:g}=Vs(),j=v||g,C=i.useRef(null),[N,b]=i.useState({left:!1,right:!1}),h=i.useMemo(()=>e.map(W=>W.id),[e]),f=a==="scrollable",I=l==="default",M=l==="active-pill",O=M||l==="animated",P=I,B=O||P,z=M&&f,U=O,ne=y??O,se=typeof o=="function",K=se?Mm:Am,G=i.useRef(new Map),[R,A]=i.useState(null),[V,le]=i.useState(!1),[$,ke]=i.useState(null),Ie=i.useRef(!1),_e=i.useRef(0),Ge=i.useRef(s),Fe=i.useRef(null),ve=i.useMemo(()=>{if(!B||!$||!s||$===s)return 0;const W=e.findIndex(ie=>ie.id===$),H=e.findIndex(ie=>ie.id===s);return W<0||H<0?0:W>H?Zo:-Zo},[s,e,$,B]),Te=Pn(qs(Cr,{activationConstraint:{distance:8}})),me=i.useCallback((W,H)=>!W||!H?W===H:Math.abs(W.left-H.left)<.5&&Math.abs(W.top-H.top)<.5&&Math.abs(W.width-H.width)<.5&&Math.abs(W.height-H.height)<.5,[]),He=i.useCallback((W,H)=>{if(H){G.current.set(W,H);return}G.current.delete(W)},[]),we=i.useCallback(()=>{if(!B||!s){A(be=>be===null?be:null);return}const W=C.current,H=G.current.get(s);if(!W||!H){A(be=>be===null?be:null);return}let ie=0,pe=0,Se=H;for(;Se&&Se!==W;)ie+=Se.offsetLeft,pe+=Se.offsetTop,Se=Se.offsetParent;const Y={left:ie,top:pe,width:H.offsetWidth,height:H.offsetHeight};A(be=>me(be,Y)?be:Y)},[s,me,B]),xe=i.useCallback(()=>{if(!f){b({left:!1,right:!1});return}const W=C.current;if(!W){b({left:!1,right:!1});return}b({left:W.scrollLeft>2,right:W.scrollLeft+W.clientWidth<W.scrollWidth-2})},[f]);i.useEffect(()=>{if(!f){b({left:!1,right:!1});return}const W=C.current;if(!W)return;xe(),W.addEventListener("scroll",xe,{passive:!0});const H=new ResizeObserver(xe);return H.observe(W),()=>{W.removeEventListener("scroll",xe),H.disconnect()}},[f,e.length,xe]),i.useEffect(()=>{if(!B){A(null);return}we();const W=C.current;if(!W)return;const H=new ResizeObserver(()=>{performance.now()-_e.current>Tm&&le(!1),we()});if(H.observe(W),s){const ie=G.current.get(s);ie&&H.observe(ie)}return()=>{H.disconnect()}},[s,e.length,we,B]),i.useLayoutEffect(()=>{we()});const Ce=h.join("\0");i.useLayoutEffect(()=>{if(!B){Ie.current=!1,le(!1);return}const W=Fe.current!==Ce;if(Fe.current=Ce,!Ie.current){Ie.current=!0,Ge.current=s;return}const H=Ge.current!==s;if(Ge.current=s,!H||W){le(!1);return}_e.current=performance.now(),le(!0)},[s,Ce,B]),i.useEffect(()=>{if(!f||!s)return;const W=C.current;if(!W)return;const H=window.requestAnimationFrame(()=>{const ie=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),pe=W.querySelector(`[data-sortable-tab-id="${ie}"]`);pe&&(pe.scrollIntoView({block:"nearest",inline:"nearest"}),xe())});return()=>{window.cancelAnimationFrame(H)}},[s,f,e.length,xe]);const Ve=i.useCallback(W=>{if(!o)return;const{active:H,over:ie}=W;!ie||H.id===ie.id||o(String(H.id),String(ie.id))},[o]),Be=t.jsxs("div",{className:F("relative flex h-full min-w-0 flex-1",x),children:[f&&N.left?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",O?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,f&&N.right?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",O?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:C,className:F("relative flex h-full min-w-0 flex-1",O?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",O&&"@container/pill-tabs",O&&"pill-tabs__track",O&&(c??"gap-0.5 py-0.5"),P&&"items-center overflow-y-hidden",U&&"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",f?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:f?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[O&&R?t.jsx("div",{className:F("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",ne&&V&&(w?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:w?{left:`${R.left+ve}px`,top:`${R.top}px`,width:`${R.width}px`,height:`${R.height}px`}:{transform:`translate3d(${R.left+ve}px, ${R.top}px, 0)`,width:`${R.width}px`,height:`${R.height}px`}}):null,P&&R?t.jsx("div",{className:F("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",V&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${R.left+ve}px, 0, 0)`,width:`${R.width}px`},"aria-hidden":!0}):null,e.map(W=>{const H=W.id===s,ie=u&&O&&!H&&!!W.icon,pe=!ie,Se=!!W.icon,Y=u&&O&&H&&!f&&!z,be=W.closable!==!1&&!!r,ue=be&&!!W.icon,Ye=f||z?void 0:O?Y?"flex-none basis-auto":v?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",at=be?je=>{je.button===1&&(je.preventDefault(),je.stopPropagation(),r?.(W.id))}:void 0,ze=be?je=>{je.button===1&&je.preventDefault()}:void 0;return t.jsx(K,{id:W.id,className:Ye,children:t.jsxs("div",{ref:je=>He(W.id,je),onAuxClick:at,onMouseDown:ze,className:F("group flex h-full min-w-0 flex-nowrap items-center",f||z?"shrink-0":O?"w-full":"w-full min-w-0",O?"relative z-10 bg-transparent":H?"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":H,"aria-label":ie?W.title??W.label:void 0,onClick:()=>n(W.id),onPointerDown:B?()=>{le(!0),ke(W.id)}:void 0,onPointerUp:B?()=>ke(null):void 0,onPointerLeave:B?()=>ke(null):void 0,onPointerCancel:B?()=>ke(null):void 0,className:F(O?"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",O&&m?"lowercase":null,O&&(ie?"gap-0":"gap-1.5"),O?z?"shrink-0 whitespace-nowrap px-3 text-center":f?"max-w-56 shrink-0 px-3 text-center":ie?"px-2 !min-w-0 text-center":Y?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":f?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",O?d??(M?v?"h-[38px]":"h-[31px]":"h-7"):null,O?H?"text-foreground":"text-muted-foreground hover:text-foreground":null,O?"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:W.title??W.label,children:O?t.jsxs(t.Fragment,{children:[Se?t.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",ue&&(j?"opacity-0":"group-hover:opacity-0")),children:W.icon}),ue?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},"aria-label":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.label} tab`,children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,pe?t.jsx("span",{className:"animated-tabs__label truncate",children:W.label}):null]}):t.jsxs("span",{className:F("flex min-w-0 flex-nowrap items-center gap-1.5",!f&&"justify-center"),children:[Se?t.jsxs("span",{className:F("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",H?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",ue&&(j?"opacity-0":"group-hover:opacity-0")),children:W.icon}),ue?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},"aria-label":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.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:W.label})]})}),be&&!ue?t.jsx("button",{type:"button",onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},className:F("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",O?"-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",O?H?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":H?"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":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.label} tab`,children:t.jsx(k,{name:"close",className:"h-3 w-3"})}):null]})},W.id)})]})]});return se?t.jsxs(Tn,{sensors:Te,collisionDetection:En,onDragEnd:Ve,modifiers:[Em],children:[t.jsx(Nr,{items:h,strategy:Ad,children:Be}),t.jsx(Ni,{dropAnimation:null})]}):Be},Fm="\x1B",Lm=new RegExp(`${Fm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Om=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Bm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,_m=/Serving HTTP on .*? port (\d{2,5})/i,$m=new Set([".",",",";",":","!","?"]),zm=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=s.slice(0,-1),a=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=o;continue}if($m.has(n)){s=s.slice(0,-1);continue}break}return s},Xo=e=>{let s=zm(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},Um=e=>{if(!e)return null;const s=e.replace(Lm,""),n=s.match(_m);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=s.split(`
40
- `);for(const o of r){if(!Bm.test(o))continue;const a=Array.from(o.matchAll(Om));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Xo(c[1])).port}catch{return!1}});return Xo((l??a[0])[1])}return null},Km=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 o=new AbortController,a=window.setTimeout(()=>o.abort(),s);try{const l=await rs("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},Gm={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Hm=(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 Gm[e]},ea=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},Wm=(e,s)=>e&&(s==="ctrl"?ea(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),ei={cols:80,rows:24},Bp=({visible:e})=>{const{terminal:s,runtime:n}=ci(),{currentTheme:r}=_c(),o=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});o.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=$c(),l=de(E=>E.terminalFontSize),c=de(E=>E.terminalShell),d=de(E=>E.terminalLoginShells.includes(E.terminalShell)),{isMobile:u,isTablet:y,hasTouchOnlyPointer:m}=Vs(),w=u||y,x=(w||m)&&n.platform==="web",v=!0,g=de(E=>E.showTerminalQuickKeysOnDesktop),j=w||g,C=De(E=>E.currentSessionId),N=De(E=>E.newSessionDraft),b=C!==null||N?.open===!0,h=zc()??null,f=qe(E=>h?E.sessions.get(h):void 0),I=qe(E=>E.hasHydrated),M=qe(E=>E.ensureDirectory),T=qe(E=>E.createTab),O=qe(E=>E.setActiveTab),P=qe(E=>E.closeTab),B=qe(E=>E.setTabSessionId),z=qe(E=>E.setTabLifecycle),U=qe(E=>E.setConnecting),ne=qe(E=>E.appendToBuffer),se=qe(E=>E.replaceBuffer),K=qe(E=>E.setTabPreviewUrl),G=ui(E=>E.addDraft),R=de(E=>E.openContextPreview),A=i.useMemo(()=>f?f.activeTabId??f.tabs[0]?.id??null:null,[f,v]),V=i.useMemo(()=>{if(f)return A?f.tabs.find(E=>E.id===A)??f.tabs[0]:f.tabs[0]},[f,A]),le=i.useMemo(()=>(f?.tabs??[]).map(E=>({icon:(()=>{const X=E.iconKey?Li[E.iconKey]??"terminal":"terminal";return t.jsx(k,{name:X,className:"h-4 w-4"})})(),id:E.id,label:E.label,title:E.label,closeLabel:"Close tab"})),[f?.tabs]),$=V?.terminalSessionId??null,ke=V?.lifecycle??"idle",Ie=qe(E=>h&&A?E.getBuffer(h,A).chunks:Sn.chunks),_e=V?.isConnecting??!1,Ge=V?.previewUrl??null,[Fe,ve]=i.useState(null),[Te,me]=i.useState(!1),[He,we]=i.useState(!1),[xe,Ce]=i.useState(null),[Ve,Be]=i.useState(!1),W=i.useRef(null),H=i.useRef(null),ie=i.useRef(A),pe=i.useRef($),Se=i.useRef(h),Y=i.useRef(null),be=i.useRef(null),ue=i.useRef(new Set),Ye=i.useRef(""),at=i.useRef(new Set),ze=i.useRef(0),je=i.useCallback(()=>{Ye.current="",at.current.clear(),ze.current+=1},[]),Ae=i.useCallback(()=>{x||typeof document<"u"&&!document.hasFocus()||Y.current?.focus()},[x]),ot=i.useCallback(()=>{x||Y.current?.focus()},[x]),pt=de(E=>E.activeMainTab)==="terminal",ge=e??pt,[Je,Tt]=i.useState(ge);i.useEffect(()=>{ge&&Tt(!0)},[ge]),i.useEffect(()=>{pe.current=$},[$]),i.useEffect(()=>{!$||!s.updateAppearance||s.updateAppearance($,o.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,$]),i.useEffect(()=>{ie.current=A,je()},[A,je]),i.useEffect(()=>{Se.current=h},[h]),i.useEffect(()=>{!j&&xe!==null&&Ce(null)},[j,xe,Ce]),i.useEffect(()=>{!$&&xe!==null&&Ce(null)},[$,xe,Ce]);const S=i.useCallback(()=>{W.current?.(),W.current=null,H.current=null,we(!1)},[]);i.useEffect(()=>()=>{S(),pe.current=null},[S]);const Z=i.useCallback((E,X,ce)=>{if(!ce)return;const $e=`${Ye.current}${ce}`.replace(/\r\n|\r/g,`
41
- `),he=$e.split(`
42
- `),Ee=$e.endsWith(`
43
- `)?he.join(`
44
- `):he.slice(0,-1).join(`
45
- `);if(Ye.current=$e.endsWith(`
46
- `)?"":(he[he.length-1]??"").slice(-1024),!Ee)return;const lt=Um(Ee);if(!lt||at.current.has(lt))return;const vt=ze.current;at.current.add(lt),Km(lt).then($t=>{if(at.current.delete(lt),!$t||ze.current!==vt)return;const Lt=qe.getState().getDirectoryState(E)?.tabs.find(Ht=>Ht.id===X);!Lt||Lt.previewUrlLocked||Lt.previewUrl===lt||K(E,X,lt,{locked:!1,autoOpened:!1})})},[K]),ae=i.useCallback((E,X,ce)=>{if(H.current===ce)return;S(),H.current=ce;const $e=s.connect(ce,{onEvent:he=>{if(H.current===ce)switch(he.type){case"snapshot":{U(E,X,!1),ve(null),me(!1),we(!1),Ae(),se(E,X,he.data??"",he.sequence??0),Z(E,X,he.data??""),he.status==="exited"&&z(E,X,"exited");break}case"reconnecting":{ve(null),me(!1),we(!0);break}case"data":{he.data&&(ne(E,X,he.data,he.sequence,he.replayData),Z(E,X,he.data));break}case"exit":{const Ee=typeof he.exitCode=="number"?he.exitCode:null,lt=typeof he.signal=="number"?he.signal:null,$t=!!qe.getState().getDirectoryState(E)?.tabs.find(Lt=>Lt.id===X)?.label?.startsWith("Action:");ne(E,X,`\\r\\n[Process exited${Ee!==null?` with code ${Ee}`:""}${lt!==null?` (signal ${lt})`:""}]\\r\\n`),z(E,X,"exited"),U(E,X,!1),ve($t?null:"Terminal session ended"),me(!1),we(!1),S();break}}},onError:(he,Ee)=>{if(H.current===ce){if(!Ee){ve(null),me(!1);return}if(we(!1),he.code==="SESSION_NOT_FOUND"&&!qe.getState().getDirectoryState(E)?.tabs.find(vt=>vt.id===X)?.label?.startsWith("Action:")){ve(null),me(!1),U(E,X,!1),B(E,X,null),z(E,X,"idle"),S();return}ve(`Connection failed: ${he.message}`),me(!0),U(E,X,!1),z(E,X,"exited"),B(E,X,null),S()}}});W.current=()=>{$e.close(),H.current=null}},[ne,se,S,Ae,Z,U,z,B,s]);i.useEffect(()=>{let E=!1;if(!I||!Je)return;if(!h){ve(b?"No working directory available for terminal.":"Select a session to open the terminal."),S();return}return(async()=>{const ce=h;if(!Se.current||Se.current!==ce)return;if(!qe.getState().getDirectoryState(ce)){M(ce);return}const he=qe.getState().getDirectoryState(ce);if(!he||he.tabs.length===0)return;const Ee=he.activeTabId??he.tabs[0]?.id??null;if(!Ee)return;const lt=he.tabs.find(mt=>mt.id===Ee)??he.tabs[0],vt=lt?.terminalSessionId??null,$t=lt?.lifecycle??"idle",Lt=!!lt?.label?.startsWith("Action:"),Ht=qe.getState().getBuffer(ce,Ee),zt=Ht.byteLength>0||Ht.chunks.length>0;if(!vt){if($t==="exited"){U(ce,Ee,!1);return}if(Lt&&zt){U(ce,Ee,!1);return}const mt=`${ce}\0${Ee}`;if(ue.current.has(mt))return;const Ot=be.current??ei;ue.current.add(mt),ve(null),me(!1),we(!1),U(ce,Ee,!0);try{const L=await s.createSession({cwd:ce,sessionId:Ee,cols:Ot.cols,rows:Ot.rows,shell:c,loginShell:d,...o.current}),q=!E&&Se.current===ce&&ie.current===Ee;if(!qe.getState().getDirectoryState(ce)?.tabs.find(re=>re.id===Ee)){try{await s.close(L.sessionId)}catch{}return}if(B(ce,Ee,L.sessionId),!q)return;const te=be.current;te&&(te.cols!==Ot.cols||te.rows!==Ot.rows)&&s.resize({sessionId:L.sessionId,...te}).catch(()=>{});return}catch(L){const q=qe.getState().getDirectoryState(ce)?.tabs.find(ee=>ee.id===Ee);if(!q||q.terminalSessionId||(U(ce,Ee,!1),Se.current!==ce||ie.current!==Ee))return;ve(L instanceof Error?L.message:"Failed to start terminal session"),me(!0),we(!1);return}finally{ue.current.delete(mt)}}!vt||E||(pe.current=vt,ae(ce,Ee,vt))})(),()=>{E=!0,pe.current=null,S()}},[b,h,$,ke,A,Je,v,I,M,U,z,B,ae,S,s,d,c]),i.useEffect(()=>{if(!ge||x)return;if(typeof window>"u"){Ae();return}const E=window.requestAnimationFrame(()=>{Ae()});return()=>{window.cancelAnimationFrame(E)}},[A,Ae,ge,x]);const ye=i.useCallback(async()=>{if(!h||Ve)return;const E=qe.getState().getDirectoryState(h),X=A??E?.activeTabId??E?.tabs[0]?.id??null;if(!X)return;const ce=E?.tabs.find($e=>$e.id===X)?.terminalSessionId??null;if(!(!ce||!s.restartSession)){Be(!0),ve(null),me(!1),we(!1),S(),je();try{const $e=be.current??ei,he=await s.restartSession(ce,{cwd:h,shell:c,loginShell:d,...$e,...o.current});if(qe.getState().getDirectoryState(h)?.tabs.find(lt=>lt.id===X)?.terminalSessionId!==ce||(B(h,X,he.sessionId),z(h,X,"running"),Se.current!==h||ie.current!==X))return;pe.current=he.sessionId,ae(h,X,he.sessionId)}catch($e){if(qe.getState().getDirectoryState(h)?.tabs.find(Ee=>Ee.id===X)?.terminalSessionId!==ce||Se.current!==h||ie.current!==X)return;ve($e instanceof Error?$e.message:"Failed to restart terminal"),me(!1),we(!1),pe.current=ce,ae(h,X,ce)}finally{Be(!1)}}},[A,S,h,v,Ve,je,z,B,ae,s,d,c]),Re=i.useCallback(async()=>{await ye()},[ye]),Ke=i.useCallback(()=>{if(!h)return;const E=T(h);O(h,E),ve(null),me(!1),we(!1),S()},[T,S,h,O]),nt=i.useCallback(()=>{const E=Y.current?.getSelection(),X=C??(N?.open?"draft":null);!E||!X||!V||!h||G({directory:h,sessionKey:X},{source:"terminal",fileLabel:V.label,startLine:E.startLine,endLine:E.endLine,code:E.text,language:V.terminalSessionId??V.id,text:""})},[V,G,C,h,N?.open]),ct=i.useCallback(E=>{h&&(O(h,E),ve(null),me(!1),we(!1),S())},[S,h,O]),Gt=i.useCallback(E=>{if(!h)return;E===A&&S(),ve(null),me(!1),we(!1);const X=qe.getState().getDirectoryState(h)?.tabs.find(ce=>ce.id===E)?.terminalSessionId;(async()=>{X&&await s.close(X),P(h,E)})().catch(ce=>ve(ce instanceof Error?ce.message:"Terminal session ended"))},[A,P,S,h,s]),it=i.useCallback(E=>{if(!E||He)return;let X=E,ce=!1;xe&&E.length>0&&(X=Wm(E,xe),ce=!0);const $e=pe.current;$e&&(s.sendInput($e,X).catch(he=>{He||ve(he instanceof Error?he.message:"Failed to send input")}),ce&&(Ce(null),ot()))},[xe,ot,He,Ce,s]),gt=i.useCallback((E,X)=>{const ce=be.current;if((!ce||ce.cols!==E||ce.rows!==X)&&(be.current={cols:E,rows:X}),!ge)return;const $e=pe.current;$e&&s.resize({sessionId:$e,cols:E,rows:X}).catch(()=>{})},[ge,s]),yt=i.useCallback(E=>{Ce(X=>X===E?null:E),ot()},[ot,Ce]),Ze=i.useCallback(E=>{const X=Hm(E,xe);X&&(it(X),Ce(null),ot())},[xe,ot,it,Ce]),Bt=i.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),_t=i.useCallback(E=>{if(E.repeat)return;const X=E.key;if(!X||X==="Control"||X==="Meta"||X==="Alt"||X==="Shift")return;const ce=X.length===1?X.toLowerCase():X;if(ce in Bt){E.preventDefault(),E.stopPropagation(),Ze(Bt[ce]);return}if(xe!=="ctrl")return;const $e=E.code??"",he=X.length===1&&/[a-zA-Z]/.test(X)?X.toUpperCase():$e.startsWith("Key")&&$e.length===4?$e.slice(3).toUpperCase():null;if(he&&he.length===1&&he>="A"&&he<="Z"){const Ee=ea(he);if(!Ee)return;E.preventDefault(),E.stopPropagation(),it(Ee),Ce(null),ot()}},[xe,ot,Ze,it,Bt,Ce]);i.useEffect(()=>{if(!(!j||!xe||!$))return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[xe,_t,j,$]);const Et=i.useMemo(()=>{const E=Ks[Un].stack;if(typeof window>"u")return(Ks[a]??Ks[Un]).stack;const ce=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ce&&ce.trim().length>0?ce.trim():(Ks[a]??Ks[Un]).stack??E},[a]),xt=i.useMemo(()=>ym(r),[r]),Mt=`${h??"no-dir"}::${A??"no-tab"}`;if(i.useEffect(()=>{if(!ge||x)return;const E=Y.current;if(!E)return;const X=()=>{E.fit()};if(typeof window<"u"){const ce=window.requestAnimationFrame(()=>{X(),Ae()}),$e=[220,400].map(he=>window.setTimeout(X,he));return()=>{window.cancelAnimationFrame(ce),$e.forEach(he=>window.clearTimeout(he))}}X()},[Ae,ge,x,Mt,$]),i.useEffect(()=>{if(!ge||!x)return;let E=null;const X=()=>{E!==null&&window.cancelAnimationFrame(E),E=window.requestAnimationFrame(()=>{E=null,Y.current?.fit()})};return window.addEventListener("oc:keyboard-settled",X),()=>{window.removeEventListener("oc:keyboard-settled",X),E!==null&&window.cancelAnimationFrame(E)}},[ge,Mt,x]),!b)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(!h)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:ye,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const D=!$||_e||Ve||He,fe=Je,Ne=w?"lg":"xs",Le=w?"w-10 p-0":"w-9 p-0",We=E=>{w&&E.preventDefault()},Ct=t.jsxs(t.Fragment,{children:[t.jsx(Me,{type:"button",size:Ne,variant:"outline",onPointerDown:We,onClick:()=>Ze("esc"),disabled:D,children:"Esc"}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("tab"),disabled:D,children:[t.jsx(k,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"chip","aria-pressed":xe==="ctrl",className:w?"px-3":"px-2",onPointerDown:We,onClick:()=>yt("ctrl"),disabled:D,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"chip","aria-pressed":xe==="alt",className:w?"px-3":"px-2",onPointerDown:We,onClick:()=>yt("alt"),disabled:D,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("arrow-up"),disabled:D,children:[t.jsx(k,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("arrow-left"),disabled:D,children:[t.jsx(k,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("arrow-down"),disabled:D,children:[t.jsx(k,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("arrow-right"),disabled:D,children:[t.jsx(k,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Me,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Ze("enter"),disabled:D,children:[t.jsx(k,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:F("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",w?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[f?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:F("min-w-0 flex-1",w?"h-8":"h-7"),children:t.jsx(Rm,{items:le,activeId:A,onSelect:ct,onClose:Gt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:F("shrink-0",w?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ke,title:"New tab",children:t.jsx(k,{name:"add",className:`${w?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ye()},disabled:Ve,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(k,{name:"restart",className:"h-4 w-4"})}),t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:nt,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(k,{name:"attachment-2",className:"h-4 w-4"})}),Ge?t.jsxs(Me,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{h&&R(h,Ge)},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,!w&&j&&v&&f?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Ct}):null,!w&&j&&!f?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Ct}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:xt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:fe?t.jsx(Xi,{ref:E=>{Y.current=E},sessionKey:Mt,chunks:Ie,onInput:it,onResize:gt,theme:xt,fontFamily:Et,fontSize:l,enableTouchScroll:x,autoFocus:ge,isVisible:ge},Mt):null}),!He&&Fe&&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:Fe}),Te&&w&&t.jsx(Me,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Re,disabled:Ve,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),w&&j?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",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Ct})}):null]})},qm=hs(()=>({statusById:new Map})),_p=()=>{vi(),xi()},$p=e=>{De.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),de.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),vi(),qe.getState().clearAll(),us.getState().resetForRuntimeSwitch(),qt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),kt.getState().resetForRuntimeSwitch(),Uc.getState().resetForRuntimeSwitch(),qm.setState({statusById:new Map}),Kc(),Gc(),Rd.getState().reset(),gd.getState().resetForRuntimeSwitch(),di.getState().resetForRuntimeSwitch(e.runtimeKey),Qf.getState().resetForRuntimeSwitch(),At.getState().resetForRuntimeSwitch(e.runtimeKey),xd.getState().resetForRuntimeSwitch(e.runtimeKey),De.getState().restoreForRuntimeSwitch(e.runtimeKey),de.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=de.getState();ur({sessionId:De.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),xi()};export{uu as $,Pp as A,xp as B,Cp as C,ap as D,mu as E,Rp as F,Ir as G,mp as H,hu as I,Dr as J,pp as K,Bu as L,pu as M,Ys as N,lu as O,Op as P,Ai as Q,au as R,Lp as S,Bp as T,iu as U,Js as V,Es as W,du as X,dp as Y,vp as Z,cu as _,Zu as a,yp as a0,jp as a1,Sp as a2,gu as a3,gs as a4,bp as a5,wp as a6,kp as a7,cp as a8,up as a9,fp as aa,hp as ab,Au as ac,gp as ad,Hu as ae,Wu as af,fu as ag,lp as ah,Fp as ai,Tp as aj,$p as b,Ap as c,Mp as d,Ep as e,jo as f,qe as g,vu as h,Ip as i,Li as j,jh as k,Dh as l,kh as m,wu as n,_u as o,$u as p,zu as q,_p as r,Ch as s,Np as t,yn as u,Co as v,Uu as w,Rm as x,Ku as y,Dp as z};