@pi-chamber/web 1.0.0 → 1.0.1

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 (69) hide show
  1. package/README.md +3 -1
  2. package/bin/cli.js +7 -32
  3. package/bin/dev-server.js +185 -0
  4. package/bin/dev-server.test.js +252 -0
  5. package/bin/lib/DOCUMENTATION.md +19 -0
  6. package/bin/lib/cli-startup.js +9 -1
  7. package/bin/lib/cli-startup.test.js +30 -0
  8. package/bin/lib/commands-serve.js +9 -5
  9. package/bin/lib/server-runtime.js +6 -0
  10. package/bin/lib/server-runtime.test.js +313 -0
  11. package/dist/assets/{DiagramView-CbSxUe1D.js → DiagramView-COHSzZ9Z.js} +1 -1
  12. package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BA4LWExp.js} +1 -1
  13. package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
  14. package/dist/assets/{FilesView-DasA5EU2.js → FilesView-CIx6Bq8l.js} +1 -1
  15. package/dist/assets/{GitView-DU3mOECp.js → GitView-3Hgk_pVS.js} +3 -3
  16. package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-CVLGj7jk.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-CWeQW9_O.js} +1 -1
  18. package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-367QPDDL.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
  22. package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
  23. package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-CN0wm-Fv.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-Bkh0DWJn.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-CFToyUp4.js} +1 -1
  27. package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BXBoS1M4.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-BpbB2xiE.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
  30. package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
  31. package/dist/assets/{index-OveFsNBm.js → index-CVZfC79h.js} +1 -1
  32. package/dist/assets/{index-BXX8l7mM.css → index-Ci9OMaKW.css} +1 -1
  33. package/dist/assets/{index-DvNeSFO9.js → index-DyeT2dc_.js} +7 -7
  34. package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-dBQiDlRy.js} +1 -1
  35. package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-DWMzO-Ms.js} +1 -1
  36. package/dist/assets/{main-BsDkATRV.js → main-DkXvFwTR.js} +3 -3
  37. package/dist/assets/{main-C393Ywhx.js → main-DukaBOy3.js} +2 -2
  38. package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BH61OrJ2.js} +1 -1
  39. package/dist/assets/{miniChat-CWEerp3c.js → miniChat-B1uBoxSn.js} +2 -2
  40. package/dist/assets/{mobile-YxV9KcxF.js → mobile-DV_RYy3x.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-CA6co_Lh.js} +2 -2
  42. package/dist/assets/renderMobileApp-CyhFZ_4g.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-CVoKFaRw.js +53 -0
  44. package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-CxbVCK7k.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-HCEusnq7.js} +77 -77
  46. package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-DLA7kskG.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
  50. package/dist/assets/{web-components-B0RFakat.js → web-components-C7g3Hi85.js} +1 -1
  51. package/dist/index.html +4 -4
  52. package/dist/mini-chat.html +3 -3
  53. package/dist/mobile.html +3 -3
  54. package/package.json +8 -3
  55. package/server/index.js +40 -6
  56. package/server/lib/notifications/DOCUMENTATION.md +39 -0
  57. package/server/lib/notifications/delivery-runtime.js +314 -0
  58. package/server/lib/notifications/delivery-runtime.test.js +85 -0
  59. package/server/lib/notifications/pi-notification-watcher.js +154 -0
  60. package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
  61. package/server/lib/notifications/routes.js +74 -0
  62. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
  63. package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
  64. package/server/lib/pi/ui-settings-store.js +3 -2
  65. package/server/lib/server/runtime-requirements.js +193 -0
  66. package/server/lib/server/runtime-requirements.test.js +295 -0
  67. package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
  68. package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
  69. package/dist/assets/runtimeEndpointReset-DHARMv9w.js +0 -53
@@ -0,0 +1,53 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CVZfC79h.js","assets/useAppFontEffects-HCEusnq7.js","assets/index-DyeT2dc_.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-Ci9OMaKW.css","assets/vendor-base-ui-DXSHfszQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CxbVCK7k.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-zF3O85ti.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-BpbB2xiE.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-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.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-DWMzO-Ms.js","assets/isDiffPlainText-dBQiDlRy.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-BAHhqkBZ.js"])))=>i.map(i=>d[i]);
2
+ import{_ as os}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ne,j as t,R as i,b as Xl}from"./vendor-react-B5Z1Mdn3.js";import{aQ as Ds,aR as Zl,a2 as Pt,a3 as ze,a4 as $e,a5 as Mt,B as Me,I as R,a6 as Ge,a7 as Tt,a9 as rt,t as ie,a as ht,f as Ee,_ as _s,ae as dn,aS as yi,ag as $t,ah as Gt,ai as as,aj as Xt,ak as ls,al as Ss,aG as xs,aT as ys,g as Es,aU as or,aV as No,aW as Io,aX as nn,e as Pn,o as wi,af as ps,aY as Ro,a8 as ws,aZ as Cr,a_ as ec,a$ as tc,b0 as sc,b1 as nc,b2 as rc,b3 as kr,b4 as oc,y as Ut,b5 as ic,b6 as ac,b7 as lc,b8 as vi,b9 as cc,ba as dc,bb as Si,bc as ji,bd as Ci,aD as Ar,r as rn,n as qr,ap as uc,az as fc,aC as ki,L as js,d as Qr,ab as Us,ay as Ai,be as qn,bf as Eo,bg as ft,aE as Ni,bh as Ii,au as hc,h as Ri,j as pc,bi as mc,i as gc,bj as Ns,b as Do,c as bc,bk as xc,u as yc,aF as wc,aI as vc,bl as Nr,bm as Sc,bn as jc,aH as Cc,bo as kc,bp as Ac,T as Nc,aa as vs,am as Ei,w as Ic,ac as Rc,bq as Ec,br as Dc,k as Pc,bs as Mc,bt as Di,bu as Tc,bv as Fc,bw as Oc,bx as Lc,by as Bc,bz as _c,bA as Uc,bB as zc,bC as $c,bD as Gc}from"./useAppFontEffects-HCEusnq7.js";import{Z as Po,_ as Kc,R as Ts,$ as Pi,a0 as Mi,a1 as Wc,a2 as Hc,u as Fs,K as Yc,a3 as qc,a4 as Qc,a5 as Vc,a6 as qt,v as Qt,a7 as Jc,a8 as Xc,a9 as Zc,aa as Vr,m as Ft,ab as ed,ac as td,ad as sd,t as le,o as $,ae as nd,f as Je,B as Ae,af as Os,ag as Dt,ah as Mo,ai as Ir,a as Jr,T as Xr,U as Bn,aj as rd,ak as od,al as Ti,F as id,Q as Fi,C as on,am as Rr,h as Er,d as Cn,an as ad,ao as ld,ap as To,aq as Xs,ar as ir,as as Dr,at as _n,au as ms,av as Fo,aw as Pr,ax as Oi,ay as Mr,az as cd,aA as dd,aB as ud,aC as fd,aD as hd,aE as pd,aF as md,z as gd,aG as bd,aH as xd,Y as Li,P as yd,J as wd}from"./index-DyeT2dc_.js";import{c as zs,d as Bi,p as Zr,u as Tr,a as vd}from"./vendor-zustand-GVb4H8HE.js";import{g as is,b as Sd,c as _i,r as jd,d as Ui,s as Mn,e as zi,h as un,i as fn,j as Cd,k as kd,l as Ad,m as Oo,n as Qn,f as Nd,a as Id,S as Rd,t as Ed,o as Dd}from"./SessionUnreadDot-CvIWGgIi.js";import{C as $i,a as Gi,M as Ki,b as Wi,c as Hi,d as Yi,S as qi,D as Pd,e as Md,f as Td,g as Fd,h as Od,i as Ld,j as Bd}from"./vendor-base-ui-DXSHfszQ.js";import{c as Qi,d as Fr,P as _d,D as Vi,e as Ji,f as Ud,b as zd,a as $d,T as Gd,M as Kd}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as Wd}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as Hd,v as Yd,u as qd}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as Qd}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as Vd}from"./permissionStore-iKN1K2_x.js";const Jd="chat";function Xi(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ds.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ds.SETTINGS,n),s}return e.tab!==Jd&&s.set(Ds.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ds.FILE,e.diffFile),s}function Xd(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=Xi(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ds.SESSION)&&s.set(Ds.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 Or(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Zd(e)))try{const n=Xi(e),r=Xd(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const eu=["typescript","javascript","tsx","jsx","json","markdown"],Zi={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Lo=null;const ea=()=>(Lo??=Promise.all([os(()=>import("./index-CVZfC79h.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])),os(()=>import("./workerFactory-tw7cIdmV.js"),[]),os(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,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})),Lo),hn={},Bo=new Set,Lr=new Set;let Tn={light:"pierre-light",dark:"pierre-dark"};const tu=()=>{for(const e of Lr)e()},ta=(e,s)=>{s.setRenderOptions({theme:Tn,lineDiffType:Zi[e].lineDiffType})},Br=e=>{typeof window>"u"||Bo.has(e)||(Bo.add(e),ea().then(s=>{if(hn[e])return;const n=Zi[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:eu,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,ta(e,r),tu()}))},su=e=>(Lr.add(e),()=>Lr.delete(e)),nu=e=>{if(!(Tn.light===e.light&&Tn.dark===e.dark)){Tn=e;for(const s of Object.keys(hn)){const n=hn[s];n&&ta(s,n)}}},Zm=({children:e})=>{const s=Zl(),n=Po(!1),r=Po(!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 Ne.useEffect(()=>{let d=!1;return ea().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),nu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ne.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Br("unified"),Br("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},eg=(e="unified")=>{const s=Ne.useSyncExternalStore(su,()=>hn[e],()=>{});return Ne.useEffect(()=>{Br(e)},[e]),s},ru={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ou={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 sa(e){return e&&ou[e]||"var(--primary)"}const _o=({icon:e,className:s,colorToken:n})=>{const r=ru[e??"branch"]??"user-3";return t.jsx(R,{name:r,className:s,style:{color:sa(n)}})},iu=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Pt,{children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Mt,{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:sa(e?.color)},disabled:a,children:[r?t.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(_o,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(R,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Ge,{sideOffset:8,children:"Git identity"})]}),t.jsx(Tt,{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(rt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(_o,{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(R,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},au=e=>e==="/",Ls=e=>e.replace(/\\/g,"/"),Bs=e=>{if(!e||au(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Ps=e=>e.endsWith("/"),Un=e=>{const s=e.trim();return!s||Ps(s)?s:`${s}/`},eo=e=>e.lastIndexOf("/"),na=e=>{if(Ps(e))return e;const s=eo(e);return s<0?e:e.slice(0,s+1)},ra=e=>{const s=eo(e);return e.slice(s+1)},oa=e=>{const s=Bs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=eo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ia=e=>Ps(e)&&oa(e)!==null,lu=e=>{if(!ia(e))return null;const s=Bs(e.trim());return ra(s)||s},cu=(e,s)=>`${na(e)}${s}/`,gs=e=>{if(!e)return null;const s=Bs(Ls(e.trim()));return s?s.toLowerCase():null},Uo=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},du=(e,s)=>{const n=Bs(Ls(e.trim())),r=Bs(Ls(s.trim()));if(!n)return"";if(!r)return Un(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Un(n)},uu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,_r=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},fu=async()=>Kc(),hu=()=>{const[e,s]=Ne.useState(!1),[n,r]=Ne.useState(!1);Ne.useEffect(()=>{s(Ts()),r(Pi())},[]);const o=Ne.useCallback(async c=>e?await Mi(c):{success:!0,path:c},[e]),a=Ne.useCallback(async c=>e?await Wc():{success:!0},[e]),l=Ne.useCallback(async c=>e?await Hc():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function pu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Fs(re=>re.homeDirectory),{canRequestAccess:o,startAccessing:a}=hu(),l=i.useRef(null),c=i.useRef(new Map),[d,u]=i.useState(""),[f,p]=i.useState("~/"),[b,h]=i.useState([]),[g,m]=i.useState(!1),[v,x]=i.useState(!1),[I,w]=i.useState(null),[A,j]=i.useState(0),[N,C]=i.useState(0),[y,k]=i.useState(!1),[E,M]=i.useState(!1),[B,_]=i.useState("right"),K=i.useRef("~/"),V=d||r;i.useEffect(()=>{if(!e)return;p("~/"),h([]),C(0),k(!1),M(!1),K.current="~/",_("right"),n||requestAnimationFrame(()=>_r(l.current));let re=!1;return(async()=>{const H=await fu();re||(u(H||r||""),n||requestAnimationFrame(()=>_r(l.current)))})(),()=>{re=!0}},[r,e,n]);const L=i.useMemo(()=>na(f),[f]),T=i.useMemo(()=>Ps(f)?"":ra(f),[f]),P=i.useMemo(()=>V?Uo(L,V):"",[L,V]);i.useEffect(()=>{const re=K.current;re!==L&&(_(L.length>=re.length?"right":"left"),K.current=L)},[L]),i.useEffect(()=>{if(!e||!P){h([]),w(null);return}let re=!1;return m(!0),x(!1),w(null),Yc(P).then(oe=>{if(re)return;x(!1),w(null);const H=oe.filter(be=>be.isDirectory).map(be=>({name:be.name,path:Ls(be.path)})).sort((be,Be)=>be.name.localeCompare(Be.name));h(H)}).catch(oe=>{if(!re){h([]);const H=qc(oe)?oe.reason:"unknown";w(H),x(H==="not-found")}}).finally(()=>{re||m(!1)}),()=>{re=!0}},[P,A,e]);const U=i.useMemo(()=>{const re=T.toLowerCase(),oe=E||T.startsWith(".");return b.filter(H=>H.name.toLowerCase().startsWith(re)&&(oe||!H.name.startsWith(".")))},[T,b,E]),se=i.useMemo(()=>lu(f),[f]),W=i.useMemo(()=>oa(f),[f]),G=i.useMemo(()=>{const re=[],oe=gs(P);ia(f)&&se&&W&&re.push({type:"parent",value:"browse:up",name:se,path:W,alreadyAdded:!!(oe&&s.has(oe))});for(const H of U){const be=gs(H.path);re.push({type:"directory",value:`browse:${H.path}`,name:H.name,path:H.path,alreadyAdded:!!(be&&s.has(be))})}return re},[s,P,se,U,W,f]);i.useEffect(()=>{C(0)},[f,G.length]);const Ie=i.useMemo(()=>V?Bs(Uo(f,V)):"",[V,f]),ee=gs(Ie),Te=!!(ee&&s.has(ee)),_e=i.useMemo(()=>T?U.find(re=>re.name===T)??null:null,[T,U]),q=!!(Ie&&!Te&&(I===null||I==="not-found")&&(Ps(f)&&v||!Ps(f)&&T.trim().length>0&&_e===null)),F=G[N]??null,z=!!F,Q=i.useCallback(re=>{p(Un(re))},[]),te=i.useCallback(re=>{p(cu(f,re.name))},[f]),Ce=i.useCallback(re=>{if(re){if(re.type==="parent"){Q(re.path);return}te(re)}},[Q,te]),ge=i.useCallback(async re=>{const oe=await a(re);if(!oe.success)return ie.error("Failed to open directory",{description:oe.error||"Desktop could not grant file access."}),!1;const H=V?du(re,V):Un(Ls(re));return Q(H),!0},[Q,V,a]),xe=i.useCallback(async()=>{if(!y){k(!0);try{if(Pi()){const oe=await Mi(Ie);if(!oe.success||!oe.path){oe.error&&oe.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:oe.error});return}await ge(oe.path);return}const re=await Qc(Ie);if(re.status==="cancelled")return;if(re.status!=="picked"){ie.error("Couldn't open a folder picker",{description:re.error});return}await ge(re.path)}catch(re){ie.error("Failed to select directory",{description:re instanceof Error?re.message:"Unknown error occurred."})}finally{k(!1)}}},[ge,y,Ie]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:g,isBrowseDirectoryMissing:v,browseErrorReason:I,browseReloadKey:A,setBrowseReloadKey:j,highlightedIndex:N,setHighlightedIndex:C,isPickingLocation:y,showHidden:E,setShowHidden:M,folderEnterFrom:B,explorerRootDirectory:V,browseDirectoryDisplayPath:L,browseDirectoryAbsolutePath:P,browseFilterQuery:T,filteredEntries:U,rows:G,targetPath:Ie,isAlreadyAdded:Te,shouldCreateTarget:q,highlightedRow:F,hasHighlightedBrowseItem:z,canRequestAccess:o,browseToDisplayPath:Q,browseToEntry:te,executeRow:Ce,applyPickedLocation:ge,handleBrowseLocation:xe}}const hs=zs()(Bi(Zr((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=Qt()?.git,o=r?await r.getGitIdentities():await sd();return e({profiles:o,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=Qt()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await td();if(r&&r.userName&&r.userEmail){const o={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:o})}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=Qt()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await ed();return e({discoveredCredentials:r}),!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=Qt()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Ft("/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 Vr({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"};qt("saving");const o=Qt()?.git;return o?await o.createGitIdentity(r):await Zc(r),qt("saved"),await s().loadProfiles(),!0}catch(r){return qt("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(c=>c.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};qt("saving");const l=Qt()?.git;return l?await l.updateGitIdentity(n,a):await Xc(n,a),qt("saved"),await s().loadProfiles(),!0}catch(o){return qt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{qt("saving");const r=Qt()?.git;return r?await r.deleteGitIdentity(n):await Jc(n),qt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return qt("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:Vc(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=hs);function mu({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ht(W=>W.addProject),p=le(W=>W.setActiveMainTab),b=le(W=>W.setSessionSwitcherOpen),h=Ee(W=>W.openNewSessionDraft),g=hs(W=>W.profiles),m=hs(W=>W.globalIdentity),v=hs(W=>W.defaultGitIdentityId),x=hs(W=>W.loadProfiles),I=hs(W=>W.loadGlobalIdentity),w=hs(W=>W.loadDefaultGitIdentityId),[A,j]=i.useState(!1),[N,C]=i.useState(!1),[y,k]=i.useState(""),[E,M]=i.useState(null);i.useEffect(()=>{e&&(j(!1),C(!1),k(""),M(null))},[e]),i.useEffect(()=>{e&&(x(),I(),w())},[w,x,I,e]);const B=i.useMemo(()=>{const W=new Map;m&&W.set(m.id,m);for(const G of g)W.set(G.id,G);return Array.from(W.values())},[g,m]);i.useEffect(()=>{if(!e||!N||E!==null)return;const W=typeof v=="string"?v.trim():"";if(W&&B.some(Ie=>Ie.id===W)){M(W);return}const G=B.find(Ie=>Ie.authType==="ssh"||Ie.sshKey);G&&M(G.id)},[B,v,N,e,E]);const _=i.useMemo(()=>B.find(W=>W.id===E)??null,[B,E]),K=i.useCallback((W,G)=>{p("chat"),n&&b(!1),h({selectedProjectId:W,directoryOverride:G}),s()},[n,s,h,p,b]),V=i.useCallback(async W=>{if(!W||A)return;const G=gs(W);if(G&&r.has(G))return;let Ie=W;j(!0);try{const ee=!N&&a&&gs(W)===gs(o);if(N){const _e=y.trim();if(!_e){ie.error("Enter a repository URL before cloning.");return}const q=await Ft("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:_e,destinationPath:W,gitIdentityId:_?.id??null})});if(!q.ok)throw new Error("Failed to clone git repository");Ie=(await q.json()).path||W}else if(ee&&!(await Ft("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:W})})).ok)throw new Error("Failed to select directory");const Te=f(Ie);if(!Te){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}K(Te.id,Te.path)}catch(ee){ie.error("Failed to select directory",{description:ee instanceof Error?ee.message:"Unknown error occurred."})}finally{j(!1)}},[f,r,c,y,N,A,K,_?.id,a,o]),L=!A&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,T=L&&y.trim().length>0,P=N?T:L,U=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:A,isCloneMode:N,setIsCloneMode:C,cloneRemoteUrl:y,setCloneRemoteUrl:k,selectedGitIdentityId:E,setSelectedGitIdentityId:M,availableGitIdentities:B,selectedGitIdentity:_,canSubmit:P,submitActionLabel:d?"Already added":N?A?"Cloning...":"Clone & add":A?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:U,finalizeSelection:V}}const gu=({open:e,onOpenChange:s})=>{const n=ht(H=>H.projects),{isMobile:r,isTablet:o}=_s(),a=r||o,l=i.useMemo(()=>new Set(n.map(H=>gs(H.path)).filter(H=>!!H)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:d,rowRefs:u,query:f,setQuery:p,isLoading:b,browseErrorReason:h,setBrowseReloadKey:g,highlightedIndex:m,setHighlightedIndex:v,isPickingLocation:x,showHidden:I,setShowHidden:w,folderEnterFrom:A,browseDirectoryDisplayPath:j,browseDirectoryAbsolutePath:N,rows:C,targetPath:y,isAlreadyAdded:k,shouldCreateTarget:E,highlightedRow:M,hasHighlightedBrowseItem:B,canRequestAccess:_,executeRow:K,handleBrowseLocation:V}=pu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:L,isCloneMode:T,setIsCloneMode:P,cloneRemoteUrl:U,setCloneRemoteUrl:se,setSelectedGitIdentityId:W,availableGitIdentities:G,selectedGitIdentity:Ie,canSubmit:ee,submitActionLabel:Te,submitModifierLabel:_e,finalizeSelection:q}=mu({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:y,shouldCreateTarget:E,browseErrorReason:h,browseDirectoryAbsolutePath:N,isAlreadyAdded:k,isPickingLocation:x});i.useLayoutEffect(()=>{const H=d.current;H&&(H.scrollLeft=H.scrollWidth)},[d,f]),i.useLayoutEffect(()=>{!e||a||_r(d.current)},[d,e,a]),i.useLayoutEffect(()=>{const H=C[m];H&&u.current.get(H.value)?.scrollIntoView({block:"nearest"})},[m,u,C]);const F=i.useCallback(H=>{if(H.key==="ArrowDown"){H.preventDefault(),v(be=>Math.min(C.length-1,be+1));return}if(H.key==="ArrowUp"){H.preventDefault(),v(be=>Math.max(0,be-1));return}if(H.key==="Enter"){if(H.preventDefault(),uu(H)){q(y);return}B&&K(M);return}H.key==="Backspace"&&f===""&&(H.preventDefault(),c())},[K,q,c,B,M,f,C.length,v,y]),z=t.jsxs("button",{type:"button",onClick:()=>w(H=>!H),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:[I?t.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Q=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(R,{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(dn,{ref:d,value:f,onChange:H=>p(Ls(H.target.value)),onKeyDown:F,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:L||x,onMouseDown:H=>H.preventDefault(),onClick:()=>{V()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(R,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),te=C.some(H=>H.type==="parent"),Ce=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":T,disabled:L||x,onClick:()=>P(H=>!H),children:[t.jsx(R,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),T?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(dn,{value:U,onChange:H=>se(H.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(iu,{activeProfile:Ie,identities:G,onSelect:H=>W(H.id),isApplying:L,iconOnly:!0})]})]}):null,k?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:$("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",A==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):h&&h!=="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:h==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[h==="os-permission"&&_?t.jsx(Me,{size:"xs",onClick:()=>{V()},disabled:x,children:"Grant access"}):null,t.jsx(Me,{variant:"outline",size:"xs",onClick:()=>g(H=>H+1),children:"Try again"})]})]}):C.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:C.map((H,be)=>{const Be=be===m,O=H.type==="directory"&&te;return t.jsxs("button",{ref:Z=>{Z?u.current.set(H.value,Z):u.current.delete(H.value)},type:"button","aria-label":H.type==="parent"?H.alreadyAdded?`Go back from ${H.name}, already added`:`Go back from ${H.name}`:H.alreadyAdded?`Open ${H.name}, already added`:`Open ${H.name}`,onMouseEnter:()=>v(be),onMouseDown:Z=>Z.preventDefault(),onClick:()=>K(H),className:$("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Be&&"bg-interactive-selection text-interactive-selection-foreground",!Be&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:$("flex min-w-0 flex-1 items-center gap-2",O&&"pl-4"),children:[H.type==="parent"?t.jsx(R,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(R,{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:H.name})]}),H.alreadyAdded?t.jsx("span",{className:$("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Be?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,H.type==="parent"?t.jsx(R,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},H.value)})})},j)]})}),ge=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Q,Ce]}),xe=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(R,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(R,{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(R,{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:_e}),t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),re=t.jsx(Me,{size:r?"xs":"default",onClick:()=>{q(y)},disabled:!ee,className:$(r&&"w-full flex-1"),children:Te}),oe=()=>t.jsxs(t.Fragment,{children:[r?null:xe,t.jsx("div",{className:$("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:re})]});return r?t.jsx(yi,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:oe()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:z}),ge]})}):t.jsx($t,{open:e,onOpenChange:s,children:t.jsxs(Gt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(as,{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(Xt,{children:"Add folder"}),t.jsx(ls,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),z]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ge}),t.jsx(Ss,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:oe()})]})})},kn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,tg=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=Ee(N=>N.deleteSession),c=Ee(N=>N.deleteSessions),d=le(N=>N.showDeletionDialog),u=le(N=>N.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=_s(),h=f||p||b;i.useEffect(()=>nd(()=>{s(!1)}),[]);const g=i.useCallback(N=>{r({sessions:N.sessions,dateLabel:N.dateLabel})},[]),m=i.useCallback(()=>{r(null),a(!1)},[]),v=i.useCallback(async N=>{if(N.sessions.length===0)return;if(N.sessions.length===1){const E=N.sessions[0];await l(E.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const C=N.sessions.map(E=>E.id),{deletedIds:y,failedIds:k}=await c(C);if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:N.dateLabel?`Removed all sessions from ${N.dateLabel}.`:void 0;ie.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:kn(E)})}k.length>0&&ie.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:kn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>xs.onDeleteRequest(N=>{if(!d){v(N);return}g(N)}),[g,d,v]),i.useEffect(()=>xs.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const N=n.sessions[0];if(!await l(N.id)){ie.error("Failed to delete session"),a(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const N=n.sessions.map(E=>E.id),C=await c(N),y=C.deletedIds,k=C.failedIds;if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:kn(E),action:{label:"OK",onClick:()=>{}}})}if(k.length>0&&(ie.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:kn("Please try again in a moment.")}),y.length===0)){a(!1);return}}m()}finally{a(!1)}}},[n,l,c,m]),I=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",w=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(N=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:is(N)})},N.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(R,{name:"checkbox-blank",className:"size-4"}):t.jsx(R,{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:m,disabled:o,children:"Cancel"}),t.jsx(Me,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),j=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[h?t.jsx(yi,{open:!!n,onClose:()=>{o||m()},title:j,footer:t.jsx("div",{className:"flex justify-end gap-2",children:A}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),w]})}):t.jsx($t,{open:!!n,onOpenChange:N=>{if(!N){if(o)return;m()}},children:t.jsxs(Gt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:j}),I&&t.jsx(ls,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),t.jsx(Ss,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),t.jsx(gu,{open:e,onOpenChange:s})]})},sg=()=>{const e=ys(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(ys.getState().markNotificationSent(s.key),ie.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},bu=[{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:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","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:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{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:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],xu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function yu(e){const s=e.trim().toLowerCase();return bu.find(n=>n.slug===s)??null}function wu(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=xu[s];if(n)return n;const r=yu(s);return r?r.slug:"home"}function ng(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function rg(){const e=i.useRef(!1),s=i.useRef(!1),n=Ee(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),a=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=Ee.getState().currentSessionId,b=Es().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const h=Ee.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,h)}}if(f.settingsPath){a(wu(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,o,a,l]),d=i.useCallback(()=>{const f=Ee.getState(),p=Es().getState(),b=le.getState();return{sessionId:or({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),u=i.useCallback((f={})=>{if(s.current)return;const p=d();Or(p,f)},[d]);i.useEffect(()=>{if(e.current||(e.current=!0,!No()))return;const f=Io();(async()=>(await c(f),Or({...d(),sessionId:f.sessionId??or({currentSessionId:Ee.getState().currentSessionId,piSelectedSessionId:Es().getState().selectedSessionId,draft:Ee.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),i.useEffect(()=>{const f=()=>{const v=Ee.getState(),x=Es().getState();return or({currentSessionId:v.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:v.newSessionDraft})};let p=f(),b=Ee.getState().newSessionDraft?.open===!0;const h=()=>{const v=Ee.getState(),x=f(),I=v.newSessionDraft?.open===!0;x===p&&I===b||s.current||(p=x,b=I,u({replace:!0}))},g=Ee.subscribe(()=>{h()}),m=Es().subscribe(()=>{h()});return()=>{g(),m()}},[u]),i.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,h=le.getState().pendingDiffFile;return le.subscribe(m=>{if(s.current)return;const v=m.activeMainTab!==f,x=m.isSettingsDialogOpen!==p,I=m.settingsPage!==b,w=m.pendingDiffFile!==h&&m.activeMainTab==="diff";f=m.activeMainTab,p=m.isSettingsDialogOpen,b=m.settingsPage,h=m.pendingDiffFile,(v||x||I||w)&&u()})},[u]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Io();if(No())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function vu(e=!0){const s=Pn(r=>r.checkForUpdates),n=i.useRef(s);i.useEffect(()=>{n.current=s},[s]),i.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=p=>{const b=Math.round(p*1e3);return Math.max(a,Math.min(l,b))},f=p=>{c||(d=window.setTimeout(async()=>{const b=await n.current(),h=typeof b=="number"&&Number.isFinite(b)?u(b):o;f(h)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function og(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return vu(e),null}const zo=12,Su=[{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"}],ju=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=Su,onComplete:a})=>{const l=Ne.useRef(!1);Ne.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ne.useMemo(()=>Array.from({length:zo},(d,u)=>{const f=Math.PI*2*u/zo;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:$("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((f,p)=>{const b=f.x*d.radius,h=f.y*d.radius,g={"--translate-x":`${b}px`,"--translate-y":`${h}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${d.id}-${p}-${s}`)})},`${d.id}-${s}`)})}):null},Cu=({durationMs:e=3400}={})=>{const[s,n]=Ne.useState({isActive:!1,cycle:0}),r=Ne.useRef(null),o=Ne.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ne.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ne.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 Ne.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},aa=i.createContext(void 0),ig=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Cu(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(aa.Provider,{value:a,children:[e,t.jsx(ju,{isActive:s,burstKey:n})]})},ku={triggerFireworks:()=>{},dismissFireworks:()=>{}},ag=()=>i.useContext(aa)??ku,zn=2e3,la=600*1e3;async function Au(){try{const e=await Ft("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const s=await e.json().catch(()=>({}));return{success:!0,autoRestart:s.autoRestart!==!1,jobId:typeof s.jobId=="string"?s.jobId:void 0,channel:s.channel==="rc"?"rc":s.channel==="stable"?"stable":void 0,targetVersion:typeof s.targetVersion=="string"?s.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Nu(e,s=Math.ceil(la/zn),n=zn,r=Je()){for(let o=0;o<s;o++){if(Je()!==r)return{applied:!1,stale:!0};try{const a=await Ft("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Je()!==r)return{applied:!1,stale:!0};if(a.ok){const l=await a.json().catch(()=>null);if(Je()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Je()!==r)return{applied:!1,stale:!0}}await new Promise(a=>setTimeout(a,n))}return{applied:!1}}async function Iu(e,s,n=Math.ceil(la/zn),r=zn,o=Je()){for(let a=0;a<n;a++){if(Je()!==o)return{applied:!1,stale:!0};try{const l=await Ft(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Je()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Je()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?s("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&s("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Je()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};s("reconnecting")}else s("reconnecting")}}catch{if(Je()!==o)return{applied:!1,stale:!0};s("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const $o="https://github.com/RyderAsKing/PiChamber/releases";function Ru(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 Eu(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Go(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Du(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 Pu(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 ca=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Ne.useState(null),[b,h]=Ne.useState("idle"),[g,m]=Ne.useState(null),[v,x]=Ne.useState(null),[I,w]=Ne.useState({}),A=n?.version?n.releaseUrl||`${$o}/tag/v${n.version}`:$o,j=n?.downloadUrl||A,N=a?.total?Math.round(a.downloaded/a.total*100):0,C=u==="web",y=u==="mobile",k=n?.updateCommand||"pichamber update",E=I.version||n?.version,M=I.channel||n?.channel;Ne.useEffect(()=>{e||(h("idle"),m(null),x(null),w({}))},[e]);const B=async(P=k)=>{(await ws(P)).ok&&(p(P),setTimeout(()=>p(null),2e3))},_=Ne.useCallback(async P=>{await wi(P)},[]),K=Ne.useCallback(async()=>{const P=Je();h("updating"),m(null),x(null),w({});const U=await Au();if(Je()!==P)return;if(!U.success){h("error"),m(U.error||"Update failed"),x(U.commands??null);return}if(w({version:U.targetVersion,channel:U.channel}),U.jobId){const W=await Iu(U.jobId,G=>{Je()===P&&h(G)},void 0,void 0,P);if(W.stale||Je()!==P)return;if(W.applied){window.location.reload();return}h("error"),m(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}h(U.autoRestart?"restarting":"reconnecting");const se=await Nu(n?.currentVersion,void 0,void 0,P);if(!(se.stale||Je()!==P)){if(se.applied){window.location.reload();return}h("error"),m(se.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),V=Ne.useCallback(()=>{_(j)},[_,j]),L=b!=="idle"&&b!=="error",T=Ne.useMemo(()=>{if(!n?.body)return null;const P=n.body.trim();if(!P)return null;const U=Pu(P);return U.length===0?{kind:"raw",title:"What's new",content:Go(P)}:{kind:"sections",title:"What's new",sections:[...U].sort((W,G)=>Du(W.version,G.version)).map(W=>({version:W.version,dateLabel:Ru(W.date),content:Go(Eu(W.raw)||P)}))}},[n?.body]);return t.jsx($t,{open:e,onOpenChange:L?void 0:s,children:t.jsxs(Gt,{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(Xt,{className:"flex items-center gap-2.5",children:[t.jsx(R,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||E)&&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&&E&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),E&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:E})]}),C&&M&&t.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:M==="rc"?"RC subscription":"Stable subscription"})]}),t.jsxs("div",{className:"space-y-2",children:[C&&L&&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(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="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."})]}),T&&!L&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ps,{className:"max-h-[400px] p-0",fillContainer:!1,children:T.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:P=>{const se=P.target.closest("a");se&&se.href&&(P.preventDefault(),P.stopPropagation(),_(se.href))},children:t.jsx(Ro,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(P=>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",P.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:P.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 W=U.target.closest("a");W&&W.href&&(U.preventDefault(),U.stopPropagation(),_(W.href))},children:t.jsx(Ro,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})})]},P.version))})})}),(l||g)&&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||g})}),C&&b==="error"&&(v??[k]).length>0&&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(R,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:v?"Run these commands:":"Or update via terminal:"})]}),(v??[k]).map(P=>t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:P}),t.jsx(Me,{variant:"ghost",size:"icon",onClick:()=>{B(P)},className:f===P?"text-[var(--status-success)]":void 0,title:f===P?"Copied!":"Copy command","aria-label":f===P?"Copied!":"Copy command",children:f===P?t.jsx(R,{name:"check",className:"h-4 w-4"}):t.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},P))]}),!C&&!y&&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}%`}})})]})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:A,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(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!C&&!y&&!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(R,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!C&&!y&&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(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!C&&!y&&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(R,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),y&&t.jsxs(Me,{onClick:V,size:"default",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),C&&!L&&t.jsxs("button",{onClick:K,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(R,{name:"download",className:"h-4 w-4"}),"Update Now"]}),C&&L&&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(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Mu=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:$("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:$("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({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(ze,{open:r,onOpenChange:o,children:[t.jsx($e,{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:$("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(R,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{sideOffset:8,className:$("max-w-sm",n),children:e})]})},lg="w-full min-w-40 max-w-48",cg="settings",Tu="w-full min-w-40 max-w-48",dg="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Fu="w-full max-w-[24rem]",ug="min-w-0 flex-1",fg="flex w-full min-w-0 items-center gap-2",hg="typography-meta shrink-0 text-muted-foreground tabular-nums",da="space-y-3.5",Ou="space-y-1.5",pg="typography-settings-page-title text-muted-foreground",Lu="typography-settings-section-title text-foreground",ua="typography-settings-group-title text-foreground",to="typography-settings-field-label text-foreground",Bu="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",mg="typography-meta font-medium text-foreground",gg="typography-settings-section-title text-foreground",_u=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:$("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Lu,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Bu,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:$(d),children:a})]})},bg=({children:e,className:s})=>t.jsx("div",{className:$("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Uu=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:$(ua,s),children:e}),xg=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:$("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(Uu,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:$(a),children:r})]}),an=({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:mn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:$("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:to,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:$("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},yg=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>t.jsxs("div",{"data-settings-item":o,className:$("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",l),children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:to,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:$(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:$("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),wg=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:$("pt-4",s),children:e}),zu=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:$("group flex cursor-pointer gap-2 py-0.5",p?"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:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[t.jsx(Cr,{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:to,children:n}),d,u!=null?t.jsx(pn,{children:u}):null]}),p?t.jsx("span",{className:mn,children:r}):null]})]})},vg=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:$("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(Mu,{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:$("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Sg=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:$(Ou,n),children:s});function jg({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:$("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))})}const Ur="pichamber:server-update-channel-changed",Cg=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Ur))},$u=e=>typeof window>"u"?()=>{}:(window.addEventListener(Ur,e),()=>window.removeEventListener(Ur,e));class Gu 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(ec,{className:"w-full max-w-md",children:[t.jsx(tc,{className:"text-center",children:t.jsxs(sc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(nc,{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(R,{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 Ku(e){return t.jsx(Gu,{...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 kg=({active:e=!0})=>{const s=Ee(n=>n.currentSessionId);return t.jsx(Ku,{sessionId:s||void 0,children:t.jsx(rc,{active:e},s??"no-session")})};function Wu({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 fa=Ne.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:p,...b},h)=>{const g=Ne.useRef(null),m=Ne.useRef(null),[v,x]=Ne.useState(null),I=c??v,w=Ne.useCallback(j=>{const N=g.current;if(!N)return;m.current={startY:j.clientY,startHeight:N.getBoundingClientRect().height};const C=j.currentTarget;C.setPointerCapture(j.pointerId);const y=E=>{const M=m.current;if(!M)return;const B=M.startHeight+(E.clientY-M.startY),_=Math.max(82,B);d?d(_):x(_)},k=()=>{m.current=null,C.removeEventListener("pointermove",y),C.removeEventListener("pointerup",k),C.removeEventListener("pointercancel",k)};C.addEventListener("pointermove",y),C.addEventListener("pointerup",k),C.addEventListener("pointercancel",k),j.preventDefault()},[d]),A=Ne.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const C=g.current?.querySelector("textarea");C&&document.activeElement!==C&&(j.preventDefault(),C.focus())},[]);return f?t.jsx(ps,{as:"textarea",ref:h,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:$("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,...b}):t.jsx("div",{ref:g,onPointerDown:A,style:I!==null?{height:`${I}px`}:void 0,className:$("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:h,className:$("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,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(Wu,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});fa.displayName="Textarea";const ha=[{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"}],ln=Object.fromEntries(ha.map(e=>[e.key,e.Icon])),zr="pichamber:project-actions-updated",pa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},Vt=(e,s)=>`${pa(e)}::${s}`,ma=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(_u,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),$r=e=>e.name.trim().length>0&&e.command.trim().length>0,Hu=e=>e.name.trim().length===0&&e.command.trim().length===0,Yu=e=>!$r(e)&&!Hu(e),qu=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Qu=450,Vu=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Ju=()=>({id:Vu(),name:"",command:"",icon:"play"}),Xu=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,d]=i.useState(new Set),u=i.useRef(!1);i.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const I=await kr(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),d(new Set(I.actions.map(w=>w.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>qu(s,c),[s,c]),p=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&p!==a,h=i.useCallback(async x=>await oc(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),d(new Set(x.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zr,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||u.current)return;const x=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await h(f.actions)}finally{u.current=!1}})())},Qu);return()=>{window.clearTimeout(x)}},[b,r,h,f.actions]);const g=i.useCallback(()=>{const x=Ju();n(I=>[...I,x])},[]),m=i.useCallback(x=>{n(I=>I.filter(w=>w.id!==x))},[]),v=i.useCallback((x,I)=>{n(w=>w.map(A=>A.id===x?I(A):A))},[]);return t.jsx(ma,{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:g,children:[t.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:$("space-y-6",Fu),children:s.map((x,I)=>{const w=x.icon||"play",A=ln[w]||"play",j=x.name.trim()||`Action ${I+1}`,N=Yu(x);return t.jsxs("div",{className:da,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:ua,children:j}),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:()=>m(x.id),"aria-label":`Delete ${j}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(an,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Pt,{children:[t.jsx(Mt,{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(R,{name:A,className:"h-4 w-4"})})}),t.jsx(Tt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:ha.map(C=>{const y=C.Icon,k=(x.icon||"play")===C.key;return t.jsx("button",{type:"button",onClick:()=>v(x.id,E=>({...E,icon:C.key})),className:$("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",k&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${C.label}`,children:t.jsx(R,{name:y,className:"h-4 w-4"})},C.key)})})})]}),t.jsx(dn,{value:x.name,onChange:C=>v(x.id,y=>({...y,name:C.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(an,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(fa,{value:x.command,onChange:C=>v(x.id,y=>({...y,command:C.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),N?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(zu,{checked:x.autoOpenUrl===!0,onChange:C=>v(x.id,y=>({...y,...C?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl: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 ${j}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(an,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(dn,{value:x.openUrl||"",onChange:C=>v(x.id,y=>({...y,openUrl:C.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},Zu={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},ef=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Ut(y=>y.providers),d=Ut(y=>y.modelsMetadata),u=le(y=>y.hiddenModels),f=le(y=>y.isFavoriteModel),p=le(y=>y.toggleFavoriteModel),b=le(y=>y.reorderFavoriteModel),{favoriteModelsList:h,recentModelsList:g}=ic(),[m,v]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{m||I("")},[m]);const w=e?c.find(y=>y.id===e.providerId):void 0,A=e&&w?(Array.isArray(w.models)?w.models:[]).find(y=>y.id===e.modelId):void 0,j=e?ac(A,e.modelId):s,N=i.useMemo(()=>e?u.filter(y=>!(y.providerID===e.providerId&&y.modelID===e.modelId)):u,[u,e]),C=i.useCallback(y=>{l({providerId:y.providerID,modelId:y.modelID}),v(!1)},[l]);return t.jsxs(Pt,{modal:!1,open:m,onOpenChange:y=>{r||v(y)},children:[t.jsx(Mt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:$(vi({size:"default"}),Tu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(lc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:$("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),t.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Tt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(cc,{providers:c,favoriteModels:h,recentModels:g,modelsMetadata:d,searchQuery:x,onSearchQueryChange:I,onSelect:C,labels:{...Zu,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:N,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),v(!1)},disabled:r,autoFocus:!0,onEscape:()=>v(!1),isFavorite:y=>f(y.providerID,y.modelID),onToggleFavorite:y=>p(y.providerID,y.modelID),onReorderFavorite:(y,k)=>b(y.providerID,y.modelID,k.providerID,k.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",tf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Ut(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(ma,{title:"Project",divider:!1,children:t.jsxs("div",{className:da,children:[t.jsx(an,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(dn,{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(an,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(ef,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},sf=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(()=>dc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,f)=>{o(u&&f?`${u}/${f}`: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}},nf=450,rf=(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{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},nf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},of=({project:e,onIdentitySave:s})=>{const n=sf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return rf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(tf,{form:n}),t.jsx(Xu,{projectRef:r})]})};function so({...e}){return t.jsx($i,{...e})}function no({...e}){return t.jsx(Gi,{...e})}function ro({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(Ki,{children:t.jsx(Wi,{className:$("app-region-no-drag z-50",s),children:t.jsx(Hi,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:$(Si,e),...o,children:n})})})}function Ms({className:e,...s}){return t.jsx(Yi,{className:$(ji,e),...s})}function ga({className:e,...s}){return t.jsx(qi,{className:$(Ci,e),...s})}const An=100;function Ag(){const e=le(y=>y.isArchivePageOpen),s=le(y=>y.setArchivePageOpen),n=le(y=>y.setActiveMainTab),r=Ee(y=>y.setCurrentSession),o=Ee(y=>y.unarchiveSession),a=Fs(y=>y.homeDirectory),l=Ar({archived:!0}),[c,d]=i.useState(""),[u,f]=i.useState(null),[p,b]=i.useState(An),h=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((y,k)=>(k.time?.archived??0)-(y.time?.archived??0)):[],[l,e]),m=i.useMemo(()=>{const y=new Map;for(const k of g){const E=Ae(rn(k))??"",M=y.get(E);if(M){M.sessions.push(k);continue}y.set(E,{directory:E,label:E?Os(E,a)||E:"other projects",sessions:[k]})}return[...y.values()].sort((k,E)=>E.sessions.length-k.sessions.length)},[a,g]),v=i.useMemo(()=>h?g.filter(y=>(y.title??"").toLowerCase().includes(h)):u===null?g:m.find(y=>y.directory===u)?.sessions??[],[m,h,u,g]),x=v.slice(0,p),I=v.length-x.length,w=l.length,A=i.useCallback(y=>{f(y),b(An)},[]),j=i.useCallback(y=>{const k=Ae(rn(y));r(y.id,k??void 0),n("chat"),s(!1)},[n,r,s]),N=i.useCallback(y=>{o(y.id).then(k=>{k?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const C=(y,k,E,M,B,_,K)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:B,title:_,className:$("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",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",M?"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:k}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),K?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>xs.requestDelete({sessions:K,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 ${k}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},y);return t.jsx(Pd,{open:e,onOpenChange:s,children:t.jsxs(Md,{children:[t.jsx(Td,{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(Fd,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Od,{className:"sr-only",children:"Archived sessions"}),t.jsx(Ld,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Bd,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(R,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[C("__all__","All directories",w,u===null,()=>A(null)),m.map(y=>C(y.directory||"__none__",y.label,y.sessions.length,u===y.directory,()=>A(y.directory),y.directory||void 0,y.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(R,{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:y=>{d(y.target.value),b(An)},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:v.length===1?`${v.length} archived session`:`${v.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:[x.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:h?"No matching archived sessions":"No archived sessions"})}):x.map(y=>{const k=Ae(rn(y))??"",E=k?Os(k,a)||k: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:()=>j(y),role:"button",tabIndex:0,onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),j(y))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:is(y)}),h&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:k,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Sd(y.time?.archived??y.time?.updated??y.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),N(y)},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 ${is(y)}`,children:t.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),xs.requestDelete({sessions:[y],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 ${is(y)}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},y.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>b(y=>y+An),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 af=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const s=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=s+n+r;if(o<=0)return{percent:0,hasInput:!1};const a=Math.max(0,n);return{percent:Math.min(100,Math.max(0,a/o*100)),hasInput:!0}},lf=e=>{if(!e||typeof e!="object")return 0;const s=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return s+n+r},zt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,cf=e=>{if(!e||typeof e!="object")return null;const s=zt(e.input),n=zt(e.output),r=zt(e.cacheRead),o=zt(e.cacheWrite);return{input:s,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:s+n+r+o}},Ko=e=>{const s=cf(e.info.usage);if(s)return s;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:zt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,a=zt(o.input),l=zt(o.output),c=zt(o.reasoning),d=zt(o.cache?.read),u=zt(o.cache?.write);return{input:a,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:a+l+c+d+u}},ba=380,lr=8,df=140;function uf({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[d,u]=i.useState(!1),[f,p]=i.useState(null),{enabled:b}=qr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const h=()=>{const v=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!v||!x){p(null);return}const I=v.left-x.left;p(Math.min(Math.max(I,lr),Math.max(lr,x.width-ba-lr)))};h();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const m=new ResizeObserver(h);return m.observe(g),()=>m.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const h=window.setTimeout(()=>{c(!1),u(!1)},df);return()=>window.clearTimeout(h)},[e,l]),i.useEffect(()=>{if(!e)return;const h=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),i.useEffect(()=>{if(!e)return;const h=g=>{const m=g.target;if(!(m instanceof Node)){s();return}o.current?.contains(m)||n.current?.contains(m)||s()};return document.addEventListener("pointerdown",h,!0),r&&document.addEventListener("wheel",h,!0),()=>{document.removeEventListener("pointerdown",h,!0),r&&document.removeEventListener("wheel",h,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:b&&f!==null}}const Wo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},$n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Nn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(R,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),ff=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=uf({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:$("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${ba}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{iconNode:t.jsx(ki,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:$("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:$n(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:$n(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Nn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
3
+ @keyframes session-metadata-in {
4
+ from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
+ to { opacity: 1; transform: translateY(0) scale(1); }
6
+ }
7
+ @keyframes session-metadata-out {
8
+ from { opacity: 1; transform: translateY(0) scale(1); }
9
+ to { opacity: 0; transform: translateY(-6px) scale(0.985); }
10
+ }
11
+ `})]}):null},hf=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=uc(r??""),d=Ut(L=>L.providers),u=Ut(L=>L.currentProviderId),f=Ut(L=>L.currentModelId),p=Ut(L=>L.getCurrentModel()),b=Ut(L=>L.getModelMetadata);Ut(L=>L.modelsMetadata.size);const h=fc(i.useCallback(L=>r?L.sessionModelSelections.get(r)??null:null,[r])),g=i.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const T=c[L]?.info;if(T.role!=="user")continue;const P=T.model,U=P?.providerID??P?.providerId,se=P?.modelID??P?.modelId,W=typeof U=="string"&&U.trim().length>0?U:void 0,G=typeof se=="string"&&se.trim().length>0?se:void 0;if(W&&G)return{providerID:W,modelID:G}}return null},[c]),m=i.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const T=c[L];if(T?.info.role==="assistant"&&Ko(T).total>0)return T}return null},[c]),v=g??(()=>{const L=m?.info.model,T=L?.providerID??L?.providerId,P=L?.modelID??L?.modelId;return T&&P?{providerID:T,modelID:P}:null})()??(h?{providerID:h.providerId,modelID:h.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),I=(v?d.find(L=>L.id===v.providerID):void 0)?.models.find(L=>L.id===v?.modelID),w=v?b(v.providerID,v.modelID):void 0,A=Wo(I?.limit,"context")??w?.limit?.context??Wo(p?.limit,"context")??0,j=m?Ko(m):null,N=m?.info?.usage,C=N?lf(N):j?.total??0,y=!a&&C>0&&A>0?Math.min(C/A*100,999):null,k=y!==null?`${$n(C)}/${$n(A)}`:null,E=y===null?"":y>=90?"text-[var(--status-error)]":y>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",M=j?.cacheRead??null,B=j?.cacheWrite??null,_=j?af({input:j.input,cache:{read:j.cacheRead,write:j.cacheWrite}}):{percent:0,hasInput:!1},K=_.hasInput?_.percent:null,V=y!==null&&k?{percentage:y,tokens:k,colorClass:E,cacheRead:M,cacheWrite:B,cacheHitPercent:K}:null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":s,onClick:()=>n(L=>!L),style:{touchAction:"manipulation"},children:t.jsx(ki,{percentage:V?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(ff,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:V})]})}),gn="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",pf="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",mf=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:$(a??gn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:n})})]}):null}),xa=({variant:e="desktop"})=>{const s=ys(f=>f.entries),[n,r]=i.useState(!1),o=i.useRef(null),a=i.useMemo(()=>[...s.values()].sort((f,p)=>p.startedAt-f.startedAt),[s]),l=a.filter(f=>f.state&&f.state.phase!=="failed").length,c=i.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=i.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(i.useEffect(()=>()=>c(),[c]),a.length===0)return null;const u=f=>{const p=f.receipt;if(!p)return;const b=Ee.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:p.path}),ys.getState().clearEntry(f.key),le.getState().setActiveMainTab("chat"),r(!1)};return t.jsxs(Pt,{open:n,onOpenChange:r,children:[t.jsx(Mt,{asChild:!0,children:t.jsxs("button",{type:"button",className:$(e==="desktop"?gn:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&d()},children:[l>0?t.jsx(js,{variant:"inline",text:null,animationType:"spinner"}):t.jsx(R,{name:"task",className:"size-[18px]"}),t.jsx("span",{children:"Background tasks"})]})}),t.jsxs(Tt,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:d,children:[t.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[t.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:l===1?"1 worktree is being created":`${l} worktrees are being created`})]}),t.jsx("div",{className:"divide-y divide-border",children:a.map(f=>t.jsx(gf,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},gf=({entry:e,onOpen:s})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=!!(e.receipt&&!e.state),a=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return t.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[t.jsx("div",{className:"mt-0.5 shrink-0",children:r?t.jsx(js,{variant:"inline",text:null,animationType:"spinner"}):n?t.jsx(R,{name:"alert",className:"size-4 text-[var(--status-error)]"}):t.jsx(R,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),t.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?t.jsx(Me,{type:"button",variant:"ghost",size:"xs",onClick:()=>ys.getState().dismissFailed(e.key),children:"Dismiss"}):null,o?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Me,{type:"button",size:"xs",onClick:s,children:"Open"}),t.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>ys.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:t.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},bf=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:a,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:d,addSessionToFolder:u}=e;i.useEffect(()=>{!n||!o||a||s.forEach(f=>{if(l.has(f.normalizedPath))return;const p=_i(f.normalizedPath),b=r.archivedSessionsByProject.get(f.id)??[],h=c[p]??[],g=new Map(h.map(m=>[m.name.toLowerCase(),m]));b.forEach(m=>{const v=jd(m,f.normalizedPath),x=v.toLowerCase();let I=g.get(x);I||(I=d(p,v),g.set(x,I)),I.sessionIds.includes(m.id)||u(p,I.id,m.id)})})},[s,n,r,o,a,l,c,d,u])},xf=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 f=a.get(u);f&&(l.push(f),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])}),yf=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:b,foldersMap:h}=e,g=i.useRef(new Map),m=i.useMemo(()=>{const C=g.current,y=new Map;let k=0,E=0;const M=(_,K)=>_.length===K.length&&_.every((V,L)=>V===K[L]),B=s.map(_=>{const K=n(_.id),V=r(_.id),L=a.has(_.id)?!!a.get(_.id):c,T=l.get(_.id)??null,P=o.get(_.normalizedPath)??[],U=C.get(_.id);if(U&&U.project===_&&M(U.activeSessions,K)&&M(U.archivedSessions,V)&&U.rootBranch===T&&U.isRepo===L&&U.worktrees===P&&U.buildGroupedSessions===d)return k+=1,y.set(_.id,U),U.section;E+=1;const se=Ui([...K,...V]),W=d(se,_.normalizedPath,P,T,L),G={project:_,groups:W};return y.set(_.id,{project:_,activeSessions:K,archivedSessions:V,rootBranch:T,isRepo:L,worktrees:P,buildGroupedSessions:d,section:G}),G});return g.current=y,k>0&&Dt("ui.sidebar.project_section.reused",k),E>0&&Dt("ui.sidebar.project_section.rebuilt",E),B},[s,n,r,o,a,c,d,l]),v=i.useMemo(()=>m,[m]),x=i.useMemo(()=>{const C=new WeakMap;if(!u)return C;const y=k=>k.reduce((E,M)=>E+1+y(M.children),0);return v.forEach(k=>{k.groups.forEach(E=>{const M=p(E.sessions,f),B=y(M),_=b(E).includes(f),K=Ae(E.directory??null),L=(K?h[K]??[]:[]).filter(T=>T.name.toLowerCase().includes(f)).length;C.set(E,{filteredNodes:M,matchedSessionCount:B,folderNameMatchCount:L,groupMatches:_,hasMatch:_||B>0||L>0})})}),C},[u,v,p,f,b,h]),I=i.useMemo(()=>u?v.map(C=>({...C,groups:C.groups.filter(y=>x.get(y)?.hasMatch===!0)})).filter(C=>C.groups.length>0):v,[u,v,x]),w=u?I:v,A=i.useRef(new WeakMap),j=i.useMemo(()=>{const C=A.current;return w.map(y=>{const k=C.get(y);if(k&&k.query===f)return k.section;const E=y.groups.filter(T=>!T.isArchivedBucket),M=y.groups.filter(T=>T.isArchivedBucket),B=E.flatMap(T=>u?x.get(T)?.filteredNodes??[]:T.sessions),_=E.map(T=>({scopeKey:T.folderScopeKey??Ae(T.directory??null),directory:T.directory??null})).filter(T=>!!T.scopeKey),K=E.find(T=>T.isMain)??null,V={id:"flat",label:K?.label??"",branch:K?.branch??null,description:K?.description??null,isMain:!0,isArchivedBucket:!1,directory:K?.directory??y.project.normalizedPath,folderScopeKey:K?.folderScopeKey??y.project.normalizedPath,folderScopes:_,sessions:B};if(u){const T=E.map(P=>x.get(P)).filter(P=>!!P);x.set(V,{filteredNodes:B,matchedSessionCount:T.reduce((P,U)=>P+U.matchedSessionCount,0),folderNameMatchCount:T.reduce((P,U)=>P+U.folderNameMatchCount,0),groupMatches:T.some(P=>P.groupMatches),hasMatch:T.some(P=>P.hasMatch)})}const L={project:y.project,groups:[V,...M]};return C.set(y,{query:f,section:L}),L})},[x,u,f,w]),N=i.useMemo(()=>u?w.reduce((C,y)=>C+y.groups.reduce((k,E)=>{const M=x.get(E);if(!M)return k;const B=M.folderNameMatchCount+(M.groupMatches?1:0);return k+M.matchedSessionCount+B},0),0):0,[u,w,x]);return{projectSections:m,visibleProjectSections:v,groupSearchDataByGroup:x,searchableProjectSections:I,sectionsForRender:w,flatSectionsForRender:j,searchMatchCount:N}},wf=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,b=i.useMemo(()=>{const g=new Map,m=new Map,v=(x,I,w,A)=>{g.has(x)||g.set(x,new Map);const j=g.get(x);A.forEach(N=>{const C=Ae(N.session.directory??w??I);j.set(N.session.id,{directory:C}),m.has(x)||m.set(x,{id:N.session.id,directory:C}),N.children.length>0&&v(x,I,C,N.children)})};return s.forEach(x=>{x.groups.forEach(I=>{v(x.project.id,x.project.normalizedPath,I.directory,I.sessions)})}),{metaByProject:g,firstSessionByProject:m}},[s]),h=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){h.current=n;return}if(h.current===n)return;const g=s.find(N=>N.project.id===n);if(!g)return;h.current=n;const m=b.metaByProject.get(n);if(a&&m&&m.has(a)){o(N=>{if(N.get(n)===a)return N;const C=new Map(N);return C.set(n,a),C});return}const v=a?Array.from(b.metaByProject.entries()).some(([N,C])=>N!==n&&C.has(a)):!1;if(a&&m&&!v)return;if(!m||m.size===0){f("chat"),d&&p(!1),u({selectedProjectId:g.project.id,directoryOverride:g.project.normalizedPath});return}const x=r.get(n),I=x&&m.has(x)?x:null,w=b.firstSessionByProject.get(n)?.id??null,A=I??w;if(!A||A===a)return;const j=m.get(A)?.directory??null;l(A,j,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,b,f,p,o]),i.useEffect(()=>{if(!n||!a)return;const g=b.metaByProject.get(n);!g||!g.has(a)||o(m=>{if(m.get(n)===a)return m;const v=new Map(m);return v.set(n,a),v})},[n,a,b,o])},vf=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Ee(c=>c.currentSessionId),o=Ee(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},Ho=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Sf=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},jf=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,ya=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=Sf(e.trim())%Ho.length;return Ho[s]},Cf=(e,s)=>{const n=ya(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Yo=e=>!!e.time?.archived,kf=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=Ae(a.directory??null)??"";return`${is(a)} ${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 f=Ae(l??null),p=Ui(a).sort((C,y)=>Qr(C,y,e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(p.map(C=>[C.id,C])),h=new Map,g=new Map;p.forEach(C=>{const y=C.parentID??null,k=y?b.get(y):null,E=k&&Yo(k)===Yo(C)?y:null;h.set(C.id,E),E&&g.set(E,(g.get(E)??0)+1)});const m=c.map(C=>({worktree:C,directory:Ae(C.path)})).filter(C=>!!C.directory&&!C.worktree.isPrimary).sort((C,y)=>y.directory.length-C.directory.length),v=(C,y)=>y===C||y.startsWith(`${C}/`),x=C=>{const y=Ae(C.directory??null);return y?m.find(k=>v(k.directory,y))?.worktree??null:null},I=(C,y)=>{const k=jf(C.id,h,g);return{session:C,children:[],worktree:y,forkColorId:k}},w=[],A=new Map,j=[];for(const C of m)A.set(C.directory,[]);p.forEach(C=>{const y=x(C),k=I(C,y);C.time?.archived?j.push(k):y?A.get(Ae(y.path)??"")?.push(k):w.push(k)});const N=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?Mo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:w}];for(const{worktree:C,directory:y}of m)N.push({id:`worktree:${y}`,label:C.branch||(C.detached?"Detached HEAD":C.name),branch:C.branch,description:Mo(y,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:C,directory:y,folderScopeKey:y,sessions:A.get(y)??[]});return j.length>0&&N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?_i(f):null,sessions:j}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Af=({mobileVariant:e,isTablet:s})=>!e&&!s,Nf=({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])},If=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((w,A,j)=>{Ir("navigation.session_select"),le.getState().closeMainSurfaces();const N=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},C=j?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),w===Ee.getState().currentSessionId){e.allowReselect&&C&&e.onSessionSelected?.(w),N();return}Ir("navigation.session_state_set"),e.setCurrentSession(w,A??null),C&&e.onSessionSelected?.(w),N()},[e]),a=i.useCallback((w,A)=>{e.setEditingId(w),e.setEditTitle(A)},[e]),l=i.useCallback(async w=>{if(!e.editingId)return;const A=(w??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=i.useCallback(async(w,A)=>{try{return(await ws(w)).ok?(n(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=i.useCallback(async w=>{const A=await e.shareSession(w.id);if(!A?.share?.url){ie.error("Unable to share session");return}const j=await d(A.share.url,w.id);ie[j?"success":"warning"]("Session shared",{description:j?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=i.useCallback((w,A)=>{d(w,A).then(j=>{j||ie.error("Failed to copy URL")})},[d]),p=i.useCallback(w=>{ws(w).then(A=>{if(A.ok){ie.success("Session ID copied");return}ie.error("Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[]),b=i.useCallback(async w=>{await e.unshareSession(w)?ie.success("Session unshared"):ie.error("Unable to unshare session")},[e]),h=i.useCallback(w=>{const A=[],j=N=>{(e.childrenMap.get(N)??[]).forEach(y=>{A.push(y),j(y.id)})};return j(w),A},[e.childrenMap]),g=i.useCallback((w,A)=>A?w:w.filter(j=>!j.time?.archived),[]),m=i.useCallback(async(w,A,j)=>{const N=A?.archivedBucket===!0||A?.hardDelete===!0,C=j?.descendantIds??g(h(w.id),N).map(M=>M.id);if(C.length===0){(N?await e.deleteSession(w.id):await e.archiveSession(w.id))?ie.success(N?"Session deleted":"Session archived"):ie.error(N?"Failed to delete session":"Failed to archive session");return}const y=[w.id,...C];if(N){const{deletedIds:M,failedIds:B}=await e.deleteSessions(y);if(B.length===0){const _=M.length;ie.success(_===1?`Deleted ${_} session`:`Deleted ${_} sessions`)}else ie.error("Failed to delete session");return}const{archivedIds:k,failedIds:E}=await e.archiveSessions(y);k.length>0&&ie.success(k.length===1?`Archived ${k.length} session`:`Archived ${k.length} sessions`),E.length>0&&ie.error(E.length===1?`Failed to archive ${E.length} session`:`Failed to archive ${E.length} sessions`)},[e,h,g]),v=i.useCallback((w,A)=>{const j=A?.archivedBucket===!0||A?.hardDelete===!0,N=g(h(w.id),j).map(C=>C.id);if(!e.showDeletionDialog||A?.skipConfirm===!0){m(w,A,{descendantIds:N});return}e.setDeleteSessionConfirm({session:w,descendantCount:N.length,descendantIds:N,archivedBucket:j})},[e,h,m,g]),x=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:w,archivedBucket:A,descendantIds:j}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await m(w,{archivedBucket:A},{descendantIds:j})},[e,m]),I=i.useCallback(async w=>{await e.unarchiveSession(w.id)?ie.success("Session restored"):ie.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:b,handleDeleteSession:v,handleRestoreSession:I,confirmDeleteSession:x}},Rf=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 p=d.current;if(d.current=null,c.current=null,!p)return;const{projects:b}=ht.getState(),h=b.map(g=>({...g,sidebarCollapsed:p.has(g.id)}));Vr({projects:h}).catch(()=>{})},[]),f=i.useCallback(p=>{typeof window>"u"||(d.current=p,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 p=s.getItem(n.sessionExpanded);if(p){const h=JSON.parse(p);Array.isArray(h)&&a(new Set(h.filter(g=>typeof g=="string")))}const b=s.getItem(n.projectCollapse);if(b){const h=JSON.parse(b);Array.isArray(h)&&l(new Set(h.filter(g=>typeof g=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const p=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},Ef=3;let Gn=0;const wa=[],Df=()=>Gn<Ef?(Gn+=1,Promise.resolve()):new Promise(e=>{wa.push(e)}),Pf=()=>{const e=wa.shift();if(e){e();return}Gn=Math.max(0,Gn-1)},Mf=async e=>{await Df();try{return await e()}finally{Pf()}},Tf=5*6e4,Ff=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=Us(),c=Ai(p=>p.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(p=>{Mf(()=>c(p.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const p=new Map;s.forEach(b=>{p.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)}),o(p)},[n,s,r,o]);const d=i.useMemo(()=>s.map(p=>{const b=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${b}`}).join("|"),[s,r]),u=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let p=!1;const b=setTimeout(()=>{(async()=>{const g=new Set(s.map(w=>w.id));for(const w of u.current.keys())g.has(w)||(u.current.delete(w),f.current.delete(w));const m=Date.now();if(s.filter(w=>{const A=r.get(w.normalizedPath);if(A?.isGitRepo===!1)return u.current.delete(w.id),f.current.delete(w.id),!1;if(A?.isGitRepo!==!0||A.branch===null)return!1;const j=A.branch.trim(),N=`${w.normalizedPath}\0${j}`,C=u.current.get(w.id);if(C===N){const y=f.current.get(w.id);return y&&(y.at=m),!1}return!(C!==void 0&&m-(f.current.get(w.id)?.at??0)<Tf)}).length===0)return;const x=[];if(s.forEach(w=>{const A=r.get(w.normalizedPath)?.branch?.trim()??"",j=`${w.normalizedPath}\0${A}`;A&&x.push({id:w.id,inputKey:j,branch:A})}),p||x.length===0)return;const I=Date.now();a(w=>{const A=new Map(w);return x.forEach(({id:j,branch:N})=>{N&&A.set(j,N)}),A}),x.forEach(({id:w,inputKey:A,branch:j})=>{u.current.set(w,A),j&&f.current.set(w,{branch:j,at:I})})})()},150);return()=>{p=!0,clearTimeout(b)}},[n,s,d,r,a])},Of=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}},Lf=e=>{const s=new Map;for(const n of e){const r=rn(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Bf=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},_f=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Jr(),l=Lf(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const d of Bf(c,l))Es().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:a,identities:l}},[s,n,r])},Uf=(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,qo=(e,s,n)=>{Uf(e.get(s),n)&&e.set(s,n)},va=e=>{const s=e;return Ae(s.directory)??Ae(s.project?.worktree)},zf=(e,s,n)=>{if(e.time?.archived)return!0;const r=va(e);if(!r)return n?.allowUnknownDirectory??!0;if(qn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(Ae(a)?.toLowerCase()===o)return!0;return!1},$f=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)},Gf=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const h of s){const g=Ae(h.normalizedPath);if(!g)continue;const m=a.get(g);(!m||h.id.localeCompare(m.id)<0)&&a.set(g,h),qo(o,g,{projectId:h.id,projectRoot:g,scopeDirectory:g,kind:"project"})}if(n)for(const[h,g]of n){const m=Ae(h),v=m?a.get(m):void 0;if(!(!v||!m))for(const x of g||[]){const I=Ae(x?.path);I&&qo(o,I,{projectId:v.id,projectRoot:m,scopeDirectory:I,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,p=h=>{if(!h)return null;if(l.has(h))return l.get(h)??null;const g=[];let m=h,v=null;for(;m;){if(l.has(m)){v=l.get(m)??null;break}if(g.push(m),v=o.get(m)??null,v)break;m=$f(m)}for(const x of g)l.set(x,v);return v},b=(h,g,m)=>{for(const v of h){const x=va(v);if(qn(x))continue;const I=p(x);if(!I)continue;c.set(v.id,I);const w=g.get(I.projectId);if(w?w.push(v):g.set(I.projectId,[v]),!m)continue;const A=m.get(I.scopeDirectory);A?A.add(v.id):m.set(I.scopeDirectory,new Set([v.id]))}};return b(e,d,f),b(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}};function Sa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:$("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:$("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Kf=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:p,projectId:b,mobileVariant:h=!1,alwaysShowActions:g=h,isRenaming:m=!1,renameDraft:v="",onRenameDraftChange:x,onRenameSave:I,onRenameCancel:w,droppableRef:A,isDropTarget:j=!1,onNewSession:N,depth:C=0,hideActions:y=!1,archivedBucket:k=!1})=>{const[E,M]=i.useState(!1),[B,_]=i.useState(""),K=i.useRef(null),V=m||E,L=m?v:B,T=i.useCallback(()=>{_(e.name),M(!0)},[e.name]),P=i.useCallback(()=>{const G=L.trim();G&&G!==e.name&&c(G),m&&I&&I(),M(!1),_("")},[L,e.name,m,c,I]),U=i.useCallback(()=>{m&&w&&w(),M(!1),_("")},[m,w]),se=i.useCallback(G=>{m&&x?x(G):_(G)},[m,x]);i.useEffect(()=>{if(!m)return;const G=()=>{const Te=K.current;Te&&(Te.focus(),Te.select())},Ie=requestAnimationFrame(G),ee=window.setTimeout(G,0);return()=>{cancelAnimationFrame(Ie),window.clearTimeout(ee)}},[m]);const W=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:A,className:$("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",j&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:V?void 0:G=>{G.currentTarget.blur(),l()},role:V?void 0:"button",tabIndex:V?void 0:0,onKeyDown:V?void 0:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:$("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",k?g?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":g?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(R,{name:W,className:$(Mn,j?"text-primary":"text-muted-foreground")}),V?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onSubmit:G=>{G.preventDefault(),P()},children:[t.jsx("input",{ref:K,value:L,onChange:G=>se(G.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onKeyDown:G=>{if(G.key==="Escape"){G.stopPropagation(),U();return}(G.key===" "||G.key==="Enter")&&G.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),children:t.jsx(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),U()},onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("span",{className:$(zi,j?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(Ge,{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(Sa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(R,{name:"arrow-right-s",className:$(Mn,"text-muted-foreground")}):t.jsx(R,{name:"arrow-down-s",className:$(Mn,"text-muted-foreground")})]})]}),!V&&(!y||k)?t.jsx("div",{className:$("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",g?"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:[!k&&N?t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),N()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:t.jsx(R,{name:"add",className:"size-4"})}):null,k?null:t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),T()},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(R,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":k?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(R,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(G=>t.jsx(i.Fragment,{children:u(G,0,p??null,b??null,k,void 0,"project",f?.(G))},G.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Wf=i.memo(Kf),Hf=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=zd({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})},Yf=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=$d({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},qf=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=Qi(Fr(_d,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,d]=i.useState("Session"),[u,f]=i.useState(null),[p,b]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const h=g=>{l(null),f(null),b(null);const{active:m,over:v}=g;if(!v)return;const x=m.data.current,I=v.data.current;x?.type==="session"&&x.sessionId&&I?.type==="folder"&&I.folderId&&n(x.sessionId,I.folderId)};return t.jsxs(Vi,{sensors:o,collisionDetection:Ji,onDragStart:g=>{const m=g.active.data.current;if(m?.type==="session"&&m.sessionId){l(m.sessionId),d(m.sessionTitle??"Session");const v=g.active.rect.current.initial?.width,x=g.active.rect.current.initial?.height;f(typeof v=="number"?v:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{l(null),f(null),b(null)},onDragEnd:h,children:[r,t.jsx(Ud,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:p?`${p}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(R,{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})]})},bs=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:$(o?Cd:kd,r),children:[t.jsx(R,{name:e,className:$(un(o),"text-muted-foreground")}),t.jsx("span",{className:$(fn(o),"flex-1 text-muted-foreground"),children:s})]}),Qo=(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)},Jt=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(Jt(n,s))return!0;return!1},Qf=(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})},Vo=new WeakMap;let Jo=1;const Vf=e=>{const s=Vo.get(e);if(s!==void 0)return s;const n=Jo;return Jo+=1,Vo.set(e,n),n},Gr=e=>e.children.length===0?"":e.children.map(n=>{const r=Vf(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Gr(n)}`}).join("|"),ja=(e,s,n,r,o,a)=>{const l=Jr(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,p=u.session.directory??a,b=Eo(l,f??"",d.session.id),h=Eo(l,p??"",u.session.id);return(b?n.has(b):!1)!==(h?r.has(h):!1)?!0:d.children.some((g,m)=>c(g,u.children[m]))};return c(e,s)},Kn=(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},Ca=(e,s)=>"",Jf=zs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),ka=e=>null,oo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Aa=(e,s,n)=>{if(s.has(e.session.id))return"active";let r=n.has(e.session.id)?"unread":null;for(const o of e.children)if(r=oo(r,Aa(o,s,n)),r==="active")return r;return r},Na=(e,s,n)=>{let r=null;for(const o of e)if(r=oo(r,Aa(o,s,n)),r==="active")return r;return r},Xf=50,Zf=28;function eh({visibleSessions:e,shouldVirtualize:s,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:a,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:d}){const u=i.useRef(null),[f,p]=i.useState(null),[b,h]=i.useState(0),[,g]=i.useState(0);i.useEffect(()=>{if(!s)return;const x=u.current;if(!x||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>g(w=>w+1));return I.observe(x),()=>I.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&p(null),b!==0&&h(0);return}const x=u.current;if(!x)return;let I=f;const w=r?.current??null;if(w&&w.contains(x)){if(I=w,I!==f){p(I);return}}else if(!I||!I.contains(x)){let j=x.parentElement;for(;j;){const N=window.getComputedStyle(j);if(N.overflowY==="auto"||N.overflowY==="scroll"){I=j;break}j=j.parentElement}if(I!==f){p(I);return}}if(!I)return;const A=x.getBoundingClientRect().top-I.getBoundingClientRect().top+I.scrollTop;h(j=>Math.abs(j-A)<1?j:A)},[f,b,r,s]);const m=s&&f!==null,v=Wd({count:e.length,enabled:m,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>Zf,overscan:n?20:8,scrollMargin:b,getItemKey:x=>e[x]?.session.id??x});return t.jsx("div",{ref:u,children:s?t.jsx("div",{style:{height:v.getTotalSize(),position:"relative"},children:v.getVirtualItems().map(x=>{const I=e[x.index];return I?t.jsx("div",{"data-index":x.index,ref:v.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${x.start-b}px)`},children:c(I,0,o,a,l,void 0,"project",d(I))},I.session.id):null})}):e.map(x=>t.jsx(i.Fragment,{children:c(x,0,o,a,l,void 0,"project",d(x))},x.session.id))})}const Fn=(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};function th({group:e,groupKey:s,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:a,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:b,allGroupSessions:h,projectId:g,activeProjectId:m,setActiveProjectIdOnly:v,setActiveMainTab:x,mobileVariant:I,setSessionSwitcherOpen:w,openNewSessionDraft:A}){return t.jsxs("div",{className:$("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(s),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:$("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.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:e.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(R,{name:"archive",className:$("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:$("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(R,{name:"arrow-right-s",className:"size-4"}):t.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:Fn(e.label,o)}),f]}):!e.isMain||e.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(R,{name:"git-branch",className:$("size-4 shrink-0",!d&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),t.jsx("span",{className:$("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(R,{name:"arrow-right-s",className:"size-4"}):t.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Fn(e.label,o)}),f,u?t.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:d?{color:d}:void 0,children:["#",u.number]}):null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:Fn(e.label,o)}),f]})}),p&&b?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?t.jsx(R,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(R,{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:b.label})]}):null]})}),e.isArchivedBucket&&h.length>0?t.jsx("div",{className:$("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),xs.requestDelete({sessions:h,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 ${e.label}`,children:t.jsx(R,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:$("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),g&&g!==m&&v(g),x("chat"),I&&w(!1),A({selectedProjectId:g,directoryOverride:e.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 ${e.label}`,children:t.jsx(R,{name:"add",className:"h-4 w-4"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]})}const In=(e,s)=>s?e.sessions.some(n=>Jt(n,s)):!1,sh=(e,s,n)=>e.sessions.some(r=>ja(r,r,s,n,e.directory,e.directory)),nh=(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)},Xo=(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)},rh=(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)},oh=(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&&sh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&rh(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&nh(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(In(e.group,e.editingId)||In(s.group,s.editingId))||e.editTitle!==s.editTitle&&(In(e.group,e.editingId)||In(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Kn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Kn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Xo(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Xo(s.group,e.unreadActivitySessionIds,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 ih({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,collectGroupSessions:c}){const d=ft(j=>j.foldersMap),u=e.folderScopeKey??Ae(e.directory??null),f=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),p=i.useMemo(()=>f.flatMap(({scopeKey:j,directory:N})=>(d[j]??[]).map(C=>({folder:C,scopeKey:j,scopeDirectory:N}))),[f,d]),b=i.useMemo(()=>{const j=new Map,N=C=>{C.forEach(y=>{j.set(y.session.id,y),y.children.length>0&&N(y.children)})};return N(s),j},[s]),h=i.useMemo(()=>p.map(({folder:j,scopeKey:N,scopeDirectory:C})=>{const y=Qf(j.sessionIds,b).sort(o);return{folder:j,scopeKey:N,scopeDirectory:C,nodes:y}}),[p,b,o]),g=i.useMemo(()=>{const j=new Map(h.map(k=>[k.folder.id,k])),N=new Map;for(const{folder:k}of h){if(!k.parentId)continue;const E=N.get(k.parentId);E?E.push(k.id):N.set(k.parentId,[k.id])}const C=new Map,y=k=>{const E=C.get(k);if(E!==void 0)return E;const M=j.get(k);if(!M)return C.set(k,!1),!1;const B=N.get(k)??[];if(e.isArchivedBucket&&M.nodes.length===0){const V=B.some(L=>y(L));return C.set(k,V),V}if(!n||M.folder.name.toLowerCase().includes(r)||M.nodes.length>0)return C.set(k,!0),!0;const K=B.some(V=>y(V));return C.set(k,K),K};return h.filter(({folder:k})=>y(k.id))},[h,e.isArchivedBucket,n,r]),m=i.useMemo(()=>new Set(g.flatMap(j=>j.folder.sessionIds)),[g]),v=i.useMemo(()=>s.filter(j=>!m.has(j.session.id)),[s,m]),x=i.useMemo(()=>g.filter(({folder:j})=>!j.parentId),[g]),I=i.useMemo(()=>{const j=new Map;return g.forEach(N=>{if(!N.folder.parentId)return;const C=j.get(N.folder.parentId)??[];C.push(N),j.set(N.folder.parentId,C)}),j},[g]),w=i.useMemo(()=>{const j=new Map(g.map(y=>[y.folder.id,y])),N=new Map,C=(y,k)=>{const E=N.get(y);if(E!==void 0)return E;if(k.has(y))return null;k.add(y);const M=j.get(y);let B=M?Na(M.nodes,a,l):null;for(const _ of I.get(y)??[])if(B=oo(B,C(_.folder.id,k)),B==="active")break;return N.set(y,B),B};return g.forEach(({folder:y})=>C(y.id,new Set)),N},[a,g,I,l]),A=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const j=new Map,N=new Map;for(const{folder:y}of g){if(!y.parentId)continue;const k=N.get(y.parentId)??[];k.push(y.id),N.set(y.parentId,k)}const C=(y,k)=>{if(k.has(y))return[];k.add(y);const E=g.find(({folder:_})=>_.id===y),M=E?c(E.nodes):[],B=N.get(y)??[];for(const _ of B)M.push(...C(_,k));return M};for(const{folder:y}of g)j.set(y.id,C(y.id,new Set));return j},[g,c,e.isArchivedBucket]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:g,rootFolders:x,ungroupedSessions:v,folderActivityStateById:w,folderSessionsForDeleteById:A}}function ah(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:b,renameFolder:h,deleteFolder:g,showDeletionDialog:m,setDeleteFolderConfirm:v,renderSessionNode:x,showMoreGroupSessions:I,resetGroupSessionLimit:w,mobileVariant:A,alwaysShowActions:j,activeProjectId:N,setActiveProjectIdOnly:C,setActiveMainTab:y,setSessionSwitcherOpen:k,openNewSessionDraft:E,addSessionToFolder:M,createFolderAndStartRename:B,renamingFolderId:_,renameFolderDraft:K,setRenameFolderDraft:V,setRenamingFolderId:L,pinnedSessionIds:T,expandedParents:P,sessionOrderIndex:U,editingId:se,openSidebarMenuKey:W,activeActivitySessionIds:G,unreadActivitySessionIds:Ie,onToggleCollapsedGroup:ee,dragHandleProps:Te,compactBodyPadding:_e=!1,scrollContainerRef:q}=e,F=i.useCallback((ye,Pe)=>{const je=U.get(ye.session.id),Le=U.get(Pe.session.id);if(je!==void 0||Le!==void 0){if(je===void 0)return 1;if(Le===void 0)return-1;if(je!==Le)return je-Le}return Qr(ye.session,Pe.session,T,Ni)},[T,U]),z=a?c.get(s):null,Q=a?!1:u.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const ye=Ae(s.directory??null),Pe=s.branch?.trim();return ye&&Pe?Ca():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const te=ka(),Ce=void 0,ge=f?10:5,xe=Math.max(ge,d??ge),re=a?z?.groupMatches===!0:!1,oe=a,H=i.useMemo(()=>[...oe?z?.filteredNodes??[]:s.sessions].sort(F),[F,s.sessions,z?.filteredNodes,oe]),be=i.useCallback(ye=>{const Pe=[],je=Le=>{Le.forEach(Ye=>{Pe.push(Ye.session),Ye.children.length>0&&je(Ye.children)})};return je(ye),Pe},[]),{folderScopeKey:Be,folderScopes:O,allFoldersForGroup:Z,rootFolders:he,ungroupedSessions:ue,folderActivityStateById:me,folderSessionsForDeleteById:Oe}=ih({group:s,sourceGroupNodes:H,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:F,activeActivitySessionIds:G,unreadActivitySessionIds:Ie,collectGroupSessions:be}),ve="project",X=i.useMemo(()=>{const ye=new Set;return Qo(H,se,ye),Z.forEach(({nodes:Pe})=>{Qo(Pe,se,ye)}),ye},[H,Z,se]),pe=i.useMemo(()=>{if(!W)return null;const ye=Kn(H,W,ve,!!s.isArchivedBucket);if(ye)return ye;for(const{nodes:Pe}of Z){const je=Kn(Pe,W,ve,!!s.isArchivedBucket);if(je)return je}return null},[W,H,Z,s.isArchivedBucket]),de=i.useCallback(ye=>{const Pe=new WeakMap,je=Le=>{Pe.set(Le,Gr(Le));for(const Ye of Le.children)je(Ye)};return ye.forEach(je),Pe},[]),ke=i.useMemo(()=>de(H),[de,H]),He=i.useMemo(()=>{const ye=new WeakMap;return Z.forEach(({nodes:Pe})=>{Pe.forEach(je=>ye.set(je,Gr(je)))}),ye},[Z]),We=i.useCallback(ye=>ke.get(ye)??He.get(ye)??"",[ke,He]),Se=i.useCallback(ye=>({subtreeContainsEditing:X,menuOpenSessionId:pe,nodeStructureKey:We(ye)}),[X,pe,We]),ne=ue.length,Fe=s.isArchivedBucket||a?ue:ue.slice(0,xe),De=ne-Fe.length,kt=!s.isArchivedBucket&&!a&&ne>ge&&De===0,Ze=s.isArchivedBucket===!0&&!a&&Fe.length>=Xf,Xe=s.isArchivedBucket?"archived":"active",Kt=Ze&&Fe.some(ye=>{if(ye.children.length===0)return!1;const Pe=`project:${Xe}:${ye.session.id}`;return P.has(Pe)}),wt=i.useMemo(()=>be(H),[be,H]);if(a&&!re&&he.length===0&&ue.length===0)return null;const Zt=!s.isMain&&!!s.branch,ot=s.branch&&Ad(s.branch,s.label)?{label:s.branch,color:null}:null,et=Q?Na(H,G,Ie):null,it=et?t.jsx(Sa,{state:et,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,vt=(ye,Pe)=>{const{folder:je,scopeKey:Le,scopeDirectory:Ye,nodes:ct}=ye,At=Oe.get(je.id)??[],Ot=a?!1:p.has(je.id);return t.jsx(Yf,{folderId:je.id,children:(es,pt)=>t.jsx(Wf,{folder:je,displayName:Pe,sessions:ct,isCollapsed:Ot,collapsedActivityState:Ot?me.get(je.id)??null:null,onToggle:()=>b(je.id),onRename:qe=>{h(Le,je.id,qe)},onDelete:()=>{if(s.isArchivedBucket){xs.requestDelete({sessions:At,mode:"session"});return}if(!m){g(Le,je.id);return}const qe=Z.filter(({folder:mt})=>mt.parentId===je.id).length,ts=ct.length;v({scopeKey:Le,folderId:je.id,folderName:je.name,subFolderCount:qe,sessionCount:ts})},renderSessionNode:x,getRenderExtras:We?qe=>({subtreeContainsEditing:X,menuOpenSessionId:pe,nodeStructureKey:We(qe),childRenderExtrasFor:Se}):void 0,groupDirectory:Ye??s.directory,projectId:r,mobileVariant:A,alwaysShowActions:j,isRenaming:_===je.id,renameDraft:_===je.id?K:void 0,onRenameDraftChange:qe=>V(qe),onRenameSave:()=>{const qe=K.trim();qe&&h(Le,je.id,qe),L(null),V("")},onRenameCancel:()=>{L(null),V("")},droppableRef:es,isDropTarget:pt,depth:0,onNewSession:()=>{r&&r!==N&&C(r),y("chat"),A&&k(!1),E({selectedProjectId:r,directoryOverride:Ye??s.directory,targetFolderId:je.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},je.id)},bt=()=>{const ye=new Map;for(const Le of Z){const Ye=Le.folder.parentId;if(!Ye)continue;const ct=ye.get(Ye);ct?ct.push(Le):ye.set(Ye,[Le])}const Pe=[],je=(Le,Ye)=>{const ct=Ye?`${Ye} / ${Le.folder.name}`:Le.folder.name;Pe.push(vt(Le,ct)),!(!a&&p.has(Le.folder.id))&&(ye.get(Le.folder.id)??[]).forEach(Ot=>je(Ot,ct))};return he.forEach(Le=>je(Le,"")),Pe},Wt=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",St=t.jsxs(qf,{scopeKey:O[0]?.scopeKey??Be,hasFolders:Z.length>0,onSessionDroppedOnFolder:(ye,Pe)=>{const je=Z.find(({folder:Ye})=>Ye.id===Pe);if(!je)return;const Le=ft.getState();for(const{scopeKey:Ye}of O)Ye!==je.scopeKey&&Le.getSessionFolderId(Ye,ye)&&Le.removeSessionFromFolder(Ye,ye);M(je.scopeKey,Pe,ye)},children:[bt(),s.isArchivedBucket?t.jsx(eh,{visibleSessions:Fe,shouldVirtualize:Ze,hasExpandedParent:Kt,scrollContainerRef:q,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:x,getRenderExtras:ye=>({subtreeContainsEditing:X,menuOpenSessionId:pe,nodeStructureKey:We(ye),childRenderExtrasFor:Se})}):Fe.map(ye=>t.jsx(i.Fragment,{children:x(ye,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:X,menuOpenSessionId:pe,nodeStructureKey:We(ye),childRenderExtrasFor:Se})},ye.session.id)),ne===0&&Z.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."}):t.jsx(bs,{icon:"chat-new",onClick:()=>{E({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,De>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>I(n,Fe.length),children:De===1?"Show 1 more session":`Show ${De} more sessions`}):null,kt?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>w(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:St})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(th,{group:s,groupKey:n,isCollapsed:Q,onToggleCollapsedGroup:ee,normalizedSessionSearchQuery:l,alwaysShowActions:j,groupHeaderRightPadding:Wt,dragHandleProps:Te,groupPrColor:Ce,groupPrSummary:te,groupActivityIndicator:it,showBranchSubtitle:Zt,statusLine:ot,allGroupSessions:wt,projectId:r,activeProjectId:N,setActiveProjectIdOnly:C,setActiveMainTab:y,mobileVariant:A,setSessionSwitcherOpen:k,openNewSessionDraft:E}),Q?null:t.jsx("div",{className:"oc-group-body",children:St})]})}const lh=i.memo(ah,oh);function ch(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:b,sessionSearchQuery:h,setSessionSearchQuery:g,hasSessionSearchQuery:m,searchMatchCount:v,selectionModeEnabled:x,onToggleSelectionMode:I,mobileVariant:w=!1}=e;if(s)return null;const A=$(u,"text-muted-foreground hover:text-foreground",!w&&"hover:bg-transparent");return t.jsx("div",{className:$("select-none flex-shrink-0",w?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:$("flex flex-col",w?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:$("flex items-center justify-between",w?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:$("flex min-w-0 items-center",w?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":w?"true":void 0,children:[o?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:A,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!w&&a?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:A,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(R,{name:"server",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:A,"aria-label":"Update",children:t.jsx(R,{name:"download",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,w?null:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:A,"aria-label":"Add project",children:t.jsx(R,{name:"folder-add",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),w?null:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:A,"aria-label":"Archive",children:t.jsx(R,{name:"archive",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:$("flex shrink-0 items-center",w?"gap-1":"gap-1.5"),children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>p(j=>!j),className:A,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(R,{name:"search",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:I,className:$(A,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:t.jsx(R,{name:"checkbox-multiple",className:d})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:x?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:$(w?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:m?t.jsx("span",{children:v===1?`${v} match`:`${v} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(R,{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:b,value:h,onChange:j=>g(j.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:j=>{j.key==="Escape"&&(j.stopPropagation(),m?g(""):p(!1))}}),h.length>0?t.jsx("button",{type:"button",onClick:()=>g(""),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(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function dh(e){const s=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=Xr(Bn("toggle_sidebar",n));return t.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${Oo})`}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${Oo})))`}}),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:$("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(R,{name:"chat-new",className:$(Mn,"text-current")}),t.jsx("span",{className:zi,children:"New session"})]}),e.showSidebarToggle?t.jsxs(ze,{children:[t.jsx($e,{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(R,{name:"layout-left",className:"size-4"})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Ia=500,uh=({projectId:e,worktree:s,isSelected:n,hasActive:r,onSelect:o,onClose:a,mobileVariant:l=!1})=>{const[c,d]=i.useState(!1),u=i.useRef(null),f=s.branch||(s.detached?"Detached HEAD":s.name),p=i.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);i.useEffect(()=>()=>p(),[p]);const b=i.useCallback(()=>{p(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},Ia)},[p]);return t.jsxs(so,{open:c,onOpenChange:d,children:[t.jsxs(no,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:$(Wn(l,n),"pl-6"),"aria-pressed":n,title:s.path}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx(R,{name:"git-branch",className:$(un(l),"text-muted-foreground")}),t.jsx("span",{className:fn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(ro,{className:"min-w-[160px]",children:t.jsxs(Ms,{disabled:!a,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>a?.(e,s),className:"text-destructive focus:text-destructive",children:[t.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close worktree"})]})})]})},Wn=(e,s)=>$("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),fh=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:a,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:b,setNodeRef:h,transform:g,transition:m,isDragging:v}=qd({id:e.id,disabled:!c}),[x,I]=i.useState(!1),w=i.useRef(null),A=i.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);i.useEffect(()=>()=>A(),[A]);const j=i.useCallback(()=>{A(),w.current=window.setTimeout(()=>{w.current=null,I(!0)},Ia)},[A]);return t.jsx("div",{ref:h,style:{transform:Qd.Translate.toString(g),transition:m},className:$(v&&"opacity-60"),children:t.jsxs(so,{open:x,onOpenChange:I,children:[t.jsxs(no,{render:t.jsx("button",{type:"button",onClick:()=>{x||d()},onTouchStart:j,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Wn(p,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:$("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${s}`:void 0,...c?b:{},children:t.jsx(R,{name:"folder",className:$(un(p),"text-muted-foreground")})}),t.jsx("span",{className:fn(p),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,a?t.jsx("span",{title:a,"aria-label":"Worktree discovery failed",children:t.jsx(R,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?t.jsx(R,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(ro,{className:"min-w-[160px]",children:[t.jsxs(Ms,{onClick:()=>u(e.id),children:[t.jsx(R,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(ga,{}),t.jsxs(Ms,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},hh=({projects:e,selectedProjectId:s,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:a,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:b,homeDirectory:h,className:g,mobileVariant:m=!1})=>{const v=s===null,x=ht(j=>j.reorderProjects),I=e.length>1,w=Qi(Fr(Kd,{activationConstraint:{distance:8}}),Fr(Gd,{activationConstraint:{delay:200,tolerance:6}})),A=i.useCallback(j=>{const{active:N,over:C}=j;if(!C||N.id===C.id)return;const y=ht.getState().projects,k=y.findIndex(M=>M.id===N.id),E=y.findIndex(M=>M.id===C.id);k<0||E<0||x(k,E)},[x]);return t.jsxs("div",{className:$("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",g),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:Wn(m,v),"aria-pressed":v,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(R,{name:"chat-history",className:un(m)}),t.jsx("span",{className:fn(m),children:"All sessions"})]})}),t.jsx(Vi,{sensors:w,collisionDetection:Ji,onDragEnd:A,children:t.jsx(Hd,{items:e.map(j=>j.id),strategy:Yd,children:e.map(j=>{const N=s===j.id,C=N&&!n,y=r.get(j.normalizedPath)??[],k=Qn(j.label?.trim()||Os(j.normalizedPath,h)||j.normalizedPath),E=b?.get(j.id),M=Ae(j.normalizedPath)?.toLowerCase()??"",B=M?E?.has(M)??!1:!1,_=(E?.size??0)>0,K=p?.(j.id)??!1,V=b?N?B:_:K;return t.jsxs(i.Fragment,{children:[t.jsx(fh,{project:j,label:k,isSelected:C,hasActive:V,hasWorktrees:y.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:N,canDrag:I,onSelect:()=>a(j.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m}),N?y.map(L=>{const T=n===L.path,P=Ae(L.path)?.toLowerCase()??"",U=P?E?.has(P)??!1:!1,se=b?U:!1;return t.jsx(uh,{projectId:j.id,worktree:L,isSelected:T,hasActive:se,onSelect:()=>l?.(j.id,L.path),onClose:c,mobileVariant:m},L.path)}):null]},j.id)})})}),t.jsxs("button",{type:"button",onClick:d,className:Wn(m,!1),children:[t.jsx(R,{name:"add",className:un(m)}),t.jsx("span",{className:fn(m),children:"Add folder"})]})]})},cr="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 ph({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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:cr,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:cr,"aria-label":"Shortcuts",children:t.jsx(R,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:cr,"aria-label":"About PiChamber",children:t.jsx(R,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{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 mh=(e,s)=>Qn(e.label?.trim()||Os(e.normalizedPath,s)||e.normalizedPath);function gh(e){Dt("ui.sidebar_projects_list.render");const s=i.useRef(new Map),n=i.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,s.current.clear());const r=(p,b)=>{const h=s.current,g=h.get(p);if(g&&g.groups===b)return g.ordered;const m=e.getOrderedGroups(p,b);if(h.set(p,{groups:b,ordered:m}),h.size>256){const v=h.keys().next().value;v!==void 0&&h.delete(v)}return m},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const p=[],b=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const h of b){const g=mh(h.project,e.homeDirectory);for(const m of h.groups)if(!m.isArchivedBucket)for(const v of m.sessions){const x=!!e.pinnedSessionIds?.has(v.session.id),I=v.session.time?.updated||v.session.time?.created||0;p.push({node:v,project:h.project,projectLabel:g,isPinned:x,timestamp:I,globalSession:h===e.allFoldersOnlySection})}}return p.sort((h,g)=>h.isPinned!==g.isPinned?h.isPinned?-1:1:g.timestamp-h.timestamp),p},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=i.useState(30);i.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const d=a.slice(0,l),u=a.length-d.length;if(e.sharedSessionsOnly)return t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const f=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!f?t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!f?t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsx("div",{className:"relative flex min-h-0 flex-1",children:t.jsx(ps,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),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 p=e.sectionsForRender.find(m=>m.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!p)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=p.groups.find(m=>m.isMain&&m.sessions.length>0)??p.groups.find(m=>m.sessions.length>0)??p.groups.find(m=>m.isMain)??p.groups[0];if(!b)return t.jsx(bs,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath}),children:"New session"});const h=p.groups.find(m=>m.isArchivedBucket);return[b,...h&&h.id!==b.id?[h]:[]].map(m=>{const v=`${p.project.id}:${m.id}`,x=m.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(m,v,p.project.id,x,null,!0,o)},v)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[d.map(({node:p,project:b,projectLabel:h,globalSession:g})=>{const m=p.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(p,0,m,b.id,!1,{projectLabel:h,showFolderLabel:!0,globalSession:g},"project")},p.session.id)}),u>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>c(p=>p+30),children:u===1?"Show 1 more session":`Show ${u} more sessions`}):null,l>30&&a.length>30?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(p=>{const b=p.project.id,h=r(b,p.groups),g=h.find(v=>v.isMain)??null,m=g?h.filter(v=>v.id!==g.id):h;return t.jsxs("div",{children:[g?e.renderGroupSessions(g,`${b}:${g.id}`,b,!0,null,void 0,o):null,m.map(v=>{const x=`${b}:${v.id}`,I=h.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(v,x,b,I,null,void 0,o)},v.id)})]},b)})})]})})})}const bh=i.memo(gh);let Kr=!1;const Wr=new Set;let Zo=!1;function xh(){for(const e of Wr)e()}function io(e){Kr!==e&&(Kr=e,xh())}function yh(e){e.key==="Shift"&&io(!0)}function wh(e){e.key==="Shift"&&io(!1)}function vh(){io(!1)}function Sh(){Zo||typeof window>"u"||(Zo=!0,window.addEventListener("keydown",yh),window.addEventListener("keyup",wh),window.addEventListener("blur",vh))}function jh(e){return Sh(),Wr.add(e),()=>{Wr.delete(e)}}function Ch(){return Kr}function kh(){return!1}function Ah(){return Ne.useSyncExternalStore(jh,Ch,kh)}const Nh=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Ah(),f=u?n:s,p=b=>{if(u||b.shiftKey){d(b);return}c(b)};return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",className:$("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":f,onPointerDown:a,onMouseDown:l,onClick:p,onKeyDown:b=>b.stopPropagation(),children:t.jsx(R,{name:u?"delete-bin":"archive",className:o})})}),t.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),Ih=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx($t,{open:s,onOpenChange:n,children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:"Export Markdown"}),t.jsx(ls,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} 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:o,onChange:c=>a(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Ss,{children:[t.jsx(Me,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Me,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Rh(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:b,handleDeleteSession:h,handleRestoreSession:g}=e,{Item:m,Separator:v}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(m,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(m,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(m,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[a?t.jsx(R,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(R,{name:"pushpin",className:"mr-1 h-4 w-4"}),a?"Unpin session":"Pin session"]}),t.jsxs(m,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(m,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(v,{}),l?null:t.jsxs(m,{className:"[&>svg]:mr-1",onClick:()=>h(n,{archivedBucket:l}),children:[t.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(m,{className:"[&>svg]:mr-1",onClick:()=>g(n),children:[t.jsx(R,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(m,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>h(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Eh(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(Ki,{children:t.jsx(Wi,{className:"app-region-no-drag z-50",children:t.jsx(Hi,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:$(Si,"min-w-[180px]"),children:Rh(e,{Item:({className:r,...o})=>t.jsx(Yi,{className:$(ji,r),...o}),Separator:({className:r,...o})=>t.jsx(qi,{className:$(Ci,r),...o})})})})})}const dr=new WeakMap,Dh=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;dr.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,dr.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,Dt("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}),dr.set(n,c),l=window.requestAnimationFrame(d)};function Ph(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 Mh(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 Th(e){const s=e.info.role==="user"?"User":"Assistant",n=Ph(e.info.time?.created),r=Mh(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
12
+
13
+ *${o}*`:`**${s}**`}function Fh(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Ra(e){const s=Th(e),n=Fh(e.parts).trim();return n?`${s}
14
+
15
+ ${n}`:""}function Ea(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
16
+
17
+ ---
18
+
19
+ `,a=e.records.map(Ra).filter(Boolean).join(`
20
+
21
+ ---
22
+
23
+ `),l=[o+a];for(const c of e.children)l.push(Ea(c,s+1));return l.join(`
24
+
25
+ ---
26
+
27
+ `)}function Da(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
28
+
29
+ *Exported on ${o}*
30
+
31
+ ---
32
+
33
+ `,l=e.map(Ra).filter(Boolean).join(`
34
+
35
+ ---
36
+
37
+ `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Ea(u,1)).join(`
38
+
39
+ ---
40
+
41
+ `);c+=`
42
+
43
+ ---
44
+
45
+ `+d}return c}function Pa(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 Ma(e,s){const n=await rd(s,e);return n||null}async function Oh(e){const s=Qt()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await od(e)?!0:Ti(e)}function Lh(){return id()}function Ta(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 Hn=e=>{const s=[],n=r=>{r.children.forEach(o=>{s.push(o.session.id),n(o)})};return n(e),s};function Bh(e,s){const[n,r]=i.useState(!1),[o,a]=i.useState(!0),l=e.session,c=i.useMemo(()=>Hn(e).length,[e]),d=i.useCallback(async b=>{const h=[];let g=0;for(const m of b)try{if(!s)throw new Error("Session directory is required for export");const v=[],x=m.session.title||"Untitled Sub-agent",I=typeof m.session.agent=="string"?m.session.agent:void 0,w=await d(m.children);g+=w.skipped,h.push({title:x,agent:I,records:v,children:w.children})}catch{g+=Hn(m).length+1}return{children:h,skipped:g}},[s]),u=i.useCallback(b=>{b<=0||ie.warning(b===1?`Exported session, but skipped ${b} sub-agent task that could not be loaded.`:`Exported session, but skipped ${b} sub-agent tasks that could not be loaded.`)},[]),f=i.useCallback(async b=>{if(!s){ie.error("Nothing to export");return}const h=[];if(h.length===0){ie.error("Nothing to export");return}let g,m=0;if(b&&e.children.length>0){const w=await d(e.children);g=w.children,m=w.skipped}const v=Da(h,l.title??null,g),x=Ta(l.title??null),I=await Ma(v,x);if(I){ie.success("Session exported",{action:{label:Lh(),onClick:()=>{Oh(I).then(w=>{w||ie.error("Failed to reveal path")})}}}),u(m);return}Pa(v,x),ie.success("Session exported"),u(m)},[d,e.children,l.title,s,u]),p=i.useCallback(async()=>{if(e.children.length>0){a(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:n,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,descendantCount:c,handleExportSession:p,doExportSession:f}}const _h=(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},lt=zs()((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 f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const b of f)l.delete(b);d===n&&(d=null)}else{for(const b of f)l.add(b);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),f=o.indexOf(r);if(u<0||f<0)return;const[p,b]=u<=f?[u,f]:[f,u],h=o.slice(p,b+1),g=_h(h,l),v=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of g)v.add(x);e({selectedIds:v,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}))}})),ei=e=>Ae(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),zh=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},Rn=e=>e.menuOpenSessionId??zh(e),En=(e,s,n)=>s?n.has(e.node.session.id)?!0:Jt(e.node,s):!1,Hr=(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(Hr(e.children[l],s.children[l],n,r,o))return!0;return!1},$h=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Hr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Hr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},Gh=(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.allowQuickArchiveAction!==s.allowQuickArchiveAction||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.nodeStructureKey!==s.nodeStructureKey||ei(e.node)!==ei(s.node)||!Uh(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&ja(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&$h(e,s)||e.editingId!==s.editingId&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(Jt(e.node,e.copiedSessionId)||Jt(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Rn(e),r=Rn(s);if(Jt(e.node,n)||Jt(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=Rn(e),r=Rn(s);if(Jt(e.node,n)||Jt(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.handleDeleteSession===s.handleDeleteSession&&e.handleRestoreSession===s.handleRestoreSession&&e.renderSessionNode===s.renderSessionNode};function Kh({node:e,groupDirectory:s,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:a,expansionKey:l,hasSessionSearchQuery:c}){const d=e.session,u=Ae(d.directory??null)??Ae(s??null),f=Ee(z=>z.currentSessionId===d.id),p=Ii(u),b=hc(u),h=ht(i.useCallback(z=>{if(r?.projectLabel||!n)return null;const Q=z.projects.find(te=>te.id===n);return Q?Q.label?.trim()||Os(Ae(Q.path)??Q.path,null)||Q.path:null},[n,r?.projectLabel])),g=r?.projectLabel??(h?Qn(h):null),m=e.worktree,v=r?.branchLabel??m?.branch??(p&&p!=="HEAD"?p:null),x=v,I=b===!0||!!(v||m),w=e.children.length,A=d.agent;i.useMemo(()=>{const z=m?.branch?.trim()||v?.trim(),Q=Ae(m?.path??u);return z&&Q?Ca():null},[v,u,m]);const j=ka(),N=void 0,C=i.useMemo(()=>null,[j]),y=n??u??null,k=lt(z=>z.enabled),E=lt(i.useCallback(z=>z.selectedIds.has(d.id),[d.id])),M=lt(z=>z.toggleSelected),B=lt(z=>z.setRange),K=Ri(d.id)?.type??"idle",V=K==="busy"||K==="retry",L=pc(d.id,V),T=is(d),P=e.children.length>0,U=mc(o,u,d.id),se=c?!0:a.has(l),G=gc(d.id)>0,Ie=d.time?.updated||d.time?.created||Date.now(),ee=Nd(Ie),Te=i.useMemo(()=>ya(e.forkColorId),[e.forkColorId]),_e=i.useMemo(()=>Cf(e.forkColorId,{active:f||E}),[e.forkColorId,f,E]),q=r?.globalSession&&!f&&!E?"var(--surface-elevated)":null;return{session:d,sessionDirectory:u,isActive:f,tooltipProjectLabel:g,tooltipBranchLabel:x,isGitRepo:I,subtaskCount:w,agentName:A,prSummary:j,prIconColor:N,prStatusLabel:C,selectionScopeKey:y,selectionModeEnabled:k,isRowSelected:E,toggleRowSelected:M,setRowRange:B,isStreaming:V,hasActivityDuration:L,sessionTitle:T,hasChildren:P,isPinnedSession:U,isExpanded:se,needsAttention:G,sessionCompactUpdatedLabel:ee,forkSolid:Te,rowBackground:_e??q}}function Wh(e){Dt("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,editingId:f,setEditingId:p,editTitle:b,setEditTitle:h,handleSaveEdit:g,handleCancelEdit:m,toggleParent:v,handleSessionSelect:x,handleSessionDoubleClick:I,togglePinnedSession:w,handleShareSession:A,copiedSessionId:j,handleCopyShareUrl:N,handleCopySessionId:C,handleUnshareSession:y,openSidebarMenuKey:k,setOpenSidebarMenuKey:E,renamingFolderId:M,getFoldersForScope:B,getSessionFolderId:_,removeSessionFromFolder:K,addSessionToFolder:V,createFolderAndStartRename:L,handleDeleteSession:T,handleRestoreSession:P,alwaysShowActions:U,allowQuickArchiveAction:se,renderSessionNode:W,secondaryMeta:G,renderContext:Ie="project",subtreeContainsEditing:ee,menuOpenSessionId:Te,childRenderExtrasFor:_e}=e,q=i.useMemo(()=>Fi(),[]),F=!a&&se,z=i.useRef(!1),Q=i.useRef(f);Q.current=f;const te=i.useRef(null),Ce=i.useRef(g);Ce.current=g;const[ge,xe]=i.useState(b),re=i.useRef(ge);re.current=ge;const oe=i.useRef(null),H=i.useRef(null),Be=`${Ie}:${a?"archived":"active"}:${s.session.id}`,{session:O,sessionDirectory:Z,isActive:he,tooltipProjectLabel:ue,tooltipBranchLabel:me,isGitRepo:Oe,subtaskCount:ve,agentName:X,prSummary:pe,selectionScopeKey:de,selectionModeEnabled:ke,isRowSelected:He,toggleRowSelected:We,setRowRange:Se,isStreaming:ne,hasActivityDuration:Fe,sessionTitle:De,hasChildren:kt,isPinnedSession:Ze,isExpanded:Xe,needsAttention:Kt,sessionCompactUpdatedLabel:wt,forkSolid:Zt,rowBackground:ot}=Kh({node:s,groupDirectory:r,projectId:o,secondaryMeta:G,pinnedSessionIds:l,expandedParents:c,expansionKey:Be,hasSessionSearchQuery:d}),{exportDialogOpen:et,setExportDialogOpen:it,exportIncludeSubtasks:vt,setExportIncludeSubtasks:bt,descendantCount:Wt,handleExportSession:St,doExportSession:ye}=Bh(s,Z),[Pe,je]=i.useState(!1),Le=i.useCallback(()=>{Z&&on("desktop_open_session_mini_chat_window",{sessionId:O.id,directory:Z,apiBaseUrl:Er(),clientToken:Rr()}).catch(ce=>{console.warn("[session-sidebar] failed to open mini chat window",ce)})},[O.id,Z]);i.useEffect(()=>{if(f!==O.id)return;const ce=st=>{const xt=st.target?.closest?.(`[data-session-rename-form="${CSS.escape(O.id)}"]`);H.current&&!xt&&Ce.current(re.current)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[f,O.id]),i.useLayoutEffect(()=>{if(f!==O.id){oe.current===O.id&&(oe.current=null);return}oe.current!==O.id&&(oe.current=O.id,xe(b))},[f,b,O.id]);const Ye=!ne&&Kt&&!he,ct=ne&&Fe,At=Ze,Ot=t.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),es=At?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:Ot}):null,pt=kt?t.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),v(Be)},onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),ce.stopPropagation(),v(Be))},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":Xe?"Collapse subsessions":"Expand subsessions",children:Xe?t.jsx(R,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(R,{name:"arrow-right-s",className:"h-3 w-3"})}):null,qe=ce=>{if(!ce&&te.current){const{id:st,title:tt}=te.current;te.current=null,p(st),h(tt)}},ts=ce=>{je(ce)},mt=ce=>{ce.preventDefault(),ce.stopPropagation()},Lt=ce=>{ce.preventDefault(),ce.stopPropagation()},Bt=ce=>{ce.preventDefault(),ce.stopPropagation(),E(null),T(O,{archivedBucket:a})},$s=ce=>{ce.preventDefault(),ce.stopPropagation(),E(null),T(O,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Nt=ce=>{if(z.current){z.current=!1;return}if(ke){if(ce?.preventDefault(),ce?.stopPropagation(),ce?.shiftKey){const tt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(at=>at.getAttribute("data-session-row")).filter(at=>typeof at=="string"&&at.length>0),xt=lt.getState().anchorId,ds=new Map;ds.set(O.id,Hn(s)),Se(xt,O.id,tt,de,ds);return}We(O.id,de,Hn(s));return}ce?.currentTarget&&Dh(ce.currentTarget),x(O.id,Z)},Gs=ce=>{ce.defaultPrevented||ce.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Nt(ce)},It=ce=>{(ce.button===2||ce.button===0&&ce.ctrlKey&&!ke)&&(z.current=!0)},cs={session:O,sessionTitle:De,sessionDirectory:Z,isPinnedSession:Ze,archivedBucket:a,isElectron:q,renamingFolderId:M,editingIdRef:Q,pendingRenameRef:te,handleCopySessionId:C,togglePinnedSession:w,handleExportSession:St,handleOpenMiniChatWindow:Le,handleDeleteSession:T,handleRestoreSession:P},dt=t.jsx(Eh,{...cs});return t.jsxs(i.Fragment,{children:[t.jsx(Hf,{sessionId:O.id,sessionDirectory:Z??null,sessionTitle:De,children:t.jsxs($i,{open:Pe,onOpenChange:ts,onOpenChangeComplete:qe,children:[t.jsxs(Gi,{render:t.jsx("div",{"data-session-row":O.id,"data-session-scope":de??"","data-session-archived":a?"1":"0","data-fork-color":Zt?s.forkColorId:void 0,"data-global-session":G?.globalSession?"1":void 0,onClick:Gs,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...ot?{backgroundColor:ot}:void 0},className:$("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!ot&&n>0?"bg-secondary/30 hover:bg-interactive-hover":ot?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!ot&&he&&!He&&"bg-interactive-selection",!ot&&He&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[pt,es,f===O.id?t.jsxs("form",{ref:H,"data-session-rename-form":O.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:ce=>ce.stopPropagation(),onMouseDown:ce=>ce.stopPropagation(),onSubmit:ce=>{ce.preventDefault(),g(ge)},children:[t.jsx("input",{value:ge,onChange:ce=>xe(ce.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:ce=>{ce.stopPropagation(),ce.key==="Escape"&&m()}}),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(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:m,"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(R,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:It,onClick:ce=>Nt(ce),onDoubleClick:ce=>{ce.stopPropagation(),I(O.id,De)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:$("block min-w-0 flex-1 truncate font-normal typography-ui-label",Kt?"text-foreground":"text-foreground/90"),children:Fn(De,u)})}),G?.showFolderLabel&&ue||me||Oe||pe||ve>0||X&&X!=="default"||ct?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:[G?.showFolderLabel&&ue?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:ue}):null,me?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(R,{name:"git-branch",className:$("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:me})]}):Oe?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(R,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,ve>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(R,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:ve})]}):null,X&&X!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:X}):null,ct?t.jsx(Id,{sessionId:O.id,running:ne,className:"text-muted-foreground/70"}):null]}):null]})]}),Ze?t.jsx(R,{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:$("flex items-center justify-end",F&&(U||Pe)?"opacity-0":F?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:ne?t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):Ye?t.jsx(Rd,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:wt})}),F?t.jsx("div",{className:$("absolute inset-0 flex items-center justify-end",U||Pe?"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(Nh,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:mt,onMouseDown:Lt,onArchive:Bt,onDelete:$s})}):null]})]}),dt]})}),kt&&Xe?s.children.map(ce=>{const st=_e?_e(ce):{subtreeContainsEditing:ee,menuOpenSessionId:Te,nodeStructureKey:""};return t.jsx(i.Fragment,{children:W(ce,n+1,Z??r,o,a,G?.globalSession?{globalSession:!0}:void 0,Ie,st)},ce.session.id)}):null,t.jsx(Ih,{open:et,onOpenChange:it,descendantCount:Wt,exportIncludeSubtasks:vt,setExportIncludeSubtasks:bt,onExport:ye})]},O.id)}const Hh=i.memo(Wh,Gh),Yh=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx($t,{open:e,onOpenChange:s,children:t.jsx(Gt,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ps,{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(of,{project:n,onIdentitySave:r}):null})})})});function Fa(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(Ss,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>n(!s),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":!s,children:[s?t.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(R,{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:r,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:()=>{o()},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:a})]})]})}function qh(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=c=>is(c);return t.jsx($t,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(ls,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be permanently deleted.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be archived.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`"${s?.session?l(s.session):"Untitled Session"}" will be permanently deleted.`:`"${s?.session?l(s.session):"Untitled Session"}" will be archived.`})]}),t.jsx(Fa,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:s?.archivedBucket?"Delete":"Archive"})]})})}function Qh(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($t,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:d}),t.jsx(ls,{children:u})]}),t.jsx(Fa,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:l?"Delete":"Archive"})]})})}function Vh(e){const{value:s,setValue:n,onConfirm:r}=e,{git:o}=Us(),[a,l]=i.useState(null),[c,d]=i.useState(!1),[u,f]=i.useState(!1),[p,b]=i.useState(!1),h=s?.worktree.path??null;i.useEffect(()=>{let j=!1;return l(null),d(!1),f(!1),b(!1),!s||!h?()=>{j=!0}:(o.getGitStatus(h).then(N=>{if(!j){if(typeof N?.isClean!="boolean"){d(!0);return}l(N)}}).catch(()=>{j||d(!0)}),()=>{j=!0})},[o,s,h]);const g=a?.isClean===!1,m=(a?.ahead??0)>0,v=m&&!s?.worktree.branch,x=s?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",I=!!(s&&a&&!c&&!s.hasActiveSession&&(!g&&!v||u)&&!p),w=s?.worktree.branch||s?.worktree.name||s?.worktree.path||"",A=async()=>{if(I){b(!0);try{await r({force:g})}finally{b(!1)}}};return t.jsx($t,{open:!!s,onOpenChange:j=>{!j&&!p&&n(null)},children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:"Close worktree?"}),t.jsx(ls,{children:`Closing "${w}" removes its worktree directory. ${x}`})]}),c?t.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[t.jsx(R,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):a===null?t.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,s?.hasActiveSession?t.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,g?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(Cr,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,m?t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:a?.ahead===1?`This worktree has 1 unpushed commit. ${x}`:`This worktree has ${a?.ahead} unpushed commits. ${x}`}),v?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(Cr,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,t.jsxs(Ss,{className:"sm:justify-end",children:[t.jsx(Me,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),t.jsx(Me,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!I,children:p?"Closing…":"Close worktree"})]})]})})}function Jh(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx($t,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:"Delete folder?"}),t.jsx(ls,{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(Ss,{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 Xh=({updateDialogOpen:e,setUpdateDialogOpen:s,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:a,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:b,confirmDeleteFolder:h,closeWorktreeConfirm:g,setCloseWorktreeConfirm:m,confirmCloseWorktree:v,bulkDeleteConfirm:x,setBulkDeleteConfirm:I,confirmBulkDelete:w})=>t.jsxs(t.Fragment,{children:[t.jsx(ca,{open:e,onOpenChange:s,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),t.jsx(Yh,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:a}),t.jsx(qh,{value:l,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),t.jsx(Jh,{value:p,setValue:b,onConfirm:h}),t.jsx(Vh,{value:g,setValue:m,onConfirm:v}),t.jsx(Qh,{value:x,setValue:I,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:w})]}),Zh=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=Ae(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return nn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=Ae(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(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},ep=e=>{let s=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(s+=r.sessions.length);return s},tp=e=>{const s=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);s.set(n.project.id,r)}return s},sp=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),np=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),rp=(e,s)=>{const n=new Map;for(const r of e){const o=new Set;for(const a of r.groups){if(a.isArchivedBucket)continue;if(a.sessions.some(c=>s.has(c.session.id))&&a.directory){const c=Ae(a.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},op=e=>e.map(s=>s.groups.some(n=>n.isArchivedBucket)?{...s,groups:s.groups.filter(n=>!n.isArchivedBucket)}:s),ip=(e,s,n,r)=>{if(!n)return s;const o=e.find(c=>c.project.id===n);if(!o)return[];const a=Ae(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&Ae(c.directory)===a);return l?[{...o,groups:[l]}]:[]},ap=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=Qn(o.project.label?.trim()||Os(o.project.normalizedPath,s)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==a?l.branch:null,d={projectLabel:a,branchLabel:c},u=f=>{f.forEach(p=>{const b=o.project.normalizedPath.length,h=r.get(p.session.id)??-1;b<h||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:d}),r.set(p.session.id,b),p.children.length>0&&u(p.children))})};u(l.sessions)})}),n};function lp({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const d=i.useMemo(()=>ap(e,a),[e,a]),u=i.useMemo(()=>op(s),[s]),f=i.useMemo(()=>ip(n,u,r,o),[n,u,r,o]),p=i.useMemo(()=>ep(e),[e]),b=i.useMemo(()=>tp(e),[e]),h=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?sp(x,l):!1},[l,e]),g=i.useMemo(()=>rp(e,l),[l,e]),m=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?np(x,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:b,hasActiveSessionByProject:h,activeDirectoriesByProject:g,hasUnseenByProject:m}}const cp=({selectedCount:e,archivedBucket:s,onRestore:n,onDelete:r,onDone:o})=>{const a=s?"Delete":"Archive",l="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return t.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[t.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),t.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[s?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(R,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:$("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":a,children:t.jsx(R,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:t.jsx(R,{name:"close",className:"h-4 w-4"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},dp=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:p}=e,b=lt(T=>T.enabled),h=lt(T=>T.selectedIds.size),g=h>0,m=lt(T=>T.selectedIds),v=lt(T=>T.scopeKey),x=i.useCallback(()=>{lt.getState().toggleMode()},[]),I=i.useCallback(()=>{lt.getState().disable()},[]),w=i.useMemo(()=>{if(!g||typeof document>"u")return!1;let T=!1,P=!1;for(const U of m){const se=document.querySelectorAll(`[data-session-row="${CSS.escape(U)}"]`);for(const W of se)W.getAttribute("data-session-archived")==="1"?P=!0:T=!0}return P&&!T},[g,m]),A=i.useMemo(()=>{if(v)return v;if(!g||typeof document>"u")return null;for(const T of m){const U=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(U&&U.length>0)return U}return null},[g,m,v]),j=i.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(P=>P.scopeKey):[A]},[A,o]),N=i.useMemo(()=>j.flatMap(T=>r[T]??[]),[r,j]),C=i.useCallback(T=>{for(const P of j)if((r[P]??[]).some(U=>U.id===T))return P;return null},[r,j]),y=i.useMemo(()=>{if(!g)return!1;for(const T of j)for(const P of r[T]??[])for(const U of P.sessionIds)if(m.has(U))return!0;return!1},[r,j,g,m]),k=i.useCallback((T,P)=>{const U=Array.from(m);for(const se of j)se!==T&&l(se,U);a(T,P,U)},[a,l,m,j]),E=i.useCallback(T=>{if(!g)return;const P=C(T);P&&k(P,T)},[g,k,C]),M=i.useCallback(()=>{const T=j[0];if(!T||!g)return;const P=c(T);P&&k(T,P.id)},[c,g,k,j]),B=i.useCallback(()=>{if(!g)return;const T=Array.from(m);for(const P of j)l(P,T)},[l,m,j,g]),_=i.useCallback(async()=>{const T=Array.from(m);if(T.length!==0){if(w){const{deletedIds:P,failedIds:U}=await f(T);P.length>0&&ie.success(P.length===1?`Deleted ${P.length} session`:`Deleted ${P.length} sessions`),U.length>0&&ie.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`)}else{const{archivedIds:P,failedIds:U}=await d(T);P.length>0&&ie.success(P.length===1?`Archived ${P.length} session`:`Archived ${P.length} sessions`),U.length>0&&ie.error(U.length===1?`Failed to archive ${U.length} session`:`Failed to archive ${U.length} sessions`)}lt.getState().clear()}},[d,w,f,m]),K=i.useCallback(()=>{if(!g)return;const T=m.size;if(!n){_();return}p({sessionCount:T,archivedBucket:w})},[w,_,m,n,p,g]),V=i.useCallback(async()=>{if(!g||!w)return;const T=Array.from(m),{restoredIds:P,failedIds:U}=await u(T);P.length>0&&ie.success(P.length===1?`Restored ${P.length} session`:`Restored ${P.length} sessions`),U.length>0&&ie.error(U.length===1?`Failed to restore ${U.length} session`:`Failed to restore ${U.length} sessions`),lt.getState().clear()},[w,g,m,u]),L=i.useCallback(async()=>{p(null),await _()},[_]);return i.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),P=U=>{if(s)return;const se=U.target;if(se&&(se.tagName==="INPUT"||se.tagName==="TEXTAREA"||se.isContentEditable))return;const W=T?U.metaKey:U.ctrlKey;if(U.key==="Escape"){U.preventDefault(),lt.getState().disable();return}if(W&&U.key==="Backspace"){U.preventDefault(),K();return}if(W&&(U.key==="a"||U.key==="A")){const G=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(G.length===0)return;U.preventDefault();const ee=lt.getState().scopeKey??G[0]?.getAttribute("data-session-scope")??null,Te=q=>ee?q.getAttribute("data-session-scope")===ee:!0,_e=G.filter(Te).map(q=>q.getAttribute("data-session-row")).filter(q=>typeof q=="string"&&q.length>0);if(_e.length===0)return;lt.getState().replaceAll(_e,ee||null)}};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[K,s,b]),{selectionModeEnabled:b,hasSelection:g,selectedIdsSize:h,bulkScopeIsArchived:w,derivedSelectionScope:A,bulkScopeFolders:N,bulkCanRemoveFromFolder:y,handleToggleSelectionMode:x,handleExitSelectionMode:I,handleBulkMoveToFolder:E,handleBulkCreateFolderAndMove:M,handleBulkRemoveFromFolder:B,handleBulkDelete:K,handleBulkRestore:V,confirmBulkDelete:L}},up=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},fp=zs()(Zr(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:up})),ti="oc.sessions.projectCollapse",si="oc.sessions.groupOrder",ni="oc.sessions.groupCollapse",ri="oc.sessions.activeSessionByProject",oi="oc.sessions.expandedParents.v3",hp=new Set,ur=[],jt=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},pp=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Ir("react.session_sidebar_render"),Dt("ui.session_sidebar.render"),Dt(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Dt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=i.useState(!1),[u,f]=i.useState(""),p=i.useRef(null),b=i.useRef(null),[h,g]=i.useState(null),[m,v]=i.useState(""),[x,I]=i.useState(null),[w,A]=i.useState(new Set),j=i.useMemo(()=>Cn(),[]),[N,C]=i.useState(new Set),y=Ns(S=>S.selectedSpaceId),k=Ns(S=>S.selectedWorktreePath),[E,M]=i.useState(new Map),[B,_]=i.useState(new Map),[K,V]=i.useState(!1),[L,T]=i.useState(null),[P,U]=i.useState(null),[se,W]=i.useState(""),[G,Ie]=i.useState(null),[ee,Te]=i.useState(null),[_e,q]=i.useState(null),[F,z]=i.useState(null),Q=Do(S=>S.ids),te=bc(i.useCallback(S=>e?S.rankById:Ni,[e])),Ce=nn(S=>e?xc(S.catalog):"",void 0,"catalog"),ge=i.useMemo(()=>Ce?Ce.split("|"):ur,[Ce]),xe=i.useMemo(()=>new Set(ge),[ge]),re=yc(Tr(S=>e?Object.entries(S.index.session.unseenCount).filter(([,Y])=>Y>0).map(([Y])=>Y).sort():ur)),oe=i.useMemo(()=>new Set(re),[re]),H=Do(S=>S.toggle),[be,Be]=i.useState(()=>{try{const S=Cn().getItem(ni);if(!S)return new Set;const Y=JSON.parse(S);return new Set(Array.isArray(Y)?Y.filter(J=>typeof J=="string"):[])}catch{return new Set}}),[O,Z]=i.useState(()=>{try{const S=Cn().getItem(si);if(!S)return new Map;const Y=JSON.parse(S),J=new Map;return Object.entries(Y).forEach(([Re,Ke])=>{Array.isArray(Ke)&&J.set(Re,Ke.filter(Qe=>typeof Qe=="string"))}),J}catch{return new Map}}),he=i.useMemo(()=>{try{const S=Cn().getItem(ri);if(!S)return new Map;const Y=JSON.parse(S),J=new Map;return Object.entries(Y).forEach(([Re,Ke])=>{typeof Ke=="string"&&Ke.length>0&&J.set(Re,Ke)}),J}catch{return new Map}},[]),ue=i.useCallback(S=>{try{j.setItem(ri,JSON.stringify(Object.fromEntries(S.entries())))}catch{}},[j]),[me,Oe]=i.useState(new Map),ve=i.useRef(0),X=Fs(S=>S.homeDirectory),pe=Fs(S=>S.currentDirectory),de=ht(S=>S.projects),ke=ht(S=>S.activeProjectId),He=ht(S=>S.removeProject),We=ht(S=>S.setActiveProjectIdOnly),Se=ht(S=>S.updateProjectMeta),ne=ht(S=>S.reorderProjects),Fe=le(S=>S.setActiveMainTab),De=le(S=>S.setSettingsDialogOpen),kt=le(S=>S.setSettingsPage),Ze=le(S=>S.toggleHelpDialog),Xe=le(S=>S.setSessionSwitcherOpen),Kt=le(S=>S.setArchivePageOpen),wt=le(S=>S.showDeletionDialog),Zt=le(S=>S.setShowDeletionDialog),ot=wc(u,120),et=i.useMemo(()=>ot.trim().toLowerCase(),[ot]),it=et.length>0,vt=ft(S=>S.collapsedFolderIds),bt=ft(S=>S.foldersMap),Wt=ft(S=>S.getFoldersForScope),St=ft(S=>S.createFolder),ye=ft(S=>S.renameFolder),Pe=ft(S=>S.deleteFolder),je=ft(S=>S.addSessionToFolder),Le=ft(S=>S.addSessionsToFolder),Ye=ft(S=>S.removeSessionFromFolder),ct=ft(S=>S.removeSessionsFromFolders),At=ft(S=>S.toggleFolderCollapse),Ot=ft(S=>S.getSessionFolderId);Nf({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchContainerRef:p});const es=vc(e),{git:pt}=Us(),qe=nn(S=>S.connection,void 0,"chrome"),ts=nn(S=>{for(const Y of S.catalog.listStatusByDirectory.values())if(Y==="ready")return!0;return!1},void 0,"catalog"),mt=Ar({archived:!1}),Lt=Ar({archived:!0}),Bt=Ee(S=>S.setCurrentSession),$s=Ee(S=>S.updateSessionTitle),Nt=Ee(S=>S.shareSession),Gs=Ee(S=>S.unshareSession),It=Nr(S=>S.projects),cs=Nr(S=>S.refreshProject),dt=i.useMemo(()=>Sc(de,{projects:It}),[de,It]),ce=i.useMemo(()=>{const S=new Map;for(const Y of de){const J=Ae(Y.path);if(!J)continue;const Re=It.get(J)?.error;Re&&S.set(J,Re)}return S},[de,It]);i.useEffect(()=>{if(!y)return;const S=de.find(J=>J.id===y);if(!S){Ns.getState().clearSpaceSelection();return}if(!k)return;(dt.get(Ae(S.path)??S.path)??[]).some(J=>Ae(J.path)===Ae(k))||(Ns.getState().clearSelectedWorktree(),ie.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[dt,de,y,k]);const st=Ee(S=>S.openNewSessionDraft),tt=i.useCallback(S=>{le.getState().closeMainSurfaces(),st(S),r?.()},[r,st]),xt=Pn(Tr(S=>({checkForUpdates:S.checkForUpdates,available:S.available,runtimeType:S.runtimeType,info:S.info,downloading:S.downloading,downloaded:S.downloaded,progress:S.progress,error:S.error,downloadUpdate:S.downloadUpdate,restartToUpdate:S.restartToUpdate}))),ds=i.useMemo(()=>jc(de,dt,{includeWorktrees:!0}),[dt,de]),at=i.useMemo(()=>mt.filter(S=>zf(S,ds,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:X})),[mt,X,ds]),bn=i.useMemo(()=>[...at,...Lt],[Lt,at]),Ks=Jr(),xn=i.useMemo(()=>`${Ks}|${de.map(S=>`${S.id}:${Ae(S.path)??""}`).join("|")}`,[de,Ks]),Ws=i.useMemo(()=>{const S=new Set;let Y=!0;for(const J of de){const Re=Ae(J.path);if(!Re)continue;const Ke=It.get(Re)?.status??"idle";Ke==="failed"&&S.add(Re),(Ke==="idle"||Ke==="loading")&&(Y=!1)}return{complete:Y,unresolved:S}},[de,It]),us=Ws.complete?xn:null,Vn=!Ws.complete,Ht=Ws.unresolved,{isTablet:Hs}=_s(),Cs=s||Hs,Jn=Af({mobileVariant:s,isTablet:Hs}),{buildGroupSearchText:Xn,filterSessionNodesForSearch:Ys,buildGroupedSessions:qs}=kf({homeDirectory:X,pinnedSessionIds:Q,sessionOrderRanks:te}),{scheduleCollapsedProjectsPersist:yn}=Rf({safeStorage:j,keys:{sessionExpanded:oi,projectCollapse:ti,groupOrder:si,groupCollapse:ni},groupOrderByProject:O,collapsedGroups:be,setExpandedParents:A,setCollapsedProjects:C}),D=i.useMemo(()=>Cc(at,Q,te),[Q,te,at]),ae=i.useMemo(()=>D.map(S=>S.id).join("|"),[D]),we=i.useRef(null),Ue=i.useMemo(()=>{const S=we.current;if(S&&S.signature===ae)return S.map;const Y=new Map(D.map((J,Re)=>[J.id,Re]));return we.current={signature:ae,map:Y},Y},[D,ae]),ut=i.useMemo(()=>{const S=new Map;return D.forEach(Y=>{const J=Y.parentID;if(!J)return;const Re=S.get(J)??[];Re.push(Y),S.set(J,Re)}),S.forEach(Y=>Y.sort((J,Re)=>Qr(J,Re,Q,te))),S},[D,Q,te]),Ve=i.useMemo(()=>t.jsx(bs,{icon:"chat-new",mobileVariant:s,onClick:()=>tt(),children:"New session"}),[s,tt]),Qs=i.useMemo(()=>de.find(S=>S.id===x)??null,[de,x]),Yt=i.useCallback(S=>{x&&Se(x,{label:S.label,defaultModel:S.defaultModel??null})},[x,Se]),_a=i.useCallback(()=>{const S=Pn.getState();if(S.available&&S.info){V(!0);return}xt.checkForUpdates().then(()=>{const{available:Y,error:J}=Pn.getState();if(J){ie.error("Failed to check for updates",{description:J});return}if(!Y){ie.success("You are on the latest version");return}V(!0)})},[xt]),ks=kc(),ao=i.useCallback(()=>{if(s&&Xe(!1),r?.(),ks?.openSettings){ks.openSettings();return}De(!0)},[ks,s,r,Xe,De]),Ua=xt.available&&(xt.runtimeType==="desktop"||xt.runtimeType==="web"),za=Ee(S=>S.deleteSession),lo=Ee(S=>S.deleteSessions),$a=Ee(S=>S.archiveSession),co=Ee(S=>S.archiveSessions),Ga=Ee(S=>S.unarchiveSession),Ka=Ee(S=>S.unarchiveSessions),{copiedSessionId:Wa,handleSessionSelect:Ha,handleSessionDoubleClick:Ya,handleSaveEdit:qa,handleCancelEdit:Qa,handleShareSession:Va,handleCopyShareUrl:Ja,handleCopySessionId:Xa,handleUnshareSession:Za,handleDeleteSession:el,handleRestoreSession:tl,confirmDeleteSession:sl}=If({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:Fe,setSessionSwitcherOpen:Xe,setCurrentSession:Bt,updateSessionTitle:$s,shareSession:Nt,unshareSession:Gs,deleteSession:za,deleteSessions:lo,archiveSession:$a,archiveSessions:co,unarchiveSession:Ga,childrenMap:ut,showDeletionDialog:wt,setDeleteSessionConfirm:Ie,deleteSessionConfirm:G,setEditingId:g,setEditTitle:v,editingId:h,editTitle:m}),nl=i.useCallback(()=>{if(!ee)return;const{scopeKey:S,folderId:Y}=ee;Te(null),Pe(S,Y)},[ee,Pe]),uo=i.useCallback(()=>{xs.requestDirectoryDialog()},[]),rl=i.useCallback(S=>{A(Y=>{const J=Ed(Y,S);try{j.setItem(oi,JSON.stringify(Array.from(J)))}catch{}return J})},[j]),fo=i.useCallback((S,Y)=>{if(!S)return null;Y&&vt.has(Y)&&At(Y);const J=St(S,"New folder",Y);return U(J.id),W(J.name),J},[vt,At,St]),Vs=jt(Ha),ol=jt(Ya),il=jt(qa),al=jt(Qa),ll=jt(Va),cl=jt(Ja),dl=jt(Xa),ul=jt(Za),fl=jt(el),hl=jt(tl),Zn=jt(fo),ho=i.useCallback((S,Y)=>{_(J=>{const Re=new Map(J);return Re.set(S,Y+7),Re})},[]),wn=i.useCallback(S=>{_(Y=>{if(!Y.has(S))return Y;const J=new Map(Y);return J.delete(S),J})},[]),po=i.useCallback(S=>{_(Y=>{let J=!1;const Re=new Map(Y),Ke=`${S}:`;for(const Qe of Re.keys())Qe.startsWith(Ke)&&(Re.delete(Qe),J=!0);return J?Re:Y})},[]),pl=i.useCallback(S=>{ve.current=Date.now()+150,po(S),C(Y=>{const J=new Set(Y);J.has(S)?J.delete(S):J.add(S);try{j.setItem(ti,JSON.stringify(Array.from(J)))}catch{}return yn(J),J})},[po,j,yn]),ss=i.useMemo(()=>de.map(S=>({...S,normalizedPath:Ae(S.path)})).filter(S=>!!S.normalizedPath),[de]),ml=i.useMemo(()=>ss.map(S=>S.normalizedPath),[ss]),mo=Ac(e?ml:ur);Ff({enabled:e,normalizedProjects:ss,gitRepoStatus:mo,setProjectRepoStatus:M,setProjectRootBranches:Oe});const go=i.useMemo(()=>Gf(at,ss,dt,Lt),[Lt,dt,ss,at]);_f({enabled:e,hasAuthoritativeGlobalSessions:ts,sessions:bn});const{getSessionsForProject:gl,getArchivedSessionsForProject:bl}=Of({ownership:go});bf({enabled:e,normalizedProjects:ss,ownership:go,hasAuthoritativeGlobalSessions:ts,isWorktreeTopologyLoading:Vn,unresolvedWorktreeProjectPaths:Ht,foldersMap:bt,createFolder:St,addSessionToFolder:je});const bo=i.useRef(!1);ke&&E.has(ke)&&(bo.current=!!E.get(ke));const xl=fp(S=>S.showArchivedSessions),er=ht(S=>S.manualProjectOrder),xo=i.useRef(new Set),vn=Dd(xo.current,w,"project");xo.current=vn;const tr={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Hs,catalogSessions:mt,archivedSessions:Lt,projects:de,activeProjectId:ke,manualProjectOrder:er,currentDirectory:pe,availableWorktreesByProject:dt,pinnedSessionIds:Q,sessionOrderRanks:te,foldersMap:bt,collapsedFolderIds:vt,gitBranches:es,gitRepoStatus:mo,updateStore:xt,showArchivedSessions:xl,projectRepoStatus:E,projectRootBranches:me,resolvedWorktreeTopologyKey:us,unresolvedWorktreeProjectPaths:Ht,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:h,editTitle:m,editingProjectDialogId:x,expandedParents:w,collapsedProjects:N,visibleSessionCountByGroup:B,updateDialogOpen:K,openSidebarMenuKey:L,renamingFolderId:P,renameFolderDraft:se,deleteSessionConfirm:G,deleteFolderConfirm:ee,bulkDeleteConfirm:F,collapsedGroups:be},yo=i.useRef(null),wo=yo.current;if(wo){let S=!1;for(const Y of Object.keys(tr))Object.is(wo[Y],tr[Y])||(Dt(`ui.session_sidebar.source.${Y}`),S=!0);S||Dt("ui.session_sidebar.source.parent_or_context")}yo.current=tr;const yl=i.useMemo(()=>{const S=new Map(er.map((Y,J)=>[Y,J]));return[...ss].sort((Y,J)=>(S.get(Y.id)??1/0)-(S.get(J.id)??1/0))},[er,ss]),{projectSections:Rt,groupSearchDataByGroup:vo,sectionsForRender:wl,flatSectionsForRender:sr,searchMatchCount:vl}=yf({normalizedProjects:yl,getSessionsForProject:gl,getArchivedSessionsForProject:bl,availableWorktreesByProject:dt,projectRepoStatus:E,projectRootBranches:me,lastRepoStatus:bo.current,buildGroupedSessions:qs,hasSessionSearchQuery:it,normalizedSessionSearchQuery:et,filterSessionNodesForSearch:Ys,buildGroupSearchText:Xn,foldersMap:bt}),Sn=i.useMemo(()=>{const S=at.filter(J=>qn(rn(J),X));if(S.length===0)return null;const Y=qs(S,"~",[],null,!1).map(J=>it?{...J,sessions:Ys(J.sessions,et)}:J).filter(J=>J.sessions.length>0&&!J.isArchivedBucket);return Y.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Y}},[qs,Ys,it,X,et,at]),Sl=i.useMemo(()=>{if(!it||!Sn)return 0;const S=Y=>Y.reduce((J,Re)=>J+1+S(Re.children),0);return Sn.groups.reduce((Y,J)=>Y+S(J.sessions),0)},[Sn,it]),jl=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:Cl}=xf(O),So=i.useRef(!1);i.useEffect(()=>{if(So.current||Rt.length===0)return;const S=Rt.flatMap(Y=>Y.groups.filter(J=>J.isArchivedBucket).map(J=>`${Y.project.id}:${J.id}`));S.length>0&&Be(Y=>new Set([...Y,...S])),So.current=!0},[Rt]);const{filteredSectionsForSidebarRender:kl,totalSessionCount:Al,sessionCountByProject:Nl,hasActiveSessionByProject:Il,activeDirectoriesByProject:Js,hasUnseenByProject:Rl}=lp({projectSections:Rt,flatSectionsForRender:sr,sectionsForRender:wl,selectedSpaceId:y,selectedWorktreePath:k,homeDirectory:X,activeSessionIdSet:xe,unreadSessionIdSet:oe}),nr=i.useCallback(S=>{if(Ns.getState().selectSpace(S),!S)return;We(S);const Y=Rt.find(Ke=>Ke.project.id===S),J=Y?.groups.find(Ke=>Ke.isMain),Re=J?.sessions[0]?.session;Re?Vs(Re.id,J?.directory??Y?.project.normalizedPath??null,{keepPanelOpen:!0}):Y&&tt({selectedProjectId:S,directoryOverride:Y.project.normalizedPath})},[tt,Rt,We,Vs]),El=s?"flex size-10 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",Dl=s?"size-5":"h-4.5 w-4.5",jn=jt((S,Y=0,J,Re,Ke=!1,Qe,_t="project",As)=>t.jsx(Hh,{node:S,depth:Y,groupDirectory:J,projectId:Re,archivedBucket:Ke,pinnedSessionIds:Q,expandedParents:vn,hasSessionSearchQuery:it,normalizedSessionSearchQuery:et,editingId:h,setEditingId:g,editTitle:m,setEditTitle:v,handleSaveEdit:il,handleCancelEdit:al,toggleParent:rl,handleSessionSelect:Vs,handleSessionDoubleClick:ol,togglePinnedSession:H,handleShareSession:ll,copiedSessionId:Wa,handleCopyShareUrl:cl,handleCopySessionId:dl,handleUnshareSession:ul,openSidebarMenuKey:L,setOpenSidebarMenuKey:T,renamingFolderId:P,getFoldersForScope:Wt,getSessionFolderId:Ot,removeSessionFromFolder:Ye,addSessionToFolder:je,createFolderAndStartRename:Zn,handleDeleteSession:fl,handleRestoreSession:hl,mobileVariant:s,alwaysShowActions:Cs,allowQuickArchiveAction:Jn,renderSessionNode:jn,secondaryMeta:Qe,renderContext:_t,subtreeContainsEditing:As?.subtreeContainsEditing??hp,menuOpenSessionId:As?.menuOpenSessionId??null,nodeStructureKey:As?.nodeStructureKey??"",childRenderExtrasFor:As?.childRenderExtrasFor})),Pl=i.useMemo(()=>{const S=new Map;return sr.forEach(Y=>{const J=Y.groups.find(Re=>!Re.isArchivedBucket);J?.folderScopes&&J.folderScopes.length>0&&S.set(Y.project.id,J.folderScopes)}),S},[sr]),Ml=i.useCallback((S,Y)=>{const J=[];return Y.forEach(Re=>{Re.isArchivedBucket||(J.push(Re.directory),Re.folderScopes?.forEach(Ke=>J.push(Ke.directory)))}),t.jsx(Zh,{directories:J})},[]),jo=i.useCallback(S=>{wn(S),Be(Y=>{const J=new Set(Y);return J.has(S)?J.delete(S):J.add(S),J})},[wn]),Tl=i.useCallback((S,Y,J,Re,Ke,Qe,_t)=>t.jsx(lh,{group:S,groupKey:Y,projectId:J,hideGroupLabel:Re,dragHandleProps:Ke,compactBodyPadding:Qe,hasSessionSearchQuery:it,normalizedSessionSearchQuery:et,groupSearchDataByGroup:vo,visibleSessionCount:B.get(Y),collapsedGroups:be,hideDirectoryControls:a,collapsedFolderIds:vt,toggleFolderCollapse:At,renameFolder:ye,deleteFolder:Pe,showDeletionDialog:wt,setDeleteFolderConfirm:Te,renderSessionNode:jn,showMoreGroupSessions:ho,resetGroupSessionLimit:wn,mobileVariant:s,alwaysShowActions:Cs,activeProjectId:ke,setActiveProjectIdOnly:We,setActiveMainTab:Fe,setSessionSwitcherOpen:Xe,openNewSessionDraft:tt,addSessionToFolder:je,createFolderAndStartRename:Zn,renamingFolderId:P,renameFolderDraft:se,setRenameFolderDraft:W,setRenamingFolderId:U,pinnedSessionIds:Q,expandedParents:vn,sessionOrderIndex:Ue,editingId:h,editTitle:m,openSidebarMenuKey:L,activeActivitySessionIds:xe,unreadActivitySessionIds:oe,onToggleCollapsedGroup:jo,scrollContainerRef:_t}),[it,et,vo,B,be,a,vt,At,ye,Pe,wt,jn,ho,wn,s,Cs,ke,We,Fe,Xe,tt,je,Zn,P,se,Q,vn,Ue,h,m,L,xe,oe,jo]),Co=!!(P||h||x),{selectionModeEnabled:rr,hasSelection:ko,selectedIdsSize:Fl,bulkScopeIsArchived:Ol,derivedSelectionScope:Ll,bulkScopeFolders:Bl,bulkCanRemoveFromFolder:_l,handleToggleSelectionMode:Ul,handleExitSelectionMode:zl,handleBulkMoveToFolder:$l,handleBulkCreateFolderAndMove:Gl,handleBulkRemoveFromFolder:Kl,handleBulkDelete:Wl,handleBulkRestore:Hl,confirmBulkDelete:Yl}=dp({isInlineEditing:Co,showDeletionDialog:wt,foldersMap:bt,folderScopesByProject:Pl,addSessionsToFolder:Le,removeSessionsFromFolders:ct,createFolderAndStartRename:fo,archiveSessions:co,unarchiveSessions:Ka,deleteSessions:lo,setBulkDeleteConfirm:z}),Ao=i.useCallback(()=>{le.getState().closeMainSurfaces(),Fe("chat"),s&&Xe(!1),st(),r?.()},[s,r,st,Fe,Xe]),ql=i.useCallback((S,Y)=>{const J=de.find(Qe=>Qe.id===S);if(!J)return;const Re=Ae(Y.path)?.toLowerCase(),Ke=!!(Re&&Js.get(S)?.has(Re));q({projectId:S,projectPath:J.path,worktree:Y,hasActiveSession:Ke})},[Js,de]),Ql=i.useCallback(async({force:S})=>{const Y=_e;if(!Y)return;const J=Ae(Y.worktree.path)?.toLowerCase();if(!!(J&&Js.get(Y.projectId)?.has(J))){q({...Y,hasActiveSession:!0}),ie.warning("Stop the active session before closing this worktree.");return}if(!pt.deleteGitWorktree){ie.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await pt.deleteGitWorktree(Y.projectPath,{directory:Y.worktree.path,force:S}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Qe=await cs(Y.projectPath,pt);const _t=Ae(Y.worktree.path);Qe!==null&&_t!==null&&Qe.some(Jl=>Ae(Jl.path)===_t)&&(Qe=await cs(Y.projectPath,pt));const As=_t!==null&&Ae(pe)===_t,Vl=_t!==null&&y===Y.projectId&&Ae(k)===_t;(As||Vl)&&nr(Y.projectId),q(null),Qe===null?ie.warning("Worktree closed, but the sidebar could not be refreshed."):ie.success("Worktree closed.")}catch(Ke){const Qe=Ke instanceof Error?Ke.message:"Try again.";ie.error("Failed to close worktree.",{description:Qe})}},[Js,_e,pe,pt,nr,cs,y,k]);return t.jsx(Nc,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:p,className:$("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(vf,{projectSections:Rt,activeProjectId:ke,initialActiveSessionByProject:he,persistActiveSessionByProject:ue,handleSessionSelect:Vs,mobileVariant:s,openNewSessionDraft:st,setActiveMainTab:Fe,setSessionSwitcherOpen:Xe}),!a&&!s?t.jsx(dh,{onNewSession:Ao,showSidebarToggle:!0}):null,t.jsx(ch,{hideDirectoryControls:a,handleOpenDirectoryDialog:uo,onOpenArchive:()=>{s&&Xe(!1),Kt(!0)},onOpenSettings:s?ao:void 0,onOpenInstances:s?ks?.openInstances:void 0,instanceLabel:s?ks?.instanceLabel:void 0,onOpenUpdate:s?ks?.openUpdate:void 0,headerActionIconClass:Dl,headerActionButtonClass:El,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:it,searchMatchCount:vl+(y===null?Sl:0),selectionModeEnabled:rr,onToggleSelectionMode:Ul,mobileVariant:s}),qe==="error"||qe==="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&&Rt.length>0?t.jsx(hh,{projects:Rt.map(S=>S.project),selectedProjectId:y,selectedWorktreePath:k,worktreesByProject:dt,worktreeErrorsByProject:ce,onSelectProject:nr,onSelectWorktree:(S,Y)=>{Ns.getState().selectWorktree(S,Y),We(S);const Ke=Rt.find(Qe=>Qe.project.id===S)?.groups.find(Qe=>Ae(Qe.directory)===Ae(Y))?.sessions[0]?.session;Ke?Vs(Ke.id,Y,{keepPanelOpen:!0}):tt({selectedProjectId:S,directoryOverride:Y})},onCloseWorktree:ql,onOpenDirectoryDialog:uo,onOpenProjectEditDialog:I,onRemoveProject:He,totalSessionCount:Al,getSessionCountForProject:S=>Nl.get(S)??0,hasActiveSessionByProject:Il,activeDirectoriesByProject:Js,hasUnseenByProject:Rl,homeDirectory:X,mobileVariant:s}):null,t.jsx(bh,{sectionsForRender:kl,allFoldersOnlySection:y===null?Sn:null,projectSections:Rt,activeProjectId:ke,showOnlyMainWorkspace:l,hasSessionSearchQuery:it,emptyState:Ve,searchEmptyState:jl,isAllFoldersView:y===null,pinnedSessionIds:Q,renderSessionNode:jn,renderGroupSessions:Tl,homeDirectory:X,collapsedProjects:N,hideDirectoryControls:a,projectRepoStatus:E,mobileVariant:s,alwaysShowActions:Cs,toggleProject:pl,setActiveProjectIdOnly:We,setActiveMainTab:Fe,setSessionSwitcherOpen:Xe,openNewSessionDraft:tt,openProjectEditDialog:I,removeProject:He,reorderProjects:ne,getOrderedGroups:Cl,setGroupOrderByProject:Z,renderProjectStatusIndicator:Ml,openSidebarMenuKey:L,setOpenSidebarMenuKey:T,isInlineEditing:Co}),s&&!(rr&&ko)?t.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:[t.jsx(xa,{variant:"mobile"}),t.jsx(Me,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Ao,"aria-label":"New session",children:t.jsx(R,{name:"chat-new",className:"size-4"})})]}):null,rr&&ko?t.jsx(cp,{selectedCount:Fl,scopeKey:Ll,scopeFolders:Bl,archivedBucket:Ol,onMoveToFolder:$l,onCreateFolderAndMove:Gl,onRemoveFromFolder:Kl,canRemoveFromFolder:_l,onRestore:Hl,onDelete:Wl,onDone:zl}):null,s?null:t.jsx(ph,{onOpenSettings:ao,onOpenShortcuts:Ze,onOpenAbout:()=>{kt("about"),De(!0)},onOpenUpdate:_a,showRuntimeButtons:!0,showUpdateButton:Ua}),t.jsx(Xh,{updateDialogOpen:K,setUpdateDialogOpen:V,updateStore:xt,editingProject:Qs,setEditingProjectDialogId:I,handleSaveProjectEdit:Yt,deleteSessionConfirm:G,setDeleteSessionConfirm:Ie,showDeletionDialog:wt,setShowDeletionDialog:Zt,confirmDeleteSession:sl,deleteFolderConfirm:ee,setDeleteFolderConfirm:Te,confirmDeleteFolder:nl,closeWorktreeConfirm:_e,setCloseWorktreeConfirm:q,confirmCloseWorktree:Ql,bulkDeleteConfirm:F,setBulkDeleteConfirm:z,confirmBulkDelete:Yl})]})})},Ng=i.memo(pp),ii=6,Ct=.18,en=1.2,tn=.38,On=48,mp=(e,s)=>e==="left"?s<0:s>0,Ig=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Rg=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,ai=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),Eg=e=>{const{side:s,dx:n,dy:r,dt:o,progress:a,isDragging:l}=e,c=n/Math.max(1,o);if(l){const d=s==="left"?c<-Ct:c>Ct,u=s==="left"?c>Ct:c<-Ct;return d||!u&&a<tn}return Math.abs(n)>=On&&Math.abs(r)<=Math.abs(n)*en&&mp(s,n)},gp=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:o,progress:a}=e,l=r/Math.max(1,o);return s==="left"?n?l<-Ct?!1:l>Ct?!0:a>tn:l>Ct?!0:l<-Ct?!1:a>tn:n?l>Ct?!1:l<-Ct?!0:a>tn:l<-Ct?!0:l>Ct?!1:a>tn},bp='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',xp=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(bp);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let o=e;for(;o&&o!==s;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const a=getComputedStyle(o).overflowX;if(a==="auto"||a==="scroll")return!0}o=o.parentElement}return!1},Ln=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Yr=512*1024,yp=new TextEncoder,wp=new TextDecoder,fr=e=>{const s=yp.encode(e);if(s.byteLength<=Yr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Yr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:wp.decode(r),byteLength:r.byteLength}},Is=(e,s)=>`${e}\0${s}`,hr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},vp="terminal-store";let li=!1,ci=0;const Dn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ci+=1,`tab-${Date.now().toString(36)}-${ci.toString(36)}`),pr=e=>typeof e=="object"&&e!==null,Sp=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function nt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const jp=/^Terminal(?: (\d+))?$/,Cp=e=>{let s=0;for(const n of e){const r=jp.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}`},mr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),gr=e=>({tabs:[e],activeTabId:e.id}),Et=(e,s)=>e.tabs.findIndex(n=>n.id===s);let br=null,xr=null;const kp=e=>{if(xr&&br?.sessions===e.sessions&&br.nextTabId===e.nextTabId)return xr;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 br={sessions:e.sessions,nextTabId:e.nextTabId},xr=s,s},Ap=()=>{const e=vd(()=>ad());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))}},fe=zs()(Bi(Zr((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=nt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=Dn(),c=mr(l,"Terminal");return a.set(r,gr(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=nt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=nt(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(Is(nt(n),r))??Ln,createTab:n=>{const r=nt(n);if(!r)return"tab-invalid";const o=Dn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Cp(c?.tabs??[]),f=mr(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,gr(f)),{sessions:l,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Et(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=nt(n),l=o.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=Et(u,r);if(f<0||u.tabs[f]?.label===l)return c;const p=[...u.tabs];return p[f]={...p[f],label:l},d.set(a,{...u,tabs:p}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Et(d,r);if(u<0)return l;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return l;const p=[...d.tabs];return p[u]={...p[u],iconKey:f},c.set(a,{...d,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Et(c,r);if(d<0)return a;const u=c.tabs.filter(m=>m.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,m])=>!(m.directory===o&&m.tabId===r))),p=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,b=Is(o,r),h=a.buffers.has(b)?hr(a.buffers,m=>m===b):null;if(u.length===0){const m=Dn(),v=mr(m,"Terminal");return l.set(o,gr(v)),{sessions:l,nextTabId:a.nextTabId+1,...h?{buffers:h}:{},...p?{projectActionRuns:f}:{}}}let g=c.activeTabId;return c.activeTabId===r&&(g=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:g}),{sessions:l,...h?{buffers:h}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Et(d,r);if(u<0)return l;const f=d.tabs[u],p=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,h={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},g=Is(a,r),m=p&&l.buffers.has(g)?hr(l.buffers,x=>x===g):null,v=[...d.tabs];return v[u]=h,c.set(a,{...d,tabs:v}),{sessions:c,...m?{buffers:m}:{}}})},setTabLifecycle:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Et(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(a,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Et(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(a,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=nt(n);e(c=>{const d=c.sessions.get(l);if(!d||Et(d,r)<0)return c;const u=Is(l,r),f=c.buffers.get(u)??Ln;if(f.lastSequence>a)return c;const p=fr(o);if(f.lastSequence===a&&f.byteLength===p.byteLength&&f.chunks.map(g=>g.data).join("")===p.text)return c;const b=c.nextChunkId,h=new Map(c.buffers);return h.set(u,{chunks:p.text?[{id:b,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:a}),{buffers:h,nextChunkId:p.text?b+1:b}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=nt(n);e(d=>{const u=d.sessions.get(c);if(!u||Et(u,r)<0)return d;const f=Is(c,r),p=d.buffers.get(f)??Ln;if(a!==void 0&&a<=p.lastSequence)return d;const b=d.nextChunkId,h=fr(o),g=l!==void 0&&l!==o?fr(l).text:void 0,m={id:b,data:h.text,...g!==void 0?{replayData:g}:{},byteLength:h.byteLength},v=[...p.chunks,m];let x=p.byteLength+m.byteLength;for(;x>Yr&&v.length>1;){const w=v.shift();if(!w)break;x-=w.byteLength}const I=new Map(d.buffers);return I.set(f,{chunks:v,byteLength:x,lastSequence:a??p.lastSequence}),{buffers:I,nextChunkId:b+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=nt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const f=Et(u,r);if(f<0)return c;const p=u.tabs[f],b=a.autoOpened??p.previewAutoOpened,h=a.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===b&&p.previewUrlLocked===h)return c;const g=[...u.tabs];return g[f]={...p,previewUrl:o,previewAutoOpened:b,previewUrlLocked:h},d.set(l,{...u,tabs:g}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Et(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},l.set(o,{...c,tabs:f}),{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=nt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Is(r,""),c=hr(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:vp,storage:Ap(),partialize:kp,merge:(e,s)=>{if(!pr(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"||!pr(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],p=[],b=new Map;for(const v of f){if(!pr(v))continue;const x=typeof v.id=="string"?v.id:null;if(!x)continue;const I=Sp(x);I!==null&&(o=Math.max(o,I));const w=I===null?x:Dn();b.set(x,w),p.push({id:w,label:typeof v.label=="string"?v.label:"Terminal",iconKey:typeof v.iconKey=="string"?v.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof v.createdAt=="number"?v.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const h=typeof u.activeTabId=="string"?u.activeTabId:null,g=h?b.get(h)??h:null,m=g?p.some(v=>v.id===g):!1;r.set(d,{tabs:p,activeTabId:m?g:p[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"&&!li){li=!0;const e=fe.persist,s=()=>{fe.getState().hasHydrated||fe.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Np(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 yr(e,s,n){const o=`${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",cursorInactiveStyle:"none",fontSize:s,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,selectionInactiveBackground:n.selectionInactiveBackground,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}}}const Ip=(e,s)=>{const n=`${e??""} ${s??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},Rp=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),Ep=(e,s,n)=>{if(e.altKey)return null;const r=Rp(e);return s==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":null},sn=e=>typeof e=="string"&&e.trim().length>0;async function di(e){return sn(e)?(await ws(e)).ok:!1}async function Dp(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Pp=(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))}},Mp=(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 Tp=null;const Fp=()=>Tp??=Promise.all([os(()=>import("./vendor-xterm-xterm-CrXqRur4.js"),__vite__mapDeps([112,113])),os(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,s])=>({Xterm:e,Fit:s})),Op=2e3,Lp=()=>{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,Op))]).then(()=>{})},Bp=(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))}},Oa=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:f=!0},p)=>{const b=i.useRef(null),h=i.useRef(null),g=i.useRef(null),m=i.useRef(n),v=i.useRef(r),x=i.useRef(o),I=i.useRef(a),w=i.useRef(l),A=i.useRef(null),j=i.useRef(null),N=i.useRef(null),C=i.useRef(""),y=i.useRef(!1),k=i.useRef(0),E=i.useRef(f),M=i.useRef(!1),[B,_]=i.useState(0),[K,V]=i.useState(0),[L,T]=i.useState(!1),[P,U]=i.useState(!1);m.current=n,v.current=r,E.current=f,x.current=o,I.current=a,w.current=l,i.useLayoutEffect(()=>{const q=b.current;if(!q)return;const F=Bp(q,a,l);j.current=F,F&&v.current(F.cols,F.rows)},[a,l]);const se=i.useCallback(()=>{const q=b.current,F=h.current;if(!q||!F||!g.current||!E.current)return;const z=q.getBoundingClientRect();if(!(z.width<24||z.height<24))try{g.current.fit();const Q={cols:F.cols,rows:F.rows};(!A.current||A.current.cols!==Q.cols||A.current.rows!==Q.rows)&&(A.current=Q,v.current(Q.cols,Q.rows)),M.current||(M.current=!0,_(te=>te+1))}catch{}},[]),W=i.useCallback(()=>{if(y.current||!C.current||!h.current)return;const q=h.current,F=C.current;if(C.current="",!F)return;y.current=!0;const z=k.current;q.write(F,()=>{h.current!==q||k.current!==z||(y.current=!1,C.current&&W())})},[]),G=i.useCallback(()=>{N.current=null,C.current="",y.current=!1,k.current+=1;const q=h.current;if(!q){V(F=>F+1);return}try{q.reset()}catch{V(F=>F+1)}},[]),Ie=i.useCallback(q=>{q?.preventDefault(),U(sn(h.current?.getSelection())),T(!0)},[]),ee=i.useCallback(q=>{q.stopPropagation();const F=h.current,z=F?.getSelection()??"";F?.focus(),sn(z)&&di(z)},[]),Te=i.useCallback(q=>{q.stopPropagation();const F=h.current;F?.focus(),Dp().then(z=>{z&&h.current===F&&F&&F.paste(z)})},[]),_e=i.useCallback(q=>{q.stopPropagation();const F=h.current;F?.focus();try{F?.selectAll()}catch{}U(sn(F?.getSelection()))},[]);return i.useEffect(()=>{const q=b.current;if(!q)return;let F=!1,z=null,Q=null,te=null,Ce=null,ge=[];const xe=()=>{z&&E.current&&(z.options.cursorBlink=!0)},re=be=>{be.relatedTarget instanceof Node&&q.contains(be.relatedTarget)||z&&(z.options.cursorBlink=!1)},oe=()=>{z&&E.current&&q.contains(document.activeElement)&&(z.options.cursorBlink=!0)},H=()=>{z&&(z.options.cursorBlink=!1)};return q.addEventListener("focusin",xe),q.addEventListener("focusout",re),window.addEventListener("focus",oe),window.addEventListener("blur",H),Promise.all([Fp(),Lp()]).then(([{Xterm:be,Fit:Be}])=>{if(F)return;const O=x.current,Z=I.current,he=w.current;z=new be.Terminal({...yr(Z,he,O),...j.current??{}});const ue=new Be.FitAddon;z.loadAddon(ue),z.open(q),h.current=z,g.current=ue;const me=typeof navigator>"u"?"other":Ip(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Oe=z;z.attachCustomKeyEventHandler(ve=>{if(ve.type!=="keydown")return!0;const X=Oe.getSelection(),pe=Ep({key:ve.key,code:ve.code,ctrlKey:ve.ctrlKey,shiftKey:ve.shiftKey,metaKey:ve.metaKey,altKey:ve.altKey},me,sn(X));return pe==="copy"?(di(X),!1):pe!=="ignore"}),ge=[z.onData(ve=>m.current(ve))],Q=new ResizeObserver(()=>{te&&clearTimeout(te),te=setTimeout(se,80)}),Q.observe(q),se(),Ce=requestAnimationFrame(se)}),()=>{F=!0;const be=document.activeElement;be instanceof HTMLElement&&q.contains(be)&&(be.blur(),window.Capacitor?.getPlatform?.()==="android"&&os(async()=>{const{Keyboard:O}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:O}},__vite__mapDeps([114,115])).then(({Keyboard:O})=>O.hide()).catch(()=>{})),Q?.disconnect(),te&&clearTimeout(te),Ce!==null&&cancelAnimationFrame(Ce),q.removeEventListener("focusin",xe),q.removeEventListener("focusout",re),window.removeEventListener("focus",oe),window.removeEventListener("blur",H),ge.forEach(Be=>Be.dispose()),z?.dispose(),h.current=null,g.current=null,A.current=null,N.current=null,C.current="",y.current=!1,k.current+=1,M.current=!1}},[se,K]),i.useEffect(()=>{const q=h.current;q&&(q.options.theme=yr(a,l,o).theme,q.options.fontFamily=yr(a,l,o).fontFamily,q.options.fontSize=l)},[a,l,o]),i.useEffect(()=>{const q=h.current,F=b.current;!q||!F||(q.options.cursorBlink=f&&document.hasFocus()&&F.contains(document.activeElement))},[f,B]),i.useEffect(()=>{if(!h.current)return;if(s.length===0){N.current!==null&&G();return}const F=N.current;let z=-1;if(F!==null){for(let Ce=s.length-1;Ce>=0;Ce-=1){const ge=s[Ce].id;if(ge===F){z=Ce;break}if(ge<F)break}if(z<0){G();return}}const Q=z<0,te=z>=0?s.slice(z+1):s;C.current+=te.map(Ce=>Q?Ce.replayData??Ce.data:Ce.data).join(""),N.current=s.at(-1)?.id??null,W()},[s,W,B,G]),i.useEffect(()=>{if(!u||!f)return;const q=requestAnimationFrame(()=>h.current?.focus());return()=>cancelAnimationFrame(q)},[u,f,B,e]),i.useEffect(()=>{const q=b.current,F=h.current;if(!d||!q||!F)return;let z=null,Q=null,te="idle",Ce=0,ge=0,xe=0,re=0,oe=null;const H=Math.max(12,l+2),be=()=>{window.Capacitor?.getPlatform?.()==="android"&&os(async()=>{const{Keyboard:pe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:pe}},__vite__mapDeps([114,115])).then(({Keyboard:pe})=>pe.show()).catch(()=>{})},Be=()=>{Q&&(clearTimeout(Q),Q=null)},O=(X,pe)=>{const de=q.querySelector("canvas");return de?Pp(X,pe,de.getBoundingClientRect(),F.cols,F.rows):null},Z=(X,pe)=>{const de=q.querySelector("canvas");if(!de)return;const ke=de.getBoundingClientRect(),He=ke.left+(pe.column+.5)/F.cols*ke.width,We=ke.top+(pe.row+.5)/F.rows*ke.height;de.dispatchEvent(new MouseEvent(X,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:He,clientY:We}))},he=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ue=X=>{X.pointerType!=="touch"||z!==null||(z=X.pointerId,te="pending",Ce=X.clientX,ge=X.clientY,xe=X.clientY,re=0,oe=null,q.setPointerCapture(X.pointerId),Q=setTimeout(()=>{if(Q=null,z!==X.pointerId||te!=="pending")return;const pe=O(Ce,ge);if(!pe)return;const de=F.buffer.active,ke=Math.max(0,de.length-F.rows-de.viewportY+pe.row),He=de.getLine(ke),We=Array.from({length:F.cols},(Fe,De)=>He?.getCell(De)?.getChars()??""),Se=Mp(We,pe.column),ne={column:Se.startColumn,row:pe.row};oe={column:Se.endColumn,row:pe.row},te="selecting",Z("mousedown",ne),Z("mousemove",oe)},350))},me=X=>{if(z!==X.pointerId)return;if(te==="selecting"){const ke=O(X.clientX,X.clientY);ke&&(!oe||ke.column!==oe.column||ke.row!==oe.row)&&(oe=ke,Z("mousemove",ke)),X.cancelable&&X.preventDefault();return}if(te==="pending"){if(Math.hypot(X.clientX-Ce,X.clientY-ge)<8)return;Be(),te="scrolling"}if(te!=="scrolling")return;const pe=xe-X.clientY;xe=X.clientY,re+=pe;const de=Math.trunc(re/H);de&&(F.scrollLines(de),re-=de*H),X.cancelable&&X.preventDefault()},Oe=X=>{if(z!==X.pointerId)return;const pe=te==="pending",de=te==="selecting";Be(),q.hasPointerCapture(X.pointerId)&&q.releasePointerCapture(X.pointerId),z=null,te="idle",de&&he(),pe&&(F.focus(),be())},ve=X=>{if(z!==X.pointerId)return;const pe=te==="selecting";Be(),q.hasPointerCapture(X.pointerId)&&q.releasePointerCapture(X.pointerId),z=null,te="idle",pe&&he()};return q.addEventListener("pointerdown",ue),q.addEventListener("pointermove",me,{passive:!1}),q.addEventListener("pointerup",Oe),q.addEventListener("pointercancel",ve),()=>{Be(),q.removeEventListener("pointerdown",ue),q.removeEventListener("pointermove",me),q.removeEventListener("pointerup",Oe),q.removeEventListener("pointercancel",ve)}},[d,l,B]),i.useImperativeHandle(p,()=>({focus:()=>h.current?.focus(),fit:se,getSelection:()=>{const q=h.current,F=q?.getSelectionPosition(),z=q?.getSelection()??"";return!F||!z.trim()?null:{text:z,startLine:F.start.y+1,endLine:F.end.y+1}}}),[se]),t.jsxs(so,{open:L,onOpenChange:T,children:[t.jsx(no,{render:t.jsx("div",{ref:b,"data-terminal-owner":"main",className:$("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:Ie})}),t.jsxs(ro,{className:"min-w-[180px]",children:[t.jsxs(Ms,{disabled:!P,onClick:ee,children:[t.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),t.jsxs(Ms,{onClick:Te,children:[t.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),t.jsx(ga,{}),t.jsx(Ms,{onClick:_e,children:"Select All"})]})]})});Oa.displayName="TerminalViewport";const _p=({directory:e,tabId:s,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:a,terminal:l,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:p,onInput:b,controllerRef:h})=>{const g=fe(w=>e&&s?w.getBuffer(e,s).chunks:Ln.chunks),m=i.useRef(null),v=o&&a,x=i.useCallback(w=>{m.current=w,h&&(h.current=o?w:h.current),!o&&h&&h.current===w&&(h.current=null)},[h,o]);i.useEffect(()=>{if(!o||!a)return;const w=requestAnimationFrame(()=>{m.current?.fit()});return()=>cancelAnimationFrame(w)},[o,a,r,n]);const I=i.useCallback((w,A)=>{if(!o)return;const j=p.current;(!j||j.cols!==w||j.rows!==A)&&(p.current={cols:w,rows:A}),n&&l.resize({sessionId:n,cols:w,rows:A}).catch(()=>{})},[o,p,n,l]);return t.jsx("div",{className:$("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:t.jsx(Oa,{ref:x,sessionKey:r,chunks:g,onInput:b,onResize:I,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:v,isVisible:v},r)})},Up=({items:e,activeId:s,onSelect:n,onClose:r,onCreate:o,disabled:a=!1})=>{const l=e.find(c=>c.id===s)??e[0]??null;return t.jsxs(Pt,{modal:!1,children:[t.jsx(Mt,{asChild:!0,children:t.jsxs("button",{type:"button",disabled:a,title:l?`Switch terminal, current: ${l.label}`:"Switch terminal","aria-label":l?`Switch terminal, current: ${l.label}`:"Switch terminal",className:$(vi({size:"sm"}),"min-w-0 max-w-full"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l?.icon??t.jsx(R,{name:"terminal",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:l?.label??"Terminal"})]}),t.jsx(R,{name:"arrow-down-s",className:"size-3.5 shrink-0"})]})}),t.jsxs(Tt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(l?.id??s);return t.jsxs(rt,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,t.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?t.jsx(R,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,t.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:t.jsx(R,{name:"close",className:"size-3"})})]},c.id)}),t.jsx(vs,{}),t.jsxs(rt,{onClick:o,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},zp=({isTouchTerminal:e,activeModifier:s,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const a=e?"lg":"xs",l=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return t.jsxs(t.Fragment,{children:[t.jsx(Me,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Me,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[t.jsx(R,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Me,{type:"button",size:a,variant:"chip","aria-pressed":s==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,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:a,variant:"chip","aria-pressed":s==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,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:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[t.jsx(R,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Me,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[t.jsx(R,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Me,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[t.jsx(R,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Me,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[t.jsx(R,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Me,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[t.jsx(R,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]})},$p="\x1B",Gp=new RegExp(`${$p}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Kp=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Wp=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Hp=/Serving HTTP on .*? port (\d{2,5})/i,Yp=new Set([".",",",";",":","!","?"]),qp=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(Yp.has(n)){s=s.slice(0,-1);continue}break}return s},ui=e=>{let s=qp(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},Qp=e=>{if(!e)return null;const s=e.replace(Gp,""),n=s.match(Hp);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(`
46
+ `);for(const o of r){if(!Wp.test(o))continue;const a=Array.from(o.matchAll(Kp));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(ui(c[1])).port}catch{return!1}});return ui((l??a[0])[1])}return null},Vp=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 Ft("/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)}},Jp={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Xp=(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 Jp[e]},La=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},Zp=(e,s)=>e&&(s==="ctrl"?La(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Ba={cols:80,rows:24},fi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class em{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(s,n,r,o){if(!r)return;const a=`${this.tail}${r}`.replace(/\r\n|\r/g,`
47
+ `),l=a.split(`
48
+ `),c=a.endsWith(`
49
+ `)?l.join(`
50
+ `):l.slice(0,-1).join(`
51
+ `);if(this.tail=a.endsWith(`
52
+ `)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=Qp(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Vp(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const p=fe.getState().getDirectoryState(s)?.tabs.find(b=>b.id===n);!p||p.previewUrlLocked||p.previewUrl===d||o(s,n,d,{locked:!1,autoOpened:!1})})}}const tm=(e,s)=>{if(s!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?La(o):null};function sm({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:b,tabs:h}){const g=fe(F=>F.ensureDirectory),m=fe(F=>F.setTabSessionId),v=fe(F=>F.setTabLifecycle),x=fe(F=>F.setConnecting),I=fe(F=>F.appendToBuffer),w=fe(F=>F.replaceBuffer),A=fe(F=>F.setTabPreviewUrl),[j,N]=i.useState(null),[C,y]=i.useState(!1),[k,E]=i.useState(!1),M=i.useRef(new Map),B=i.useRef(null),_=i.useRef(n),K=i.useRef(r),V=i.useRef(s),L=i.useRef(null),T=i.useRef(new Set),P=i.useRef(new Map),U=i.useRef(h),se=i.useRef(l),W=i.useRef(a),G=i.useRef(e);U.current=h,se.current=l,W.current=a,G.current=e;const Ie=i.useCallback(()=>{const F=_.current;F&&P.current.get(F)?.reset()},[]);i.useEffect(()=>{K.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),i.useEffect(()=>{_.current=n},[n]),i.useEffect(()=>{V.current=s},[s]);const ee=i.useCallback(()=>{for(const F of M.current.values())try{F()}catch{}M.current.clear(),B.current=null,E(!1)},[]);i.useEffect(()=>()=>{ee(),K.current=null},[ee]);const Te=i.useCallback((F,z,Q)=>{let te=P.current.get(z);te||(te=new em,P.current.set(z,te)),te.scan(F,z,Q,A)},[A]),_e=i.useCallback((F,z,Q)=>{if(M.current.has(Q)){B.current=Q;return}const te=To(),Ce=()=>To()===te&&V.current===F&&fe.getState().getDirectoryState(F)?.tabs.find(xe=>xe.id===z)?.terminalSessionId===Q,ge=e.connect(Q,{onEvent:xe=>{if(Ce())switch(xe.type){case"snapshot":{_.current===z&&K.current===Q?(x(F,z,!1),N(null),y(!1),E(!1),b()):x(F,z,!1),w(F,z,xe.data??"",xe.sequence??0),Te(F,z,xe.data??""),xe.status==="exited"&&v(F,z,"exited");break}case"reconnecting":{_.current===z&&(N(null),y(!1),E(!0));break}case"data":{xe.data&&(I(F,z,xe.data,xe.sequence,xe.replayData),Te(F,z,xe.data));break}case"exit":{const re=typeof xe.exitCode=="number"?xe.exitCode:null,oe=typeof xe.signal=="number"?xe.signal:null,be=!!fe.getState().getDirectoryState(F)?.tabs.find(Be=>Be.id===z)?.label?.startsWith("Action:");I(F,z,`\\r\\n[Process exited${re!==null?` with code ${re}`:""}${oe!==null?` (signal ${oe})`:""}]\\r\\n`),v(F,z,"exited"),_.current===z&&(x(F,z,!1),N(be?null:"Terminal session ended"),y(!1),E(!1));break}}},onError:(xe,re)=>{if(!Ce())return;const oe=_.current===z;if(!re){oe&&(N(null),y(!1));return}if(xe.code==="SESSION_NOT_FOUND"&&!fe.getState().getDirectoryState(F)?.tabs.find(be=>be.id===z)?.label?.startsWith("Action:")){oe&&(N(null),y(!1),x(F,z,!1),E(!1)),m(F,z,null),v(F,z,"idle");return}oe&&(E(!1),N(`Connection failed: ${xe.message}`),y(!0),x(F,z,!1),v(F,z,"exited"),m(F,z,null))}});M.current.set(Q,()=>ge.close()),B.current=Q},[I,b,w,Te,x,v,m,e]),q=i.useMemo(()=>h.map(F=>`${F.id}:${F.terminalSessionId??""}`).join(","),[h]);return i.useEffect(()=>{if(!l||!a||!s)return;const F=s,z=new Set;for(const Q of h)Q.terminalSessionId&&(z.add(Q.terminalSessionId),_e(F,Q.id,Q.terminalSessionId));for(const[Q,te]of M.current)if(!z.has(Q)){try{te()}catch{}M.current.delete(Q)}},[q,h,s,l,a,_e]),i.useEffect(()=>ld(()=>{if(!se.current||!W.current)return;const F=V.current;if(!F)return;const z=[];for(const te of U.current){if(!te.terminalSessionId)continue;fe.getState().getDirectoryState(F)?.tabs.find(ge=>ge.id===te.id)?.terminalSessionId===te.terminalSessionId&&z.push({id:te.id,terminalSessionId:te.terminalSessionId})}if(M.current.clear(),B.current=null,z.length===0)return;E(!0),N(null),y(!1);for(const te of z)_e(F,te.id,te.terminalSessionId);const Q=L.current;if(Q)for(const te of z)G.current.resize({sessionId:te.terminalSessionId,...Q}).catch(()=>{})}),[_e]),i.useEffect(()=>{let F=!1;if(!l||!a)return;if(!s){N(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const Q=s;if(!V.current||V.current!==Q)return;if(!fe.getState().getDirectoryState(Q)){g(Q);return}const Ce=fe.getState().getDirectoryState(Q);if(!Ce||Ce.tabs.length===0)return;const ge=Ce.activeTabId??Ce.tabs[0]?.id??null;if(!ge)return;const xe=Ce.tabs.find(O=>O.id===ge)??Ce.tabs[0],re=xe?.terminalSessionId??null,oe=xe?.lifecycle??"idle",H=!!xe?.label?.startsWith("Action:"),be=fe.getState().getBuffer(Q,ge),Be=be.byteLength>0||be.chunks.length>0;if(!re){if(oe==="exited"){x(Q,ge,!1);return}if(H&&Be){x(Q,ge,!1);return}const O=`${Q}\0${ge}`;if(T.current.has(O))return;const Z=L.current??Ba;T.current.add(O),N(null),y(!1),E(!1),x(Q,ge,!0);try{const he=await e.createSession({cwd:Q,sessionId:ge,cols:Z.cols,rows:Z.rows,shell:c,loginShell:d,...u.current});if(!fe.getState().getDirectoryState(Q)?.tabs.find(Oe=>Oe.id===ge)){try{await e.close(he.sessionId)}catch{}return}m(Q,ge,he.sessionId);const me=L.current;me&&(me.cols!==Z.cols||me.rows!==Z.rows)&&e.resize({sessionId:he.sessionId,...me}).catch(()=>{});return}catch(he){const ue=fe.getState().getDirectoryState(Q)?.tabs.find(me=>me.id===ge);if(!ue||ue.terminalSessionId||(x(Q,ge,!1),V.current!==Q||_.current!==ge))return;N(he instanceof Error?he.message:"Failed to start terminal session"),y(!0),E(!1);return}finally{T.current.delete(O)}}!re||F||(K.current=re)})(),()=>{F=!0}},[p,s,r,o,n,a,f,l,g,x,v,m,e,d,c,u]),{connectionError:j,setConnectionError:N,isFatalError:C,setIsFatalError:y,isReconnectPending:k,setIsReconnectPending:E,terminalIdRef:K,lastViewportSizeRef:L,directoryRef:V,activeTabIdRef:_,disconnectStream:ee,resetTerminalPreviewScan:Ie,startStream:_e}}function nm({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=i.useState(null),p=i.useRef(null),b=i.useCallback(()=>{d||p.current?.focus()},[d]),h=i.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[d]);i.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),i.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const g=i.useCallback(w=>{if(!w||n)return;let A=w,j=!1;u&&w.length>0&&(A=Zp(w,u),j=!0);const N=s.current;N&&(e.sendInput(N,A).catch(C=>{n||r(C instanceof Error?C.message:"Failed to send input")}),j&&(f(null),b()))},[u,b,n,r,e,s]),m=i.useCallback((w,A)=>{const j=l.current;if((!j||j.cols!==w||j.rows!==A)&&(l.current={cols:w,rows:A}),!a)return;const N=s.current;N&&e.resize({sessionId:N,cols:w,rows:A}).catch(()=>{})},[a,l,e,s]),v=i.useCallback(w=>{f(A=>A===w?null:w),b()},[b]),x=i.useCallback(w=>{const A=Xp(w,u);A&&(g(A),f(null),b())},[u,b,g]),I=i.useCallback(w=>{if(w.repeat)return;const A=w.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const j=A.length===1?A.toLowerCase():A;if(j in fi){w.preventDefault(),w.stopPropagation(),x(fi[j]);return}const N=tm(w,u);N&&(w.preventDefault(),w.stopPropagation(),g(N),f(null),b())},[u,b,x,g]);return i.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[u,I,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:b,focusTerminalWhenWindowActive:h,handleViewportInput:g,handleViewportResize:m,handleModifierToggle:v,handleMobileKeyPress:x}}function rm({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:b,setConnectionError:h,setIsFatalError:g,setIsReconnectPending:m}){const v=fe(B=>B.createTab),x=fe(B=>B.setActiveTab),I=fe(B=>B.closeTab),w=fe(B=>B.setTabSessionId),A=fe(B=>B.setTabLifecycle),[j,N]=i.useState(!1),C=i.useCallback(async()=>{if(!s||j)return;const B=fe.getState().getDirectoryState(s),_=n??B?.activeTabId??B?.tabs[0]?.id??null;if(!_)return;const K=B?.tabs.find(V=>V.id===_)?.terminalSessionId??null;if(!(!K||!e.restartSession)){N(!0),h(null),g(!1),m(!1),p();try{const V=c.current??Ba,L=await e.restartSession(K,{cwd:s,shell:o,loginShell:a,...V,...l.current});if(fe.getState().getDirectoryState(s)?.tabs.find(P=>P.id===_)?.terminalSessionId!==K||(w(s,_,L.sessionId),A(s,_,"running"),d.current!==s||u.current!==_))return;f.current=L.sessionId,b(s,_,L.sessionId)}catch(V){if(fe.getState().getDirectoryState(s)?.tabs.find(T=>T.id===_)?.terminalSessionId!==K||d.current!==s||u.current!==_)return;h(V instanceof Error?V.message:"Failed to restart terminal"),g(!1),m(!1),f.current=K,b(s,_,K)}finally{N(!1)}}},[n,u,d,s,r,j,c,p,h,g,m,A,w,b,e,l,f,a,o]),y=i.useCallback(async()=>{await C()},[C]),k=i.useCallback(()=>{if(!s)return;const B=v(s);x(s,B),h(null),g(!1),m(!1)},[v,s,x,h,g,m]),E=i.useCallback(B=>{s&&(x(s,B),h(null),g(!1),m(!1))},[s,x,h,g,m]),M=i.useCallback(B=>{if(!s)return;h(null),g(!1),m(!1);const _=fe.getState().getDirectoryState(s)?.tabs.find(K=>K.id===B)?.terminalSessionId;(async()=>{_&&await e.close(_),I(s,B)})().catch(K=>h(K instanceof Error?K.message:"Terminal session ended"))},[I,s,h,g,m,e]);return{isRestarting:j,handleRestart:C,handleHardRestart:y,handleCreateTab:k,handleSelectTab:E,handleCloseTab:M}}const Dg=({visible:e,onCloseView:s,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Us(),{currentTheme:a}=Ei(),l=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground};const{monoFont:c}=Ic(),d=le(ne=>ne.terminalFontSize),u=le(ne=>ne.terminalShell),f=le(ne=>ne.terminalLoginShells.includes(ne.terminalShell)),{isMobile:p,isTablet:b,hasTouchOnlyPointer:h}=_s(),g=p||b,m=(g||h)&&o.platform==="web",v=!0,x=le(ne=>ne.showTerminalQuickKeysOnDesktop),I=g||x,w=Ee(ne=>ne.currentSessionId),A=Ee(ne=>ne.newSessionDraft),j=w!==null||A?.open===!0,N=Rc()??null,C=fe(ne=>N?ne.sessions.get(N):void 0),y=fe(ne=>ne.hasHydrated),k=le(ne=>ne.openContextPreview),E=i.useMemo(()=>C?C.activeTabId??C.tabs[0]?.id??null:null,[C,v]),M=i.useMemo(()=>{if(C)return E?C.tabs.find(ne=>ne.id===E)??C.tabs[0]:C.tabs[0]},[C,E]),B=i.useMemo(()=>(C?.tabs??[]).map(ne=>({icon:(()=>{const Fe=ne.iconKey?ln[ne.iconKey]??"terminal":"terminal";return t.jsx(R,{name:Fe,className:"h-4 w-4"})})(),id:ne.id,label:ne.label,title:ne.label,closeLabel:"Close tab"})),[C?.tabs]),_=M?.terminalSessionId??null,K=M?.lifecycle??"idle",V=i.useMemo(()=>(C?.tabs??[]).map(ne=>({id:ne.id,terminalSessionId:ne.terminalSessionId,label:ne.label})),[C?.tabs]),L=M?.isConnecting??!1,T=M?.previewUrl??null,U=le(ne=>ne.activeMainTab)==="terminal",se=e??U,[W,G]=i.useState(se);i.useEffect(()=>{se&&G(!0)},[se]);const{connectionError:Ie,setConnectionError:ee,isFatalError:Te,setIsFatalError:_e,isReconnectPending:q,setIsReconnectPending:F,terminalIdRef:z,lastViewportSizeRef:Q,directoryRef:te,activeTabIdRef:Ce,resetTerminalPreviewScan:ge,startStream:xe}=sm({terminal:r,effectiveDirectory:N,activeTabId:E,terminalSessionId:_,terminalLifecycle:K,hasOpenedTerminalViewport:W,terminalHydrated:y,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:v,hasActiveContext:j,tabs:V,focusTerminalWhenWindowActive:()=>{!m&&typeof document<"u"&&document.hasFocus()&&oe.current?.focus()}}),{activeModifier:re,terminalControllerRef:oe,focusTerminalWhenWindowActive:H,handleViewportInput:be,handleModifierToggle:Be,handleMobileKeyPress:O}=nm({terminal:r,terminalIdRef:z,isReconnectPending:q,setConnectionError:ee,showQuickKeys:I,isTerminalVisible:se,lastViewportSizeRef:Q,terminalSessionId:_,useTouchTerminalInput:m}),{isRestarting:Z,handleRestart:he,handleHardRestart:ue,handleCreateTab:me,handleSelectTab:Oe,handleCloseTab:ve}=rm({terminal:r,effectiveDirectory:N,activeTabId:E,enableTabs:v,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:Q,directoryRef:te,activeTabIdRef:Ce,terminalIdRef:z,resetTerminalPreviewScan:ge,startStream:xe,setConnectionError:ee,setIsFatalError:_e,setIsReconnectPending:F});i.useEffect(()=>{if(!se||m)return;if(typeof window>"u"){H();return}const ne=window.requestAnimationFrame(()=>{H()});return()=>{window.cancelAnimationFrame(ne)}},[E,H,se,m]);const X=i.useMemo(()=>{const ne=Xs[ir].stack;if(typeof window>"u")return(Xs[c]??Xs[ir]).stack;const De=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return De&&De.trim().length>0?De.trim():(Xs[c]??Xs[ir]).stack??ne},[c]),pe=i.useMemo(()=>Np(a),[a]),de=`${N??"no-dir"}::${E??"no-tab"}`;if(i.useEffect(()=>{if(!se||m)return;const ne=oe.current;if(!ne)return;const Fe=()=>{ne.fit()};if(typeof window<"u"){const De=window.requestAnimationFrame(()=>{Fe(),H()}),kt=[220,400].map(Ze=>window.setTimeout(Fe,Ze));return()=>{window.cancelAnimationFrame(De),kt.forEach(Ze=>window.clearTimeout(Ze))}}Fe()},[H,se,m,oe,de,_]),i.useEffect(()=>{if(!se||!m)return;let ne=null;const Fe=()=>{ne!==null&&window.cancelAnimationFrame(ne),ne=window.requestAnimationFrame(()=>{ne=null,oe.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),ne!==null&&window.cancelAnimationFrame(ne)}},[se,oe,de,m]),!j)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(!N)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:he,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ke=!_||L||Z||q,He=W,We=C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx(Up,{items:B,activeId:E,onSelect:Oe,onClose:ve,onCreate:me})}),t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:$("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:me,title:"New tab","aria-label":"New tab",children:t.jsx(R,{name:"add",className:`${g?"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:()=>{he()},disabled:Z,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?t.jsxs(Me,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{N&&k(N,T)},title:"Open preview pane",children:[t.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,Se=t.jsx(zp,{isTouchTerminal:g,activeModifier:re,disabled:ke,onKeyPress:O,onModifierToggle:Be});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:$("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",g?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[We?n?Xl.createPortal(t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:We}),n):t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[We,s?t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:s,title:"Close terminal view","aria-label":"Close terminal view",children:t.jsx(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!g&&I&&v&&C?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Se}):null,!g&&I&&!C?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Se}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:pe.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:He&&N&&C?C.tabs.map(ne=>{const Fe=ne.id===E;return t.jsx(_p,{directory:N,tabId:ne.id,sessionId:ne.terminalSessionId,sessionKey:`${N}::${ne.id}`,isActive:Fe,isTerminalVisible:se,terminal:r,theme:pe,fontFamily:X,fontSize:d,enableTouchScroll:m,lastViewportSizeRef:Q,onInput:be,controllerRef:oe},ne.id)}):null}),!q&&Ie&&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:Ie}),Te&&g&&t.jsx(Me,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ue,disabled:Z,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),g&&I?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Se})}):null]})},om=48,im=96,gt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Pg=(e,s)=>{const n=i.useRef(s);n.current=s;const r=s.enabled;i.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const a=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?im:om;let d=!1,u=!1,f=!1,p=null,b=!1,h=0,g=0,m=0,v=0;const x=()=>{d=!1,u=!1,f=!1,p=null},I=()=>{const k=n.current,E=p,M=b;u&&E&&(gt(E==="left"?k.onLeftProgress:k.onRightProgress,M?1:0),gt(k.onDragEnd,E,M)),x()},w=()=>{I(),u||x()},A=k=>{const E=n.current;if(E.enabled===!1){u&&p?I():x();return}if(k.touches.length!==1){u&&p?I():x();return}const M=k.touches[0],B=o.getBoundingClientRect(),_=o.clientWidth,K=!!E.leftOpen,V=!!E.rightOpen,L=T=>xp(T,o);if(K||V){if(L(k.target)){x();return}if(K&&V){const T=M.clientX<=B.left+c;M.clientX>=B.right-c?(p="right",b=!0):T?(p="left",b=!0):(p=K?"left":"right",b=!0)}else K?(p="left",b=!0):(p="right",b=!0);v=wr(p==="left"?E.leftWidth:E.rightWidth,_),v<10&&(v=_||window.innerWidth||320),v<10&&(v=320),d=!0}else{if(L(k.target)){x();return}p=null,b=!1,v=0,d=!0}h=M.clientX,g=M.clientY,m=Date.now(),u=!1,f=!1},j=k=>{if(!d)return;if(k.touches.length!==1){w();return}const E=k.touches[0],M=E.clientX-h,B=E.clientY-g;if(!f){if(Math.abs(M)<ii&&Math.abs(B)<ii)return;if(Math.abs(B)>Math.abs(M)*en){x();return}if(!p){const V=n.current;p=M>0?"left":"right",v=wr(p==="left"?V.leftWidth:V.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(p==="left"){if(!b&&M<=0){x();return}if(b&&M>=0){x();return}}else{if(!b&&M>=0){x();return}if(b&&M<=0){x();return}}f=!0,u=!0,gt(n.current.onDragStart,p)}if(!u)return;k.cancelable&&k.preventDefault();const _=n.current,K=ai(p,b,M,v);gt(p==="left"?_.onLeftProgress:_.onRightProgress,K)},N=(k,E)=>{if(!d){x();return}const M=k-h,B=E-g;if(!p&&!b&&Math.abs(M)>=On&&Math.abs(B)<=Math.abs(M)*en){const P=n.current;p=M>0?"left":"right",v=wr(p==="left"?P.leftWidth:P.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(!p){x();return}const _=Math.max(1,Date.now()-m),K=n.current;if(!u){const P=Math.abs(M),U=Math.abs(B);P>=On&&U<=P*en?p==="left"&&!b&&M>0?(gt(K.onLeftProgress,1),gt(K.onLeftOpen)):p==="right"&&!b&&M<0?(gt(K.onRightProgress,1),gt(K.onRightOpen)):gt(p==="left"?K.onLeftProgress:K.onRightProgress,b?1:0):gt(p==="left"?K.onLeftProgress:K.onRightProgress,b?1:0);const se=p;x(),gt(K.onDragEnd,se);return}const V=ai(p,b,M,v),L=gp({side:p,isOpenAtStart:b,dx:M,dt:_,progress:V}),T=p;gt(T==="left"?L?K.onLeftOpen:K.onLeftClose:L?K.onRightOpen:K.onRightClose),x(),gt(K.onDragEnd,T,L)},C=k=>{const E=k.changedTouches[0];if(!E){x();return}const M=E.clientX-h,B=E.clientY-g;d&&(u||Math.abs(M)>=On&&Math.abs(B)<=Math.abs(M)*en)&&k.cancelable&&k.preventDefault(),N(E.clientX,E.clientY)},y=()=>{w()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",j,{passive:!1}),o.addEventListener("touchend",C,{passive:!1}),o.addEventListener("touchcancel",y,{passive:!0}),()=>{try{u&&p&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",j),o.removeEventListener("touchend",C),o.removeEventListener("touchcancel",y)}},[e,r])};function Mg({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function hi({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const am=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,lm=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>qn(s,n)?null:e,vr=()=>ms.filter(e=>Pr.has(e.id)).map(e=>({...Oi(e)})),cm=()=>{if(typeof window>"u")return Mr;const e=window.localStorage.getItem("openInAppId");return e&&Dr(e)?e:Mr};let Sr=!1,Rs=!1,ns=!1,rs=0,cn=null;const pi=()=>{cn&&(clearTimeout(cn),cn=null)},fs=zs()((e,s)=>({selectedAppId:cm(),availableApps:vr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Sr||typeof window>"u")return;Sr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:vr(),hasLoadedApps:u});return}const f=new Set(d.map(g=>g.name)),p=new Map(d.map(g=>[g.name,g.iconDataUrl??void 0])),h=ms.filter(g=>f.has(g.appName)||Pr.has(g.id)).map(g=>({...Oi(g),iconDataUrl:p.get(g.appName)}));e({availableApps:h,hasLoadedApps:!0})},r=async d=>{if(!Ts()||!_n()||Rs||s().hasLoadedApps&&!d)return;const f=ms.map(p=>p.appName);pi(),Rs=!0,ns=!1,e({isScanning:!0});try{const{apps:p,success:b,hasCache:h,isCacheStale:g}=await Fo(f,d),m=b&&!h&&p.length===0&&rs<3;if(e({isCacheStale:h?g:!1}),n(p,b?!m:!1),b){if(m){const x=[800,1600,3200][rs]??3200;rs+=1,ns=!0,cn=setTimeout(()=>{r()},x);return}rs=0,ns=!1;return}if(rs<3){const x=[1e3,3e3,7e3][rs]??7e3;rs+=1,ns=!0,cn=setTimeout(()=>{r()},x)}}finally{Rs=!1,ns||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Dr(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(rs=3,ns=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Sr||s().initialize(),!Ts()||!_n()||Rs||s().hasLoadedApps&&!n)return;const o=ms.map(a=>a.appName);pi(),n&&e({hasLoadedApps:!1}),Rs=!0,ns=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await Fo(o,n),d=new Set(a.map(b=>b.name)),u=new Map(a.map(b=>[b.name,b.iconDataUrl??void 0])),p=ms.filter(b=>d.has(b.appName)||Pr.has(b.id)).map(b=>({...b,iconDataUrl:u.get(b.appName)}));e({availableApps:p.length>0?p:vr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Rs=!1,ns||e({isScanning:!1})}},selectApp:async n=>{Dr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Vr({openInAppId:n}))}})),dm="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",um="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",jr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?dm:e.id==="terminal"?um:void 0}),mi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,o]=i.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):t.jsx("span",{className:$("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},fm=({directory:e,className:s})=>{const n=fs(g=>g.selectedAppId),r=fs(g=>g.availableApps),o=fs(g=>g.isCacheStale),a=fs(g=>g.isScanning),l=fs(g=>g.initialize),c=fs(g=>g.loadInstalledApps),d=fs(g=>g.selectApp);i.useEffect(()=>{l()},[l]);const u=Ts()&&_n(),f=i.useMemo(()=>{const g=r.find(m=>m.id===n)??r.find(m=>m.id===Mr)??r[0]??ms[0];return jr(g||ms[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async g=>{await cd(e,g.id,g.appName)||await Ti(e,g.appName)},b=async g=>{await d(g.id),await p(g)},h=async()=>{(await ws(e)).ok&&ie.success("Path copied to clipboard")};return t.jsxs("div",{className:$("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{p(f)},className:$("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:t.jsx(mi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Pt,{children:[t.jsx(Mt,{asChild:!0,children:t.jsx("button",{type:"button",className:$("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Tt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{h()},children:[t.jsx(R,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(vs,{}),r.map(g=>{const m=jr(g);return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{b(g)},children:[t.jsx(mi,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:m.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:g.label}),f.id===g.id?t.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},g.id)}),o?t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(R,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},hm="\x1B",pm=new RegExp(`${hm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),mm=/https?:\/\/[^\s<>'"`]+/gi,yt="__pichamber_auto_discover_preview__",gm=15e3,bm=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},xm=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},ym=e=>{const n=e.replace(pm,"").match(mm);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&o.push({raw:a,parsed:l})}catch{}if(o.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,b=f==="/"||f==="",h=!!(c.search||c.hash);let g=0;return u&&(g+=50),b&&(g+=30),g-=Math.min(p*5,20),h&&(g-=10),g};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},wm=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],vm=["dev","start","preview","serve"];async function Sm(e,s,n){if(!e)return null;const r=km(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Am(n);if(o){const a=await Nm(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await jm(e)){const o=await Cm(),a=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function jm(e){const s=`${e}/index.html`,n=await Yn(s,e);return typeof n=="string"&&n.trim().length>0}async function Cm(){try{const e=await Ft("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function km(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(vm.some(o=>n.includes(o)))return s}return null}function Am(e){for(const{pattern:s}of wm)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Nm(e){const s=await Yn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Yn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Yn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Ft(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Qt()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Ft(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Im(e){try{const s=await Yn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Rm=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function Em({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Ei(),{terminal:o}=Us(),{isMobile:a}=_s(),l=le(O=>O.terminalShell),c=le(O=>O.terminalLoginShells.includes(O.terminalShell)),d=le(O=>O.setSettingsPage),u=le(O=>O.setSettingsDialogOpen),f=le(O=>O.setSettingsProjectsSelectedId),p=le(O=>O.openContextPreview),b=fe(O=>O.ensureDirectory),h=fe(O=>O.setTabLabel),g=fe(O=>O.setTabIconKey),m=fe(O=>O.setActiveTab),v=fe(O=>O.setConnecting),x=fe(O=>O.setTabSessionId),I=fe(O=>O.setTabPreviewUrl),w=fe(O=>O.projectActionRuns),A=fe(O=>O.setProjectActionRun),j=fe(O=>O.updateProjectActionRunStatus),N=fe(O=>O.removeProjectActionRun),[C,y]=i.useState([]),[k,E]=i.useState(null),[M,B]=i.useState(!1),_=i.useRef({}),K=i.useRef({}),V=i.useRef({}),L=i.useRef({}),T=i.useRef(new Set),P=i.useRef(0),U=e?.id??null,se=e?.path??"",W=i.useMemo(()=>U?{id:U,path:se}:null,[U,se]),G=i.useCallback(async O=>{await wi(O)},[]),Ie=i.useCallback(async()=>{if(!W)return;const O=P.current+1;P.current=O,B(!0);try{const Z=await kr(W);if(P.current!==O)return;const he=Z.actions;y(he),E(ue=>ue===yt||ue&&he.some(me=>me.id===ue)?ue:null)}catch{if(P.current!==O)return}finally{P.current===O&&B(!1)}},[W]),ee=i.useMemo(()=>pa(s||W?.path||""),[s,W?.path]),Te=i.useMemo(()=>k?C.find(O=>O.id===k)??null:null,[C,k]),_e=i.useMemo(()=>({id:yt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),q=!a,F=i.useMemo(()=>q?[_e,...C]:C,[C,_e,q]);i.useEffect(()=>{Ie()},[Ie]),i.useEffect(()=>{if(typeof window>"u")return;const O=Z=>{const he=Z.detail;U&&(he?.projectId&&he.projectId!==U||Ie())};return window.addEventListener(zr,O),()=>{window.removeEventListener(zr,O)}},[Ie,U]),i.useEffect(()=>{k&&(k===yt&&q||C.some(O=>O.id===k)||E(null))},[C,q,k]),i.useEffect(()=>{const O=()=>{const Z=fe.getState(),he=Z.sessions,ue=Z.projectActionRuns;for(const[me,Oe]of Object.entries(ue)){const X=he.get(Oe.directory)?.tabs.find(De=>De.id===Oe.tabId);if(!X||X.terminalSessionId!==Oe.sessionId){N(me);continue}const pe=K.current[me]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};K.current[me]=pe;const de=F.find(De=>De.id===Oe.actionId),ke=Z.getBuffer(Oe.directory,Oe.tabId).chunks;if(!de||ke.length===0)continue;const He=ke.filter(De=>pe.lastSeenChunkId===null||De.id>pe.lastSeenChunkId);if(He.length===0)continue;const We=He.map(De=>De.data).join(""),Se=`${pe.tail}${We}`,ne=!pe.openedUrl&&de.autoOpenUrl===!0?ym(Se):null,Fe=He[He.length-1]?.id??pe.lastSeenChunkId;if(pe.lastSeenChunkId=Fe,pe.tail=Se.slice(-512),ne)if(pe.openedUrl=!0,pe.openInPreview){const De=ue[me];De&&(I(De.directory,De.tabId,ne,{locked:!1,autoOpened:!1}),De.status==="waiting-for-preview"&&j(me,"running"),window.clearTimeout(L.current[me]),delete L.current[me],p(De.directory,ne))}else G(ne),ie.success("Opened URL from action output");K.current[me]=pe}for(const me of Object.keys(K.current))ue[me]||(delete K.current[me],window.clearTimeout(L.current[me]),delete L.current[me])};return O(),fe.subscribe((Z,he)=>{(Z.sessions!==he.sessions||Z.buffers!==he.buffers)&&O()})},[F,p,G,w,N,I,j]);const z=i.useCallback(async(O,Z={})=>{if(!ee)throw new Error("No active directory");const he=Vt(ee,O.id);b(ee);const ue=fe.getState(),me=ue.getDirectoryState(ee);let Oe=_.current[he]||null;const ve=Oe?!!me?.tabs.some(de=>de.id===Oe):!1;(!Oe||!ve)&&(Oe=ue.createTab(ee),_.current[he]=Oe),h(ee,Oe,`Action: ${O.name}`),g(ee,Oe,O.icon||"play"),m(ee,Oe),Z.revealTerminal!==!1&&le.getState().openContextPanelTab(ee,{mode:"terminal"});const pe=fe.getState().getDirectoryState(ee)?.tabs.find(de=>de.id===Oe);return{key:he,tabId:Oe,sessionId:pe?.terminalSessionId??null}},[b,ee,m,g,h]),Q=i.useCallback(async O=>{if(!n&&a)return;if(!ee){ie.error("No active directory for action");return}const Z=Vt(ee,O.id),he=w[Z];if(!(he&&he.status==="running")&&!T.current.has(Z)){T.current.add(Z);try{const ue=O.id===yt?await(async()=>{const[Se,ne]=await Promise.all([kr({id:W?.id??"",path:ee}),Im(ee)]),Fe=await Sm(ee,Se.actions,ne);if(!Fe)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:yt,name:"Auto-discover",command:Fe.command,icon:"scan-2",autoOpenUrl:!0,openUrl:Fe.previewUrlHint||""}})():O,me=ue.autoOpenUrl===!0&&(ue.openUrl||"").trim().length>0,Oe=!me&&O.id!==yt,{key:ve,tabId:X,sessionId:pe}=await z(ue,{revealTerminal:Oe});let de=pe;if(!de){v(ee,X,!0);try{de=(await o.createSession({cwd:ee,sessionId:X,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(ee,X,de)}finally{v(ee,X,!1)}}if(!de)throw new Error("Failed to create terminal session");V.current[ve]?.(),v(ee,X,!0);const ke=o.connect(de,{onEvent:Se=>{Se.type==="snapshot"&&(fe.getState().replaceBuffer(ee,X,Se.data??"",Se.sequence??0),fe.getState().setConnecting(ee,X,!1)),Se.type==="data"&&typeof Se.data=="string"&&Se.data.length>0&&fe.getState().appendToBuffer(ee,X,Se.data,Se.sequence,Se.replayData),Se.type==="exit"&&(fe.getState().setTabLifecycle(ee,X,"exited"),fe.getState().setConnecting(ee,X,!1),fe.getState().removeProjectActionRun(ve),delete K.current[ve],V.current[ve]?.(),delete V.current[ve],window.clearTimeout(L.current[ve]),delete L.current[ve])},onError:(Se,ne)=>{fe.getState().setConnecting(ee,X,!1),ne&&(fe.getState().setTabLifecycle(ee,X,"exited"),fe.getState().setTabSessionId(ee,X,null),fe.getState().removeProjectActionRun(ve))}});V.current[ve]=ke.close;const He=ue.autoOpenUrl?xm(ue.openUrl):null;A({key:ve,directory:ee,actionId:ue.id,tabId:X,sessionId:de,status:ue.id===yt&&!He?"waiting-for-preview":"running"}),window.clearTimeout(L.current[ve]),delete L.current[ve],ue.id===yt&&!He&&(L.current[ve]=window.setTimeout(()=>{const Se=fe.getState(),ne=Se.projectActionRuns[ve];Se.updateProjectActionRunStatus(ve,"running"),ne&&(Se.setActiveTab(ne.directory,ne.tabId),le.getState().openContextPanelTab(ne.directory,{mode:"terminal"})),delete L.current[ve]},gm)),K.current[ve]={lastSeenChunkId:null,openedUrl:!!He||me,tail:"",openInPreview:ue.id===yt};const We=bm(ue.command.trim().replace(/\r\n|\r/g,`
53
+ `));await o.sendInput(de,`${We}\r`),He?(I(ee,X,He,{locked:!0,autoOpened:!0}),p(ee,He),ie.success("Opened action URL")):me?(I(ee,X,null,{locked:!0}),ie.error("Invalid custom URL format")):I(ee,X,null,{locked:!1,autoOpened:!1})}catch(ue){N(Z),delete K.current[Z],V.current[Z]?.(),delete V.current[Z],window.clearTimeout(L.current[Z]),delete L.current[Z],ie.error(ue instanceof Error?ue.message:"Failed to run action")}finally{T.current.delete(Z)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,z,n,a,ee,c,l,p,w,N,v,A,I,x,W?.id,o]),te=i.useCallback(async O=>{const Z=Vt(ee,O.id),he=w[Z];if(!he)return;j(Z,"stopping");const ue=Rm(o,he.sessionId,1e3);try{await o.sendInput(he.sessionId,"")}catch{}const me=await ue;if(fe.getState().getDirectoryState(he.directory)?.tabs.find(X=>X.id===he.tabId)?.terminalSessionId===he.sessionId&&!me){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:he.sessionId})}catch{}else try{await o.close(he.sessionId)}catch{}x(he.directory,he.tabId,null)}N(Z),delete K.current[Z],V.current[Z]?.(),delete V.current[Z],window.clearTimeout(L.current[Z]),delete L.current[Z]},[ee,w,N,x,o,j]),Ce=i.useCallback(()=>{const O=Te??F[0];if(!O)return;const Z=Vt(ee,O.id),he=w[Z];if(he?.status!=="stopping"){if(he){te(O);return}Q(O)}},[F,ee,Q,w,Te,te]),ge=i.useCallback((O,Z=!1)=>{if(E(O.id),!Z){Q(O);return}const he=Vt(ee,O.id),ue=w[he];if(ue?.status!=="stopping"){if(ue){te(O);return}Q(O)}},[ee,Q,w,te]),xe=i.useCallback(()=>{W?.id&&(f(W.id),d("projects"),u(!0))},[u,d,f,W?.id]),re=Te??F[0]??null,oe=re?w[Vt(ee,re.id)]:null,H=fe(O=>oe?O.sessions.get(oe.directory)?.tabs.find(Z=>Z.id===oe.tabId)?.previewUrl??null:null),be=!!((n||!a)&&W&&ee),Be=Te??F[0]??null;return{shouldRender:be,isLoading:M,normalizedDirectory:ee,resolvedSelected:Be,displayActions:F,projectActionRuns:w,selectedRunPreviewUrl:H,handlePrimaryClick:Ce,handleSelectAction:ge,openProjectActionsSettings:xe,openContextPreview:p}}const gi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:h,openProjectActionsSettings:g,openContextPreview:m}=Em({projectRef:e,directory:s,allowMobile:o});if(!a||!d)return null;const v=d.icon||"play",x=d.id===yt?"scan-2":ln[v]||"play",I=Vt(c,d.id),w=f[I],A=w?.status==="stopping",j=w?.status==="waiting-for-preview",N=!!(w&&p),C=()=>{!w||!p||m(w.directory,p)},y=d.id===yt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||A,className:$("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:b,"aria-label":w?`Stop ${d.name}`:`Run ${d.name}`,children:A||j?t.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-5 w-5"})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:C,children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Pt,{children:[t.jsx(Mt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Tt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),u.map(k=>{const E=k.icon||"play",M=k.id===yt?"scan-2":ln[E]||"play",B=Vt(c,k.id),_=f[B],K=!!_,V=_?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{h(k,!0)},children:[t.jsx(R,{name:M,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),V||_?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]}):t.jsxs("div",{className:$("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||A,className:$("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":w?`Stop ${d.name}`:`Run ${d.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||j?t.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-4 w-4"})})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:C,className:$(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Pt,{children:[t.jsx(Mt,{asChild:!0,children:t.jsx("button",{type:"button",className:$(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Tt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),u.map(k=>{const E=k.icon||"play",M=k.id===yt?"scan-2":ln[E]||"play",B=Vt(c,k.id),_=f[B],K=!!_,V=_?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{h(k,!0)},children:[t.jsx(R,{name:M,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),V||_?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]})},Dm=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Pt,{children:[t.jsx(Mt,{asChild:!0,children:t.jsx("button",{type:"button",className:$(gn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Tt,{align:"end",className:"w-64",children:[t.jsx(Ec,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(vs,{}),r.map(d=>{const u=d.user,f=!!d.current,p=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(rt,{className:"gap-2",disabled:l,onSelect:()=>{f||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(R,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:p})]}):null]}),f?t.jsx(R,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Pm=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:b}){return t.jsxs(Pt,{open:a,onOpenChange:h=>{l(h),h&&c()},children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Mt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:$(gn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(R,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Tt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[o?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:f?"Looking for updates...":p||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:b,children:"Update"}):null]})}),t.jsx(Dc,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Mm=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx($t,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Gt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(as,{children:[t.jsx(Xt,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(ls,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ss,{children:[t.jsx(Me,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Me,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Tm=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Zs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Fm=i.lazy(()=>os(()=>import("./SessionSwitcherDropdown-BAHhqkBZ.js"),__vite__mapDeps([116,24,4,5,1,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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])).then(e=>({default:e.SessionSwitcherDropdown}))),Tg=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Dt("ui.header.render");const l=le(D=>D.setSessionSwitcherOpen),c=le(D=>D.toggleSidebar),d=le(D=>D.isSidebarOpen),u=le(D=>D.activeMainTab),f=le(D=>D.setActiveMainTab),p=le(D=>D.shortcutOverrides);le(D=>D.timeFormatPreference),Us();const b=Ee(D=>!!D.newSessionDraft?.open),h=Ee(D=>D.currentSessionId),g=Ri(h??""),m=Pc(h),v=i.useMemo(()=>{if(!m)return null;const D=m;return{title:m.title??null,directory:D.directory??null,created:m.time?.created??null,slug:D.slug??null,shareUrl:m.share?.url??null,parentId:m.parentID??null}},[m]),x=ht(Tr(D=>{if(!D.activeProjectId)return null;const ae=D.projects.find(we=>we.id===D.activeProjectId);return ae?{id:ae.id,path:ae.path,label:ae.label}:null})),I=Fs(D=>D.homeDirectory),w=i.useMemo(()=>{if(!x)return null;const D=x.label?.trim();if(D)return D;const ae=x.path.split(/[\\/]/).filter(Boolean);return ae[ae.length-1]??null},[x]),{isMobile:A}=_s(),{enabled:j}=qr(),N=!!(j&&a&&o!==void 0),C=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[y,k]=i.useState(!1),E=null,M=i.useRef(null),[B,_]=i.useState(()=>typeof window>"u"?!1:Ts()),K=i.useMemo(()=>Fi(),[]),V=Mc(),[L,T]=i.useState(!1),P=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),U=Di(),se=i.useMemo(()=>{if(typeof window>"u")return null;const D=window.__PICHAMBER_MACOS_MAJOR__;if(typeof D=="number"&&Number.isFinite(D)&&D>0)return D;if(typeof navigator>"u")return null;const ae=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ae)return null;const we=Number.parseInt(ae[1],10),Ue=Number.parseInt(ae[2],10);return Number.isNaN(we)?null:we===10?Ue:we},[]);Ne.useEffect(()=>{typeof window>"u"||_(Ts())},[]);const W=le(D=>D.isSessionSwitcherOpen),G=null,Ie=null,ee=[],[Te,_e]=i.useState(!1),[q,F]=i.useState(!1),[z,Q]=i.useState("Local"),[te,Ce]=i.useState(!0),[ge,xe]=i.useState(!1),[re,oe]=i.useState(null),[H,be]=i.useState(!1),[Be,O]=i.useState(null),Z=i.useRef(0),he=i.useMemo(()=>Tm(z),[z]),ue=i.useCallback(async()=>{if(typeof window>"u"||!B)return;const D=Je(),ae=()=>Je()===D;try{if(_n()){Q("Local"),Ce(!0);return}Ce(!1);const we=await dd();if(!ae())return;const Ue=ud(),ut=fd([hd(Ue),...we.hosts]);if(ut.id===pd){Q("Local"),Ce(!0);return}Q(md(ut.label.trim()||"Instance"))}catch{ae()&&(Q("Local"),Ce(!0))}},[B]);Ne.useEffect(()=>(ue(),gd(()=>{Z.current+=1,oe(null),O(null),be(!1),xe(!1),ue()})),[ue]);const me=i.useCallback(async()=>{const D=Z.current+1;Z.current=D;const ae=Je(),we=()=>Z.current===D&&Je()===ae;if(te){oe(null),O(null);return}be(!0),O(null);try{const Ue=new URLSearchParams({appType:"web",instanceMode:"remote"}),ut=await Ft(`/api/pi/update-check?${Ue.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ut.ok)throw new Error(`Server responded with ${ut.status}`);const Ve=await ut.json();if(!we())return;oe({available:Ve.available??!1,version:Ve.version,currentVersion:Ve.currentVersion??"unknown",body:Ve.body,nextSuggestedCheckInSec:typeof Ve.nextSuggestedCheckInSec=="number"?Ve.nextSuggestedCheckInSec:void 0,packageManager:Ve.packageManager,updateCommand:Ve.updateCommand,channel:Ve.channel==="rc"?"rc":"stable"})}catch(Ue){if(!we())return;oe(null),O(Ue instanceof Error?Ue.message:"Failed to check remote instance updates")}finally{we()&&be(!1)}},[te]);i.useEffect(()=>$u(()=>{te||me()}),[me,te]),i.useEffect(()=>{Z.current+=1,oe(null),O(null),be(!1),xe(!1)},[te,z]),i.useEffect(()=>{if(!B||te)return;const D=3e3,ae=3600*1e3;let we=!1,Ue=null;const ut=Ve=>{Ue=window.setTimeout(()=>{if(we||typeof document<"u"&&document.visibilityState!=="visible"){ut(ae);return}me().finally(()=>{we||ut(ae)})},Ve)};return ut(D),()=>{we=!0,Ue!==null&&window.clearTimeout(Ue)}},[me,te,z,B]);const Oe=i.useCallback(()=>{if(re?.available){xe(!0);return}me()},[me,re?.available]),ve=h?v??null:null,X=i.useRef(null),[pe,de]=i.useState(0);i.useEffect(()=>{if(!h){X.current&&(X.current=null,de(Ue=>Ue+1));return}if(ve){X.current={sessionId:h,session:ve,expiresAt:Date.now()+2e3};return}const D=X.current;if(!D||D.sessionId!==h)return;const ae=D.expiresAt-Date.now();if(ae<=0){X.current=null,de(Ue=>Ue+1);return}const we=window.setTimeout(()=>{X.current?.sessionId===h&&(X.current=null),de(Ue=>Ue+1)},ae);return()=>{window.clearTimeout(we)}},[h,ve]);const ke=(()=>{if(ve)return ve;if(!h)return null;const D=X.current;return D&&D.sessionId===h&&D.expiresAt>Date.now()?D.session:null})(),He=i.useMemo(()=>{const D=typeof ke?.directory=="string"?ke.directory:"";return Zs(D||"")},[ke?.directory]),We=Ee(D=>D.newSessionDraft?.open?Zs(D.newSessionDraft.directoryOverride??""):""),Se=i.useMemo(()=>am({sessionDirectory:He,draftDirectory:We,isNewSessionDraftOpen:b}),[We,b,He]),Fe=Ii(Se||null),De=i.useMemo(()=>lm({activeProjectLabel:w,openDirectory:Se,homeDirectory:I}),[w,I,Se]),kt=!!(De||Fe),Ze=i.useMemo(()=>h?is(ke):De??"PiChamber",[ke,h,De]),Xe=Tc(),Kt=Ee(D=>D.updateSessionTitle),wt=Ee(D=>D.archiveSessions),Zt=Ee(D=>D.deleteSessions),[ot,et]=i.useState(!1),[it,vt]=i.useState(!1),bt=i.useRef(!1),[Wt,St]=i.useState(""),[ye,Pe]=i.useState(null),je=i.useRef(null);i.useEffect(()=>{bt.current=!1,vt(!1),et(!1),St(""),Pe(null)},[h]);const Le=i.useCallback(()=>{h&&(St(ke?.title?.trim()||Ze),et(!0))},[ke?.title,h,Ze]),Ye=i.useCallback(async()=>{if(!h)return;const D=Wt.trim();D&&D!==ke?.title?.trim()&&await Kt(h,D),et(!1)},[ke?.title,h,Wt,Kt]);i.useEffect(()=>{if(!ot)return;const D=ae=>{const we=ae.target;(!we||!je.current?.contains(we))&&Ye()};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[ot,Ye]);const ct=i.useCallback(()=>{h&&ws(h).then(D=>{ie[D.ok?"success":"error"](D.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[h]),At=i.useCallback(async()=>{if(!h||!Se){ie.error("Nothing to export");return}try{await Xe.syncSession(h)}catch{ie.error("Failed to load the complete session history");return}const D=[];if(D.length===0){ie.error("Nothing to export");return}const ae=Da(D,ke?.title??null),we=Ta(ke?.title??null);await Ma(ae,we)||Pa(ae,we),ie.success("Session exported")},[ke?.title,h,Se,Xe]);g?.type==="busy"||g?.type;const Ot=i.useCallback(async()=>{if(!h||!ye)return;const D=Fc(),ae=[h];for(let Ve=0;Ve<ae.length;Ve+=1){const Qs=ae[Ve];for(const Yt of D)Yt.parentID===Qs&&!ae.includes(Yt.id)&&ae.push(Yt.id)}const we=ye;if(Pe(null),(we==="archive"?await wt(ae):await Zt(ae)).failedIds.length>0){ie.error(we==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(we==="archive"?"Session archived":"Session deleted")},[wt,h,Zt,ye]),es=le(D=>D.isArchivePageOpen),pt=i.useMemo(()=>es?{title:"Archive",subtitle:null}:null,[es]),qe=i.useMemo(()=>Zs(Se||x?.path||""),[x?.path,Se]),ts=i.useCallback(()=>{qe&&ws(qe).then(D=>{ie[D.ok?"success":"error"](D.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ie.error("Failed to copy working directory"))},[qe]),mt=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),Lt=i.useRef(null);i.useEffect(()=>{!mt||!qe||(Lt.current={projectRef:mt,directory:qe})},[qe,mt]);const Bt=i.useMemo(()=>mt&&qe?{projectRef:mt,directory:qe}:Lt.current,[qe,mt]),$s=i.useCallback(async D=>{},[]),Nt=i.useCallback(()=>{if(typeof document>"u")return;const D=document.activeElement;if(!D)return;const ae=D.tagName;(ae==="INPUT"||ae==="TEXTAREA"||ae==="SELECT"||D.isContentEditable)&&D.blur()},[]),Gs=i.useCallback(()=>{if(A){Nt(),l(!W);return}c()},[Nt,A,W,l,c]),It=i.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:Zs(Se||x?.path||""),projectId:x?.id??null,apiBaseUrl:Er(),clientToken:Rr()}).catch(D=>{console.warn("[header] failed to open draft mini chat window",D)})},[x?.id,x?.path,Se]),cs=i.useCallback(()=>{if(b){It();return}h&&on("desktop_open_session_mini_chat_window",{sessionId:h,directory:Zs(Se||x?.path||""),apiBaseUrl:Er(),clientToken:Rr()}).catch(D=>{console.warn("[header] failed to open session mini chat window",D)})},[x?.path,h,It,b,Se]),dt=gn,ce=pf,st=i.useMemo(()=>n?"sessions":N?r&&o?o:null:r?"git":u,[u,N,n,r,o]),tt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&W&&l(!1)},[W,n,e,s,r,l]),xt=i.useCallback(()=>{e?.()},[e]),ds=i.useCallback(()=>{s?.()},[s]),at=i.useMemo(()=>B&&P&&!L?"5.5rem":V?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!B||U?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[B,L,P,V,U]);Ne.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",at)},[at]);const bn=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ks=d?"0px":B&&U?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":j?"2.75rem":"2.5rem";Ne.useEffect(()=>{if(!B||!P){T(!1);return}let D=!1;const ae=async()=>{try{const Ue=await on("desktop_is_window_fullscreen");D||T(Ue===!0)}catch{D||T(!1)}},we=()=>{ae()};return ae(),window.addEventListener("pichamber:window-resized",we),()=>{D=!0,window.removeEventListener("pichamber:window-resized",we)}},[B,P]);const xn=i.useMemo(()=>!B||!P||se===null?"":se>=26?"h-12":se<=15?"h-14":"",[B,P,se]),Ws=i.useMemo(()=>{if(!(B&&!U))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[B,U]),us=i.useCallback(()=>{if(typeof document>"u")return;const D=M.current?.getBoundingClientRect().height;D&&document.documentElement.style.setProperty("--oc-header-height",`${D}px`)},[]);Ne.useEffect(()=>{if(typeof window>"u")return;us();const D=M.current;if(!D||typeof ResizeObserver>"u")return()=>{};let ae=0;const we=()=>{ae||(ae=requestAnimationFrame(()=>{ae=0,us()}))},Ue=new ResizeObserver(we);return Ue.observe(D),window.addEventListener("resize",we),window.addEventListener("orientationchange",we),()=>{ae&&cancelAnimationFrame(ae),Ue.disconnect(),window.removeEventListener("resize",we),window.removeEventListener("orientationchange",we)}},[us]),Ne.useEffect(()=>{us()},[us,A,xn]);const Vn=i.useCallback(async D=>{const ae=D.target;ae.closest(".app-region-no-drag")||ae.closest("button, a, input, select, textarea")||D.button===0&&B&&await Oc()},[B]),Ht=i.useMemo(()=>A?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[A]),Hs=i.useCallback(D=>Xr(Bn(D,p)),[p]);Ne.useEffect(()=>{!A&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,A,f]),Ne.useEffect(()=>{const D=ae=>{if(bd(ae)&&!ae.shiftKey&&!ae.altKey){const we=parseInt(ae.key,10);we>=1&&we<=Ht.length&&(ae.preventDefault(),A&&(Nt(),tt()),f(Ht[we-1].id))}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[Nt,tt,A,f,Ht]),Ne.useEffect(()=>{const D=ae=>{const we=Bn("toggle_services_menu",p);if(xd(ae,we)){ae.preventDefault(),q?F(!1):(F(!0),ue());return}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p,q,ue]);const Cs=D=>{const ae=u===D.id,we=D.icon==="diff",Ue=we?null:D.icon,ut=D.id==="chat",Ve=Yt=>we?t.jsx(hi,{size:Yt}):Ue?t.jsx(R,{name:Ue,className:`h-${Yt/4} w-${Yt/4}`}):null,Qs=t.jsxs("button",{type:"button",onClick:()=>f(D.id),className:$("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ae?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",ut&&!A&&"min-w-[100px] justify-center"),"aria-label":D.label,"aria-selected":ae,role:"tab",children:[A?Ve(20):t.jsxs(t.Fragment,{children:[Ve(16),t.jsx("span",{className:"header-tab-label",children:D.label})]}),D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:D.badge})]});return t.jsx(i.Fragment,{children:Qs},D.id)},Jn=t.jsxs(t.Fragment,{children:[t.jsx(fm,{directory:qe,className:"mr-1"}),B?t.jsx(Pm,{isDesktopApp:B,currentInstanceLabel:z,compactCurrentInstanceLabel:he,currentInstanceIsLocal:te,isDesktopServicesOpen:q,setIsDesktopServicesOpen:F,refreshCurrentInstanceLabel:ue,shortcutLabel:Hs,remoteUpdateInfo:re,remoteUpdateChecking:H,remoteUpdateError:Be,onOpenRemoteUpdate:Oe}):null,t.jsx(Dm,{isMobile:A,githubAuthStatus:E,githubAccounts:ee,githubAvatarUrl:G,githubLogin:Ie,isSwitchingGitHubAccount:Te,handleGitHubAccountSwitch:$s})]}),Xn=K&&(b||!!h),Ys=()=>t.jsxs("div",{onMouseDown:Vn,className:$("app-region-drag relative flex h-12 select-none items-center pr-3",xn),style:Ws,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:bn}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ks}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[pt?t.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:pt.title}),pt.subtitle?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:pt.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:dt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Fm,{align:"start",children:t.jsx("button",{type:"button",className:dt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[ot?t.jsxs("form",{ref:je,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:D=>{D.preventDefault(),Ye()},children:[t.jsx("input",{value:Wt,onChange:D=>St(D.target.value),autoFocus:!0,onKeyDown:D=>{D.stopPropagation(),D.key==="Escape"&&et(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>et(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":Ze}),kt?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?t.jsx("span",{className:"truncate",children:De}):null,Fe?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:Fe})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:h&&!b&&!ot?t.jsxs(Pt,{open:it,onOpenChange:vt,onOpenChangeComplete:D=>{!D&&bt.current&&(bt.current=!1,Le())},children:[t.jsx(Mt,{asChild:!0,children:t.jsx(Me,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(R,{name:"more",className:"size-4"})})}),t.jsxs(Tt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(rt,{onClick:()=>{bt.current=!0},children:[t.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(rt,{onClick:ct,children:[t.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(rt,{onClick:ts,disabled:!qe,children:[t.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>{At()},children:[t.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>Pe("archive"),children:[t.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(rt,{className:"text-destructive focus:text-destructive",onClick:()=>Pe("delete"),children:[t.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Ht.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ht.map(D=>Cs(D))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(xa,{}),Bt?t.jsx(gi,{projectRef:Bt.projectRef,directory:Bt.directory,className:"mr-1"}):null,t.jsx(mf,{visible:Xn,title:b?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:cs,className:$(dt,"mr-1"),Icon:"picture-in-picture-2"}),Jn,t.jsx(Lc,{visible:U})]})]})]}),qs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[j&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:bn}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ks}})]}),!j&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:xt,className:$(ce,st==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):W?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Gs,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&W&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!W||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!N&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:Ht.map(D=>{const ae=u===D.id,we=D.icon==="diff",Ue=we?null:D.icon;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(Nt(),tt()),f(D.id)},"aria-label":D.label,"aria-selected":ae,role:"tab",className:$(ce,"relative rounded-lg",st===D.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[we?t.jsx(hi,{className:"h-5 w-5"}):Ue?t.jsx(R,{name:Ue,className:"h-5 w-5"}):null,D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:D.badge}),D.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:C.map(D=>{const ae=r&&o===D.id;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(Nt(),tt()),k(!1),a?.(D.id)},"aria-label":D.label,"aria-selected":ae,role:"tab",className:$(ce,"relative rounded-lg",ae&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:D.icon,className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})}),t.jsx(hf,{open:y,onOpenChange:k,currentSessionId:h,effectiveDirectory:Se||null,isNewSessionDraftOpen:b})]}),Bt&&t.jsx(gi,{projectRef:Bt.projectRef,directory:Bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!N?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ds,className:$(ce,"relative",st==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),yn=$("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:M,className:yn,style:{"--padding-scale":"1"},children:A?qs():Ys()}),t.jsx(Mm,{action:ye,onClose:()=>Pe(null),sessionTitle:Ze,onConfirm:()=>{Ot()}}),t.jsx(ca,{open:ge,onOpenChange:xe,info:re,downloading:!1,downloaded:!1,progress:null,error:Be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},bi="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Om="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Fg=()=>{const e=le(h=>h.isSidebarOpen),s=le(h=>h.toggleSidebar),n=le(h=>h.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=Xr(Bn("toggle_sidebar",n)),l=Di(),{enabled:c}=qr(),d=!e,u=l,f=d||u,p=u,b=i.useCallback(()=>{on("desktop_show_app_menu").catch(h=>{console.warn("[titlebar] failed to open app menu",h)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const h=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},g=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const m=o.current,v=r.current;if(!m||!v){h(0),g(0);return}const x=()=>{const w=Math.max(m.getBoundingClientRect().width,m.scrollWidth);h(w),g(v.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(x);return I.observe(m),I.observe(v),()=>{I.disconnect()}},[p]),f?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:$(bi,"shrink-0"),children:t.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,d?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:$(c?Om:bi,"shrink-0"),children:t.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},xi=200,Lm="cubic-bezier(0.22, 1, 0.36, 1)",Og=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),xi);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${xi}ms ${Lm}`}},Lg=()=>{Li()},Bg=e=>{Ee.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),fe.getState().clearAll(),Li(),Fs.getState().resetForRuntimeSwitch(),Bc.getState().resetForRuntimeSwitch(),_c.getState().resetForRuntimeSwitch(),Uc(),zc.getState().resetForRuntimeSwitch(),Ut.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ht.getState().resetForRuntimeSwitch(),$c(),Gc(),Vd.getState().reset(),yd.getState().resetForRuntimeSwitch(),Ai.getState().resetForRuntimeSwitch(e.runtimeKey),Nr.getState().resetForRuntimeSwitch(e.runtimeKey),ys.getState().resetForRuntimeSwitch(e.runtimeKey),Jf.getState().resetForRuntimeSwitch(),ft.getState().resetForRuntimeSwitch(e.runtimeKey),wd.getState().resetForRuntimeSwitch(e.runtimeKey),Ee.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=le.getState();Or({sessionId:Ee.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0})};export{of as $,Ag as A,Mg as B,kg as C,ii as D,bu as E,ig as F,ng as G,Tg as H,fs as I,iu as J,hs as K,ag as L,ba as M,_u as N,yg as O,Tu as P,cg as Q,Cg as R,Ng as S,Dg as T,gg as U,ca as V,sg as W,to as X,pg as Y,Bu as Z,fa as _,hf as a,Mu as a0,Uu as a1,pn as a2,da as a3,mn as a4,an as a5,Fu as a6,dg as a7,Ou as a8,xg as a9,Sg as aa,vg as ab,zu as ac,bg as ad,wg as ae,jg as af,lg as ag,ug as ah,fg as ai,hg as aj,ef as ak,mg as al,yu as am,Lu as an,wu as ao,eg as ap,en as b,mp as c,Ig as d,On as e,Og as f,Rg as g,Pg as h,xp as i,Fg as j,Bg as k,rg as l,og as m,tg as n,Zm as o,so as p,no as q,Lg as r,Eg as s,ro as t,uf as u,Ms as v,ga as w,af as x,lf as y,Ko as z};